context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Install;
using Umbraco.Cms.Core.IO;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.Install
{
/// <inheritdoc />
public class FilePermissionHelper : IFilePermissionHelper
{
// ensure that these directories exist and Umbraco can write to them
private readonly string[] _permissionDirs;
private readonly string[] _packagesPermissionsDirs;
// ensure Umbraco can write to these files (the directories must exist)
private readonly string[] _permissionFiles = Array.Empty<string>();
private readonly GlobalSettings _globalSettings;
private readonly IIOHelper _ioHelper;
private readonly IHostingEnvironment _hostingEnvironment;
private string _basePath;
/// <summary>
/// Initializes a new instance of the <see cref="FilePermissionHelper"/> class.
/// </summary>
public FilePermissionHelper(IOptions<GlobalSettings> globalSettings, IIOHelper ioHelper, IHostingEnvironment hostingEnvironment)
{
_globalSettings = globalSettings.Value;
_ioHelper = ioHelper;
_hostingEnvironment = hostingEnvironment;
_basePath = hostingEnvironment.MapPathContentRoot("/");
_permissionDirs = new[]
{
hostingEnvironment.MapPathWebRoot(_globalSettings.UmbracoCssPath),
hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Config),
hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Data),
hostingEnvironment.MapPathWebRoot(_globalSettings.UmbracoMediaPhysicalRootPath),
hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Preview)
};
_packagesPermissionsDirs = new[]
{
hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Bin),
hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Umbraco),
hostingEnvironment.MapPathWebRoot(_globalSettings.UmbracoPath),
hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Packages)
};
}
/// <inheritdoc/>
public bool RunFilePermissionTestSuite(out Dictionary<FilePermissionTest, IEnumerable<string>> report)
{
report = new Dictionary<FilePermissionTest, IEnumerable<string>>();
EnsureDirectories(_permissionDirs, out IEnumerable<string> errors);
report[FilePermissionTest.FolderCreation] = errors.ToList();
EnsureDirectories(_packagesPermissionsDirs, out errors);
report[FilePermissionTest.FileWritingForPackages] = errors.ToList();
EnsureFiles(_permissionFiles, out errors);
report[FilePermissionTest.FileWriting] = errors.ToList();
EnsureCanCreateSubDirectory(_hostingEnvironment.MapPathWebRoot(_globalSettings.UmbracoMediaPhysicalRootPath), out errors);
report[FilePermissionTest.MediaFolderCreation] = errors.ToList();
return report.Sum(x => x.Value.Count()) == 0;
}
private bool EnsureDirectories(string[] dirs, out IEnumerable<string> errors, bool writeCausesRestart = false)
{
List<string> temp = null;
var success = true;
foreach (var dir in dirs)
{
// we don't want to create/ship unnecessary directories, so
// here we just ensure we can access the directory, not create it
var tryAccess = TryAccessDirectory(dir, !writeCausesRestart);
if (tryAccess)
{
continue;
}
if (temp == null)
{
temp = new List<string>();
}
temp.Add(dir.TrimStart(_basePath));
success = false;
}
errors = success ? Enumerable.Empty<string>() : temp;
return success;
}
private bool EnsureFiles(string[] files, out IEnumerable<string> errors)
{
List<string> temp = null;
var success = true;
foreach (var file in files)
{
var canWrite = TryWriteFile(file);
if (canWrite)
{
continue;
}
if (temp == null)
{
temp = new List<string>();
}
temp.Add(file.TrimStart(_basePath));
success = false;
}
errors = success ? Enumerable.Empty<string>() : temp;
return success;
}
private bool EnsureCanCreateSubDirectory(string dir, out IEnumerable<string> errors)
=> EnsureCanCreateSubDirectories(new[] { dir }, out errors);
private bool EnsureCanCreateSubDirectories(IEnumerable<string> dirs, out IEnumerable<string> errors)
{
List<string> temp = null;
var success = true;
foreach (var dir in dirs)
{
var canCreate = TryCreateSubDirectory(dir);
if (canCreate)
{
continue;
}
if (temp == null)
{
temp = new List<string>();
}
temp.Add(dir);
success = false;
}
errors = success ? Enumerable.Empty<string>() : temp;
return success;
}
// tries to create a sub-directory
// if successful, the sub-directory is deleted
// creates the directory if needed - does not delete it
private bool TryCreateSubDirectory(string dir)
{
try
{
var path = Path.Combine(dir, _ioHelper.CreateRandomFileName());
Directory.CreateDirectory(path);
Directory.Delete(path);
return true;
}
catch
{
return false;
}
}
// tries to create a file
// if successful, the file is deleted
//
// or
//
// use the ACL APIs to avoid creating files
//
// if the directory does not exist, do nothing & success
private bool TryAccessDirectory(string dirPath, bool canWrite)
{
try
{
if (Directory.Exists(dirPath) == false)
{
return true;
}
if (canWrite)
{
var filePath = dirPath + "/" + _ioHelper.CreateRandomFileName() + ".tmp";
File.WriteAllText(filePath, "This is an Umbraco internal test file. It is safe to delete it.");
File.Delete(filePath);
return true;
}
return HasWritePermission(dirPath);
}
catch
{
return false;
}
}
private bool HasWritePermission(string path)
{
var writeAllow = false;
var writeDeny = false;
var accessControlList = new DirectorySecurity(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
AuthorizationRuleCollection accessRules;
try
{
accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
}
catch (Exception)
{
// This is not 100% accurate because it could turn out that the current user doesn't
// have access to read the current permissions but does have write access.
// I think this is an edge case however
return false;
}
foreach (FileSystemAccessRule rule in accessRules)
{
if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write)
{
continue;
}
if (rule.AccessControlType == AccessControlType.Allow)
{
writeAllow = true;
}
else if (rule.AccessControlType == AccessControlType.Deny)
{
writeDeny = true;
}
}
return writeAllow && writeDeny == false;
}
// tries to write into a file
// fails if the directory does not exist
private bool TryWriteFile(string file)
{
try
{
var path = file;
File.AppendText(path).Close();
return true;
}
catch
{
return false;
}
}
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
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.Runtime.InteropServices;
using System.Xml.Serialization;
namespace OpenTK.Math
{
/// <summary>Represents a 4D vector using four double-precision floating-point numbers.</summary>
[Obsolete("OpenTK.Math functions have been moved to the root OpenTK namespace (reason: XNA compatibility")]
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector4d : IEquatable<Vector4d>
{
#region Fields
/// <summary>
/// The X component of the Vector4d.
/// </summary>
public double X;
/// <summary>
/// The Y component of the Vector4d.
/// </summary>
public double Y;
/// <summary>
/// The Z component of the Vector4d.
/// </summary>
public double Z;
/// <summary>
/// The W component of the Vector4d.
/// </summary>
public double W;
/// <summary>
/// Defines a unit-length Vector4d that points towards the X-axis.
/// </summary>
public static Vector4d UnitX = new Vector4d(1, 0, 0, 0);
/// <summary>
/// Defines a unit-length Vector4d that points towards the Y-axis.
/// </summary>
public static Vector4d UnitY = new Vector4d(0, 1, 0, 0);
/// <summary>
/// Defines a unit-length Vector4d that points towards the Z-axis.
/// </summary>
public static Vector4d UnitZ = new Vector4d(0, 0, 1, 0);
/// <summary>
/// Defines a unit-length Vector4d that points towards the W-axis.
/// </summary>
public static Vector4d UnitW = new Vector4d(0, 0, 0, 1);
/// <summary>
/// Defines a zero-length Vector4d.
/// </summary>
public static Vector4d Zero = new Vector4d(0, 0, 0, 0);
/// <summary>
/// Defines an instance with all components set to 1.
/// </summary>
public static readonly Vector4d One = new Vector4d(1, 1, 1, 1);
/// <summary>
/// Defines the size of the Vector4d struct in bytes.
/// </summary>
public static readonly int SizeInBytes = Marshal.SizeOf(new Vector4d());
#endregion
#region Constructors
/// <summary>
/// Constructs a new Vector4d.
/// </summary>
/// <param name="x">The x component of the Vector4d.</param>
/// <param name="y">The y component of the Vector4d.</param>
/// <param name="z">The z component of the Vector4d.</param>
/// <param name="w">The w component of the Vector4d.</param>
public Vector4d(double x, double y, double z, double w)
{
X = x;
Y = y;
Z = z;
W = w;
}
/// <summary>
/// Constructs a new Vector4d from the given Vector2d.
/// </summary>
/// <param name="v">The Vector2d to copy components from.</param>
public Vector4d(Vector2d v)
{
X = v.X;
Y = v.Y;
Z = 0.0f;
W = 0.0f;
}
/// <summary>
/// Constructs a new Vector4d from the given Vector3d.
/// </summary>
/// <param name="v">The Vector3d to copy components from.</param>
public Vector4d(Vector3d v)
{
X = v.X;
Y = v.Y;
Z = v.Z;
W = 0.0f;
}
/// <summary>
/// Constructs a new Vector4d from the specified Vector3d and w component.
/// </summary>
/// <param name="v">The Vector3d to copy components from.</param>
/// <param name="w">The w component of the new Vector4.</param>
public Vector4d(Vector3 v, double w)
{
X = v.X;
Y = v.Y;
Z = v.Z;
W = w;
}
/// <summary>
/// Constructs a new Vector4d from the given Vector4d.
/// </summary>
/// <param name="v">The Vector4d to copy components from.</param>
public Vector4d(Vector4d v)
{
X = v.X;
Y = v.Y;
Z = v.Z;
W = v.W;
}
#endregion
#region Public Members
#region Instance
#region public void Add()
/// <summary>Add the Vector passed as parameter to this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
public void Add(Vector4d right)
{
this.X += right.X;
this.Y += right.Y;
this.Z += right.Z;
this.W += right.W;
}
/// <summary>Add the Vector passed as parameter to this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[CLSCompliant(false)]
public void Add(ref Vector4d right)
{
this.X += right.X;
this.Y += right.Y;
this.Z += right.Z;
this.W += right.W;
}
#endregion public void Add()
#region public void Sub()
/// <summary>Subtract the Vector passed as parameter from this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
public void Sub(Vector4d right)
{
this.X -= right.X;
this.Y -= right.Y;
this.Z -= right.Z;
this.W -= right.W;
}
/// <summary>Subtract the Vector passed as parameter from this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[CLSCompliant(false)]
public void Sub(ref Vector4d right)
{
this.X -= right.X;
this.Y -= right.Y;
this.Z -= right.Z;
this.W -= right.W;
}
#endregion public void Sub()
#region public void Mult()
/// <summary>Multiply this instance by a scalar.</summary>
/// <param name="f">Scalar operand.</param>
public void Mult(double f)
{
this.X *= f;
this.Y *= f;
this.Z *= f;
this.W *= f;
}
#endregion public void Mult()
#region public void Div()
/// <summary>Divide this instance by a scalar.</summary>
/// <param name="f">Scalar operand.</param>
public void Div(double f)
{
double mult = 1.0 / f;
this.X *= mult;
this.Y *= mult;
this.Z *= mult;
this.W *= mult;
}
#endregion public void Div()
#region public double Length
/// <summary>
/// Gets the length (magnitude) of the vector.
/// </summary>
/// <see cref="LengthFast"/>
/// <seealso cref="LengthSquared"/>
public double Length
{
get
{
return (double)System.Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
}
}
#endregion
#region public double LengthFast
/// <summary>
/// Gets an approximation of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property uses an approximation of the square root function to calculate vector magnitude, with
/// an upper error bound of 0.001.
/// </remarks>
/// <see cref="Length"/>
/// <seealso cref="LengthSquared"/>
public double LengthFast
{
get
{
return 1.0f / MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z + W * W);
}
}
#endregion
#region public double LengthSquared
/// <summary>
/// Gets the square of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property avoids the costly square root operation required by the Length property. This makes it more suitable
/// for comparisons.
/// </remarks>
/// <see cref="Length"/>
public double LengthSquared
{
get
{
return X * X + Y * Y + Z * Z + W * W;
}
}
#endregion
#region public void Normalize()
/// <summary>
/// Scales the Vector4d to unit length.
/// </summary>
public void Normalize()
{
double scale = 1.0f / this.Length;
X *= scale;
Y *= scale;
Z *= scale;
W *= scale;
}
#endregion
#region public void NormalizeFast()
/// <summary>
/// Scales the Vector4d to approximately unit length.
/// </summary>
public void NormalizeFast()
{
double scale = Functions.InverseSqrtFast(X * X + Y * Y + Z * Z + W * W);
X *= scale;
Y *= scale;
Z *= scale;
W *= scale;
}
#endregion
#region public void Scale()
/// <summary>
/// Scales the current Vector4d by the given amounts.
/// </summary>
/// <param name="sx">The scale of the X component.</param>
/// <param name="sy">The scale of the Y component.</param>
/// <param name="sz">The scale of the Z component.</param>
/// <param name="sw">The scale of the Z component.</param>
public void Scale(double sx, double sy, double sz, double sw)
{
this.X = X * sx;
this.Y = Y * sy;
this.Z = Z * sz;
this.W = W * sw;
}
/// <summary>Scales this instance by the given parameter.</summary>
/// <param name="scale">The scaling of the individual components.</param>
public void Scale(Vector4d scale)
{
this.X *= scale.X;
this.Y *= scale.Y;
this.Z *= scale.Z;
this.W *= scale.W;
}
/// <summary>Scales this instance by the given parameter.</summary>
/// <param name="scale">The scaling of the individual components.</param>
[CLSCompliant(false)]
public void Scale(ref Vector4d scale)
{
this.X *= scale.X;
this.Y *= scale.Y;
this.Z *= scale.Z;
this.W *= scale.W;
}
#endregion public void Scale()
#endregion
#region Static
#region Add
/// <summary>
/// Add two Vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>Result of addition</returns>
public static Vector4d Add(Vector4d a, Vector4d b)
{
a.X += b.X;
a.Y += b.Y;
a.Z += b.Z;
a.W += b.W;
return a;
}
/// <summary>
/// Add two Vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">Result of addition</param>
public static void Add(ref Vector4d a, ref Vector4d b, out Vector4d result)
{
result.X = a.X + b.X;
result.Y = a.Y + b.Y;
result.Z = a.Z + b.Z;
result.W = a.W + b.W;
}
#endregion
#region Sub
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>Result of subtraction</returns>
public static Vector4d Sub(Vector4d a, Vector4d b)
{
a.X -= b.X;
a.Y -= b.Y;
a.Z -= b.Z;
a.W -= b.W;
return a;
}
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">Result of subtraction</param>
public static void Sub(ref Vector4d a, ref Vector4d b, out Vector4d result)
{
result.X = a.X - b.X;
result.Y = a.Y - b.Y;
result.Z = a.Z - b.Z;
result.W = a.W - b.W;
}
#endregion
#region Mult
/// <summary>
/// Multiply a vector and a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <returns>Result of the multiplication</returns>
public static Vector4d Mult(Vector4d a, double f)
{
a.X *= f;
a.Y *= f;
a.Z *= f;
a.W *= f;
return a;
}
/// <summary>
/// Multiply a vector and a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <param name="result">Result of the multiplication</param>
public static void Mult(ref Vector4d a, double f, out Vector4d result)
{
result.X = a.X * f;
result.Y = a.Y * f;
result.Z = a.Z * f;
result.W = a.W * f;
}
#endregion
#region Div
/// <summary>
/// Divide a vector by a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <returns>Result of the division</returns>
public static Vector4d Div(Vector4d a, double f)
{
double mult = 1.0f / f;
a.X *= mult;
a.Y *= mult;
a.Z *= mult;
a.W *= mult;
return a;
}
/// <summary>
/// Divide a vector by a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <param name="result">Result of the division</param>
public static void Div(ref Vector4d a, double f, out Vector4d result)
{
double mult = 1.0f / f;
result.X = a.X * mult;
result.Y = a.Y * mult;
result.Z = a.Z * mult;
result.W = a.W * mult;
}
#endregion
#region Min
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise minimum</returns>
public static Vector4d Min(Vector4d a, Vector4d b)
{
a.X = a.X < b.X ? a.X : b.X;
a.Y = a.Y < b.Y ? a.Y : b.Y;
a.Z = a.Z < b.Z ? a.Z : b.Z;
a.W = a.W < b.W ? a.W : b.W;
return a;
}
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise minimum</param>
public static void Min(ref Vector4d a, ref Vector4d b, out Vector4d result)
{
result.X = a.X < b.X ? a.X : b.X;
result.Y = a.Y < b.Y ? a.Y : b.Y;
result.Z = a.Z < b.Z ? a.Z : b.Z;
result.W = a.W < b.W ? a.W : b.W;
}
#endregion
#region Max
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise maximum</returns>
public static Vector4d Max(Vector4d a, Vector4d b)
{
a.X = a.X > b.X ? a.X : b.X;
a.Y = a.Y > b.Y ? a.Y : b.Y;
a.Z = a.Z > b.Z ? a.Z : b.Z;
a.W = a.W > b.W ? a.W : b.W;
return a;
}
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise maximum</param>
public static void Max(ref Vector4d a, ref Vector4d b, out Vector4d result)
{
result.X = a.X > b.X ? a.X : b.X;
result.Y = a.Y > b.Y ? a.Y : b.Y;
result.Z = a.Z > b.Z ? a.Z : b.Z;
result.W = a.W > b.W ? a.W : b.W;
}
#endregion
#region Clamp
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <returns>The clamped vector</returns>
public static Vector4d Clamp(Vector4d vec, Vector4d min, Vector4d max)
{
vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X;
vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y;
vec.Z = vec.X < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z;
vec.W = vec.Y < min.W ? min.W : vec.W > max.W ? max.W : vec.W;
return vec;
}
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <param name="result">The clamped vector</param>
public static void Clamp(ref Vector4d vec, ref Vector4d min, ref Vector4d max, out Vector4d result)
{
result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X;
result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y;
result.Z = vec.X < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z;
result.W = vec.Y < min.W ? min.W : vec.W > max.W ? max.W : vec.W;
}
#endregion
#region Normalize
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <returns>The normalized vector</returns>
public static Vector4d Normalize(Vector4d vec)
{
double scale = 1.0f / vec.Length;
vec.X *= scale;
vec.Y *= scale;
vec.Z *= scale;
vec.W *= scale;
return vec;
}
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <param name="result">The normalized vector</param>
public static void Normalize(ref Vector4d vec, out Vector4d result)
{
double scale = 1.0f / vec.Length;
result.X = vec.X * scale;
result.Y = vec.Y * scale;
result.Z = vec.Z * scale;
result.W = vec.W * scale;
}
#endregion
#region NormalizeFast
/// <summary>
/// Scale a vector to approximately unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <returns>The normalized vector</returns>
public static Vector4d NormalizeFast(Vector4d vec)
{
double scale = Functions.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z + vec.W * vec.W);
vec.X *= scale;
vec.Y *= scale;
vec.Z *= scale;
vec.W *= scale;
return vec;
}
/// <summary>
/// Scale a vector to approximately unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <param name="result">The normalized vector</param>
public static void NormalizeFast(ref Vector4d vec, out Vector4d result)
{
double scale = Functions.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z + vec.W * vec.W);
result.X = vec.X * scale;
result.Y = vec.Y * scale;
result.Z = vec.Z * scale;
result.W = vec.W * scale;
}
#endregion
#region Dot
/// <summary>
/// Calculate the dot product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The dot product of the two inputs</returns>
public static double Dot(Vector4d left, Vector4d right)
{
return left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W;
}
/// <summary>
/// Calculate the dot product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <param name="result">The dot product of the two inputs</param>
public static void Dot(ref Vector4d left, ref Vector4d right, out double result)
{
result = left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W;
}
#endregion
#region Lerp
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns>
public static Vector4d Lerp(Vector4d a, Vector4d b, double blend)
{
a.X = blend * (b.X - a.X) + a.X;
a.Y = blend * (b.Y - a.Y) + a.Y;
a.Z = blend * (b.Z - a.Z) + a.Z;
a.W = blend * (b.W - a.W) + a.W;
return a;
}
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param>
public static void Lerp(ref Vector4d a, ref Vector4d b, double blend, out Vector4d result)
{
result.X = blend * (b.X - a.X) + a.X;
result.Y = blend * (b.Y - a.Y) + a.Y;
result.Z = blend * (b.Z - a.Z) + a.Z;
result.W = blend * (b.W - a.W) + a.W;
}
#endregion
#region Barycentric
/// <summary>
/// Interpolate 3 Vectors using Barycentric coordinates
/// </summary>
/// <param name="a">First input Vector</param>
/// <param name="b">Second input Vector</param>
/// <param name="c">Third input Vector</param>
/// <param name="u">First Barycentric Coordinate</param>
/// <param name="v">Second Barycentric Coordinate</param>
/// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns>
public static Vector4d BaryCentric(Vector4d a, Vector4d b, Vector4d c, double u, double v)
{
return a + u * (b - a) + v * (c - a);
}
/// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary>
/// <param name="a">First input Vector.</param>
/// <param name="b">Second input Vector.</param>
/// <param name="c">Third input Vector.</param>
/// <param name="u">First Barycentric Coordinate.</param>
/// <param name="v">Second Barycentric Coordinate.</param>
/// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param>
public static void BaryCentric(ref Vector4d a, ref Vector4d b, ref Vector4d c, float u, float v, out Vector4d result)
{
result = a; // copy
Vector4d temp = b; // copy
temp.Sub(ref a);
temp.Mult(u);
result.Add(ref temp);
temp = c; // copy
temp.Sub(ref a);
temp.Mult(v);
result.Add(ref temp);
}
#endregion
#region Transform
/// <summary>Transform a Vector by the given Matrix</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector4d Transform(Vector4d vec, Matrix4d mat)
{
Vector4d result;
result.X = Vector4d.Dot(vec, mat.Column0);
result.Y = Vector4d.Dot(vec, mat.Column1);
result.Z = Vector4d.Dot(vec, mat.Column2);
result.W = Vector4d.Dot(vec, mat.Column3);
return result;
}
/// <summary>Transform a Vector by the given Matrix</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void Transform(ref Vector4d vec, ref Matrix4d mat, out Vector4d result)
{
result.X = vec.X * mat.Row0.X +
vec.Y * mat.Row1.X +
vec.Z * mat.Row2.X +
vec.W * mat.Row3.X;
result.Y = vec.X * mat.Row0.Y +
vec.Y * mat.Row1.Y +
vec.Z * mat.Row2.Y +
vec.W * mat.Row3.Y;
result.Z = vec.X * mat.Row0.Z +
vec.Y * mat.Row1.Z +
vec.Z * mat.Row2.Z +
vec.W * mat.Row3.Z;
result.W = vec.X * mat.Row0.W +
vec.Y * mat.Row1.W +
vec.Z * mat.Row2.W +
vec.W * mat.Row3.W;
}
#endregion
#endregion
#region Swizzle
/// <summary>
/// Gets or sets an OpenTK.Vector2d with the X and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2d Xy { get { return new Vector2d(X, Y); } set { X = value.X; Y = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3d with the X, Y and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3d Xyz { get { return new Vector3d(X, Y, Z); } set { X = value.X; Y = value.Y; Z = value.Z; } }
#endregion
#region Operators
public static Vector4d operator +(Vector4d left, Vector4d right)
{
left.X += right.X;
left.Y += right.Y;
left.Z += right.Z;
left.W += right.W;
return left;
}
public static Vector4d operator -(Vector4d left, Vector4d right)
{
left.X -= right.X;
left.Y -= right.Y;
left.Z -= right.Z;
left.W -= right.W;
return left;
}
public static Vector4d operator -(Vector4d vec)
{
vec.X = -vec.X;
vec.Y = -vec.Y;
vec.Z = -vec.Z;
vec.W = -vec.W;
return vec;
}
public static Vector4d operator *(Vector4d vec, double f)
{
vec.X *= f;
vec.Y *= f;
vec.Z *= f;
vec.W *= f;
return vec;
}
public static Vector4d operator *(double f, Vector4d vec)
{
vec.X *= f;
vec.Y *= f;
vec.Z *= f;
vec.W *= f;
return vec;
}
public static Vector4d operator /(Vector4d vec, double f)
{
double mult = 1.0f / f;
vec.X *= mult;
vec.Y *= mult;
vec.Z *= mult;
vec.W *= mult;
return vec;
}
public static bool operator ==(Vector4d left, Vector4d right)
{
return left.Equals(right);
}
public static bool operator !=(Vector4d left, Vector4d right)
{
return !left.Equals(right);
}
[CLSCompliant(false)]
unsafe public static explicit operator double*(Vector4d v)
{
return &v.X;
}
public static explicit operator IntPtr(Vector4d v)
{
unsafe
{
return (IntPtr)(&v.X);
}
}
/// <summary>Converts OpenTK.Vector4 to OpenTK.Vector4d.</summary>
/// <param name="v4">The Vector4 to convert.</param>
/// <returns>The resulting Vector4d.</returns>
public static explicit operator Vector4d(Vector4 v4)
{
return new Vector4d(v4.X, v4.Y, v4.Z, v4.W);
}
/// <summary>Converts OpenTK.Vector4d to OpenTK.Vector4.</summary>
/// <param name="v4d">The Vector4d to convert.</param>
/// <returns>The resulting Vector4.</returns>
public static explicit operator Vector4(Vector4d v4d)
{
return new Vector4((float)v4d.X, (float)v4d.Y, (float)v4d.Z, (float)v4d.W);
}
#endregion
#region Overrides
#region public override string ToString()
/// <summary>
/// Returns a System.String that represents the current Vector4d.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("({0}, {1}, {2}, {3})", X, Y, Z, W);
}
#endregion
#region public override int GetHashCode()
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode();
}
#endregion
#region public override bool Equals(object obj)
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (!(obj is Vector4d))
return false;
return this.Equals((Vector4d)obj);
}
#endregion
#endregion
#endregion
#region IEquatable<Vector4d> Members
/// <summary>Indicates whether the current vector is equal to another vector.</summary>
/// <param name="other">A vector to compare with this vector.</param>
/// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns>
public bool Equals(Vector4d other)
{
return
X == other.X &&
Y == other.Y &&
Z == other.Z &&
W == other.W;
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Collections;
using UnityEngine;
/*
* please don't use this code for sell a asset
* user for free
* developed by Poya @ http://gamesforsoul.com/
* BLOB support by Jonathan Derrough @ http://jderrough.blogspot.com/
* Modify and structure by Santiago Bustamante @ busta117@gmail.com
* Android compatibility by Thomas Olsen @ olsen.thomas@gmail.com
*
* */
public class SqliteException : Exception
{
public SqliteException (string message) : base(message)
{
}
}
public class SqliteDatabase
{
private bool CanExQuery = true;
const int SQLITE_OK = 0;
const int SQLITE_ROW = 100;
const int SQLITE_DONE = 101;
const int SQLITE_INTEGER = 1;
const int SQLITE_FLOAT = 2;
const int SQLITE_TEXT = 3;
const int SQLITE_BLOB = 4;
const int SQLITE_NULL = 5;
[DllImport("sqlite3", EntryPoint = "sqlite3_open")]
private static extern int sqlite3_open (string filename, out IntPtr db);
[DllImport("sqlite3", EntryPoint = "sqlite3_close")]
private static extern int sqlite3_close (IntPtr db);
[DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2")]
private static extern int sqlite3_prepare_v2 (IntPtr db, string zSql, int nByte, out IntPtr ppStmpt, IntPtr pzTail);
[DllImport("sqlite3", EntryPoint = "sqlite3_step")]
private static extern int sqlite3_step (IntPtr stmHandle);
[DllImport("sqlite3", EntryPoint = "sqlite3_finalize")]
private static extern int sqlite3_finalize (IntPtr stmHandle);
[DllImport("sqlite3", EntryPoint = "sqlite3_errmsg")]
private static extern IntPtr sqlite3_errmsg (IntPtr db);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_count")]
private static extern int sqlite3_column_count (IntPtr stmHandle);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_name")]
private static extern IntPtr sqlite3_column_name (IntPtr stmHandle, int iCol);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_type")]
private static extern int sqlite3_column_type (IntPtr stmHandle, int iCol);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_int")]
private static extern int sqlite3_column_int (IntPtr stmHandle, int iCol);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_text")]
private static extern IntPtr sqlite3_column_text (IntPtr stmHandle, int iCol);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_double")]
private static extern double sqlite3_column_double (IntPtr stmHandle, int iCol);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_blob")]
private static extern IntPtr sqlite3_column_blob (IntPtr stmHandle, int iCol);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes")]
private static extern int sqlite3_column_bytes (IntPtr stmHandle, int iCol);
private IntPtr _connection;
private bool IsConnectionOpen { get; set; }
private string pathDB;
#region Public Methods
/// <summary>
/// Initializes a new instance of the <see cref="SqliteDatabase"/> class.
/// </summary>
/// <param name='dbName'>
/// Data Base name. (the file needs exist in the streamingAssets folder)
/// </param>
public SqliteDatabase (string dbName)
{
pathDB = System.IO.Path.Combine (Application.persistentDataPath, dbName);
//original path
string sourcePath = System.IO.Path.Combine (Application.streamingAssetsPath, dbName);
//if DB does not exist in persistent data folder (folder "Documents" on iOS) or source DB is newer then copy it
if (!System.IO.File.Exists (pathDB) || (System.IO.File.GetLastWriteTimeUtc(sourcePath) > System.IO.File.GetLastWriteTimeUtc(pathDB))) {
if (sourcePath.Contains ("://")) {
// Android
WWW www = new WWW (sourcePath);
// Wait for download to complete - not pretty at all but easy hack for now
// and it would not take long since the data is on the local device.
while (!www.isDone) {;}
if (String.IsNullOrEmpty(www.error)) {
System.IO.File.WriteAllBytes(pathDB, www.bytes);
} else {
CanExQuery = false;
}
} else {
// Mac, Windows, Iphone
//validate the existens of the DB in the original folder (folder "streamingAssets")
if (System.IO.File.Exists (sourcePath)) {
//copy file - alle systems except Android
System.IO.File.Copy (sourcePath, pathDB, true);
} else {
CanExQuery = false;
Debug.Log ("ERROR: the file DB named " + dbName + " doesn't exist in the StreamingAssets Folder, please copy it there.");
}
}
}
}
private void Open ()
{
this.Open (pathDB);
}
private void Open (string path)
{
if (IsConnectionOpen) {
throw new SqliteException ("There is already an open connection");
}
if (sqlite3_open (path, out _connection) != SQLITE_OK) {
throw new SqliteException ("Could not open database file: " + path);
}
IsConnectionOpen = true;
}
private void Close ()
{
if (IsConnectionOpen) {
sqlite3_close (_connection);
}
IsConnectionOpen = false;
}
/// <summary>
/// Executes a Update, Delete, etc query.
/// </summary>
/// <param name='query'>
/// Query.
/// </param>
/// <exception cref='SqliteException'>
/// Is thrown when the sqlite exception.
/// </exception>
public void ExecuteNonQuery (string query)
{
if (!CanExQuery) {
Debug.Log ("ERROR: Can't execute the query, verify DB origin file");
return;
}
this.Open ();
if (!IsConnectionOpen) {
throw new SqliteException ("SQLite database is not open.");
}
IntPtr stmHandle = Prepare (query);
if (sqlite3_step (stmHandle) != SQLITE_DONE) {
throw new SqliteException ("Could not execute SQL statement.");
}
Finalize (stmHandle);
this.Close ();
}
/// <summary>
/// Executes a query that requires a response (SELECT, etc).
/// </summary>
/// <returns>
/// Dictionary with the response data
/// </returns>
/// <param name='query'>
/// Query.
/// </param>
/// <exception cref='SqliteException'>
/// Is thrown when the sqlite exception.
/// </exception>
public DataTable ExecuteQuery (string query)
{
if (!CanExQuery) {
Debug.Log ("ERROR: Can't execute the query, verify DB origin file");
return null;
}
this.Open ();
if (!IsConnectionOpen) {
throw new SqliteException ("SQLite database is not open.");
}
IntPtr stmHandle = Prepare (query);
int columnCount = sqlite3_column_count (stmHandle);
var dataTable = new DataTable ();
for (int i = 0; i < columnCount; i++) {
string columnName = Marshal.PtrToStringAnsi (sqlite3_column_name (stmHandle, i));
dataTable.Columns.Add (columnName);
}
//populate datatable
while (sqlite3_step(stmHandle) == SQLITE_ROW) {
object[] row = new object[columnCount];
for (int i = 0; i < columnCount; i++) {
switch (sqlite3_column_type (stmHandle, i)) {
case SQLITE_INTEGER:
row [i] = sqlite3_column_int (stmHandle, i);
break;
case SQLITE_TEXT:
IntPtr text = sqlite3_column_text (stmHandle, i);
row [i] = Marshal.PtrToStringAnsi (text);
break;
case SQLITE_FLOAT:
row [i] = sqlite3_column_double (stmHandle, i);
break;
case SQLITE_BLOB:
IntPtr blob = sqlite3_column_blob (stmHandle, i);
int size = sqlite3_column_bytes (stmHandle, i);
byte[] data = new byte[size];
Marshal.Copy (blob, data, 0, size);
row [i] = data;
break;
case SQLITE_NULL:
row [i] = null;
break;
}
}
dataTable.AddRow (row);
}
Finalize (stmHandle);
this.Close ();
return dataTable;
}
public void ExecuteScript (string script)
{
string[] statements = script.Split (';');
foreach (string statement in statements) {
if (!string.IsNullOrEmpty (statement.Trim ())) {
ExecuteNonQuery (statement);
}
}
}
#endregion
#region Private Methods
private IntPtr Prepare (string query)
{
IntPtr stmHandle;
if (sqlite3_prepare_v2 (_connection, query, query.Length, out stmHandle, IntPtr.Zero) != SQLITE_OK) {
IntPtr errorMsg = sqlite3_errmsg (_connection);
throw new SqliteException (Marshal.PtrToStringAnsi (errorMsg));
}
return stmHandle;
}
private void Finalize (IntPtr stmHandle)
{
if (sqlite3_finalize (stmHandle) != SQLITE_OK) {
throw new SqliteException ("Could not finalize SQL statement.");
}
}
#endregion
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Orchard.Caching;
using Orchard.Environment.Configuration;
using Orchard.Environment.Extensions;
using Orchard.Environment.ShellBuilders;
using Orchard.Environment.State;
using Orchard.Environment.Descriptor;
using Orchard.Environment.Descriptor.Models;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Utility.Extensions;
namespace Orchard.Environment {
// All the event handlers that DefaultOrchardHost implements have to be declared in OrchardStarter
public class DefaultOrchardHost : IOrchardHost, IShellSettingsManagerEventHandler, IShellDescriptorManagerEventHandler {
private readonly IHostLocalRestart _hostLocalRestart;
private readonly IShellSettingsManager _shellSettingsManager;
private readonly IShellContextFactory _shellContextFactory;
private readonly IRunningShellTable _runningShellTable;
private readonly IProcessingEngine _processingEngine;
private readonly IExtensionLoaderCoordinator _extensionLoaderCoordinator;
private readonly IExtensionMonitoringCoordinator _extensionMonitoringCoordinator;
private readonly ICacheManager _cacheManager;
private readonly static object _syncLock = new object();
private readonly static object _shellContextsWriteLock = new object();
private IEnumerable<ShellContext> _shellContexts;
private readonly ContextState<IList<ShellSettings>> _tenantsToRestart;
public DefaultOrchardHost(
IShellSettingsManager shellSettingsManager,
IShellContextFactory shellContextFactory,
IRunningShellTable runningShellTable,
IProcessingEngine processingEngine,
IExtensionLoaderCoordinator extensionLoaderCoordinator,
IExtensionMonitoringCoordinator extensionMonitoringCoordinator,
ICacheManager cacheManager,
IHostLocalRestart hostLocalRestart) {
_shellSettingsManager = shellSettingsManager;
_shellContextFactory = shellContextFactory;
_runningShellTable = runningShellTable;
_processingEngine = processingEngine;
_extensionLoaderCoordinator = extensionLoaderCoordinator;
_extensionMonitoringCoordinator = extensionMonitoringCoordinator;
_cacheManager = cacheManager;
_hostLocalRestart = hostLocalRestart;
_tenantsToRestart = new ContextState<IList<ShellSettings>>("DefaultOrchardHost.TenantsToRestart", () => new List<ShellSettings>());
T = NullLocalizer.Instance;
Logger = NullLogger.Instance;
}
public Localizer T { get; set; }
public ILogger Logger { get; set; }
public IList<ShellContext> Current {
get { return BuildCurrent().ToReadOnlyCollection(); }
}
public ShellContext GetShellContext(ShellSettings shellSettings) {
return GetShellContext(shellSettings.Name);
}
public ShellContext GetShellContext(string tenantName) {
return BuildCurrent().SingleOrDefault(shellContext => shellContext.Settings.Name.Equals(tenantName));
}
void IOrchardHost.Initialize() {
Logger.Information("Initializing");
BuildCurrent();
Logger.Information("Initialized");
}
void IOrchardHost.ReloadExtensions() {
DisposeShellContext();
}
void IOrchardHost.BeginRequest() {
Logger.Debug("BeginRequest");
BeginRequest();
}
void IOrchardHost.EndRequest() {
Logger.Debug("EndRequest");
EndRequest();
}
IWorkContextScope IOrchardHost.CreateStandaloneEnvironment(ShellSettings shellSettings) {
Logger.Debug("Creating standalone environment for tenant {0}", shellSettings.Name);
MonitorExtensions();
BuildCurrent();
var shellContext = CreateShellContext(shellSettings);
var workContext = shellContext.LifetimeScope.CreateWorkContextScope();
return new StandaloneEnvironmentWorkContextScopeWrapper(workContext, shellContext);
}
/// <summary>
/// Ensures shells are activated, or re-activated if extensions have changed
/// </summary>
IEnumerable<ShellContext> BuildCurrent() {
if (_shellContexts == null) {
lock (_syncLock) {
if (_shellContexts == null) {
SetupExtensions();
MonitorExtensions();
CreateAndActivateShells();
}
}
}
return _shellContexts;
}
void StartUpdatedShells() {
while (_tenantsToRestart.GetState().Any()) {
var settings = _tenantsToRestart.GetState().First();
_tenantsToRestart.GetState().Remove(settings);
Logger.Debug("Updating shell: " + settings.Name);
lock (_syncLock) {
ActivateShell(settings);
}
}
}
void CreateAndActivateShells() {
Logger.Information("Start creation of shells");
// is there any tenant right now ?
var allSettings = _shellSettingsManager.LoadSettings()
.Where(settings => settings.State == TenantState.Running || settings.State == TenantState.Uninitialized)
.ToArray();
// load all tenants, and activate their shell
if (allSettings.Any()) {
Parallel.ForEach(allSettings, settings => {
try {
var context = CreateShellContext(settings);
ActivateShell(context);
}
catch (Exception e) {
Logger.Error(e, "A tenant could not be started: " + settings.Name);
}
});
}
// no settings, run the Setup
else {
var setupContext = CreateSetupContext();
ActivateShell(setupContext);
}
Logger.Information("Done creating shells");
}
/// <summary>
/// Starts a Shell and registers its settings in RunningShellTable
/// </summary>
private void ActivateShell(ShellContext context) {
Logger.Debug("Activating context for tenant {0}", context.Settings.Name);
context.Shell.Activate();
lock (_shellContextsWriteLock) {
_shellContexts = (_shellContexts ?? Enumerable.Empty<ShellContext>())
.Where(c => c.Settings.Name != context.Settings.Name)
.Concat(new[] { context })
.ToArray();
}
_runningShellTable.Add(context.Settings);
}
/// <summary>
/// Creates a transient shell for the default tenant's setup
/// </summary>
private ShellContext CreateSetupContext() {
Logger.Debug("Creating shell context for root setup");
return _shellContextFactory.CreateSetupContext(new ShellSettings { Name = ShellSettings.DefaultName });
}
/// <summary>
/// Creates a shell context based on shell settings
/// </summary>
private ShellContext CreateShellContext(ShellSettings settings) {
if (settings.State == TenantState.Uninitialized) {
Logger.Debug("Creating shell context for tenant {0} setup", settings.Name);
return _shellContextFactory.CreateSetupContext(settings);
}
Logger.Debug("Creating shell context for tenant {0}", settings.Name);
return _shellContextFactory.CreateShellContext(settings);
}
private void SetupExtensions() {
_extensionLoaderCoordinator.SetupExtensions();
}
private void MonitorExtensions() {
// This is a "fake" cache entry to allow the extension loader coordinator
// notify us (by resetting _current to "null") when an extension has changed
// on disk, and we need to reload new/updated extensions.
_cacheManager.Get("OrchardHost_Extensions",
ctx => {
_extensionMonitoringCoordinator.MonitorExtensions(ctx.Monitor);
_hostLocalRestart.Monitor(ctx.Monitor);
DisposeShellContext();
return "";
});
}
/// <summary>
/// Terminates all active shell contexts, and dispose their scope, forcing
/// them to be reloaded if necessary.
/// </summary>
private void DisposeShellContext() {
Logger.Information("Disposing active shell contexts");
if (_shellContexts != null) {
lock (_syncLock) {
if (_shellContexts != null) {
foreach (var shellContext in _shellContexts) {
shellContext.Shell.Terminate();
shellContext.Dispose();
}
}
}
_shellContexts = null;
}
}
protected virtual void BeginRequest() {
// Ensure all shell contexts are loaded, or need to be reloaded if
// extensions have changed
MonitorExtensions();
BuildCurrent();
StartUpdatedShells();
}
protected virtual void EndRequest() {
// Synchronously process all pending tasks. It's safe to do this at this point
// of the pipeline, as the request transaction has been closed, so creating a new
// environment and transaction for these tasks will behave as expected.)
while (_processingEngine.AreTasksPending()) {
Logger.Debug("Processing pending task");
_processingEngine.ExecuteNextTask();
}
StartUpdatedShells();
}
void IShellSettingsManagerEventHandler.Saved(ShellSettings settings) {
Logger.Debug("Shell saved: " + settings.Name);
// if a tenant has been created
if (settings.State != TenantState.Invalid) {
if (!_tenantsToRestart.GetState().Any(t => t.Name.Equals(settings.Name))) {
Logger.Debug("Adding tenant to restart: " + settings.Name + " " + settings.State);
_tenantsToRestart.GetState().Add(settings);
}
}
}
public void ActivateShell(ShellSettings settings) {
Logger.Debug("Activating shell: " + settings.Name);
// look for the associated shell context
var shellContext = _shellContexts.FirstOrDefault(c => c.Settings.Name == settings.Name);
if (shellContext == null && settings.State == TenantState.Disabled) {
return;
}
// is this is a new tenant ? or is it a tenant waiting for setup ?
if (shellContext == null || settings.State == TenantState.Uninitialized) {
// create the Shell
var context = CreateShellContext(settings);
// activate the Shell
ActivateShell(context);
}
// terminate the shell if the tenant was disabled
else if (settings.State == TenantState.Disabled) {
shellContext.Shell.Terminate();
_runningShellTable.Remove(settings);
// Forcing enumeration with ToArray() so a lazy execution isn't causing issues by accessing the disposed context.
_shellContexts = _shellContexts.Where(shell => shell.Settings.Name != settings.Name).ToArray();
shellContext.Dispose();
}
// reload the shell as its settings have changed
else {
// dispose previous context
shellContext.Shell.Terminate();
var context = _shellContextFactory.CreateShellContext(settings);
// Activate and register modified context.
// Forcing enumeration with ToArray() so a lazy execution isn't causing issues by accessing the disposed shell context.
_shellContexts = _shellContexts.Where(shell => shell.Settings.Name != settings.Name).Union(new[] { context }).ToArray();
shellContext.Dispose();
context.Shell.Activate();
_runningShellTable.Update(settings);
}
}
/// <summary>
/// A feature is enabled/disabled, the tenant needs to be restarted
/// </summary>
void IShellDescriptorManagerEventHandler.Changed(ShellDescriptor descriptor, string tenant) {
if (_shellContexts == null) {
return;
}
Logger.Debug("Shell changed: " + tenant);
var context = _shellContexts.FirstOrDefault(x => x.Settings.Name == tenant);
if (context == null) {
return;
}
// don't restart when tenant is in setup
if (context.Settings.State != TenantState.Running) {
return;
}
// don't flag the tenant if already listed
if (_tenantsToRestart.GetState().Any(x => x.Name == tenant)) {
return;
}
Logger.Debug("Adding tenant to restart: " + tenant);
_tenantsToRestart.GetState().Add(context.Settings);
}
// To be used from CreateStandaloneEnvironment(), also disposes the ShellContext LifetimeScope.
private class StandaloneEnvironmentWorkContextScopeWrapper : IWorkContextScope {
private readonly ShellContext _shellContext;
private readonly IWorkContextScope _workContextScope;
public WorkContext WorkContext {
get { return _workContextScope.WorkContext; }
}
public StandaloneEnvironmentWorkContextScopeWrapper(IWorkContextScope workContextScope, ShellContext shellContext) {
_workContextScope = workContextScope;
_shellContext = shellContext;
}
public TService Resolve<TService>() {
return _workContextScope.Resolve<TService>();
}
public bool TryResolve<TService>(out TService service) {
return _workContextScope.TryResolve<TService>(out service);
}
public void Dispose() {
_workContextScope.Dispose();
_shellContext.Dispose();
}
}
}
}
| |
using System.Diagnostics;
namespace Lucene.Net.Search
{
/*
* 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 Lucene.Net.Util;
using System;
//Used to hold non-generic nested types
public static class FieldValueHitQueue
{
// had to change from internal to public, due to public accessability of FieldValueHitQueue
public class Entry : ScoreDoc
{
public int Slot;
public Entry(int slot, int doc, float score)
: base(doc, score)
{
this.Slot = slot;
}
public override string ToString()
{
return "slot:" + Slot + " " + base.ToString();
}
}
/// <summary> An implementation of <see cref="FieldValueHitQueue" /> which is optimized in case
/// there is just one comparator.
/// </summary>
internal sealed class OneComparatorFieldValueHitQueue<T> : FieldValueHitQueue<T>
where T : FieldValueHitQueue.Entry
{
private int oneReverseMul;
public OneComparatorFieldValueHitQueue(SortField[] fields, int size)
: base(fields, size)
{
if (fields.Length == 0)
{
throw new System.ArgumentException("Sort must contain at least one field");
}
SortField field = fields[0];
SetComparator(0, field.GetComparator(size, 0));
oneReverseMul = field.reverse ? -1 : 1;
ReverseMul[0] = oneReverseMul;
}
/// <summary> Returns whether <c>a</c> is less relevant than <c>b</c>.</summary>
/// <param name="hitA">ScoreDoc</param>
/// <param name="hitB">ScoreDoc</param>
/// <returns><c>true</c> if document <c>a</c> should be sorted after document <c>b</c>.</returns>
public override bool LessThan(T hitA, T hitB)
{
Debug.Assert(hitA != hitB);
Debug.Assert(hitA.Slot != hitB.Slot);
int c = oneReverseMul * FirstComparator.Compare(hitA.Slot, hitB.Slot);
if (c != 0)
{
return c > 0;
}
// avoid random sort order that could lead to duplicates (bug #31241):
return hitA.Doc > hitB.Doc;
}
public override bool LessThan(Entry a, Entry b)
{
return LessThan(a, b);
}
}
/// <summary> An implementation of <see cref="FieldValueHitQueue" /> which is optimized in case
/// there is more than one comparator.
/// </summary>
internal sealed class MultiComparatorsFieldValueHitQueue<T> : FieldValueHitQueue<T>
where T : FieldValueHitQueue.Entry
{
public MultiComparatorsFieldValueHitQueue(SortField[] fields, int size)
: base(fields, size)
{
int numComparators = comparators.Length;
for (int i = 0; i < numComparators; ++i)
{
SortField field = fields[i];
ReverseMul[i] = field.reverse ? -1 : 1;
SetComparator(i, field.GetComparator(size, i));
}
}
public override bool LessThan(T hitA, T hitB)
{
Debug.Assert(hitA != hitB);
Debug.Assert(hitA.Slot != hitB.Slot);
int numComparators = comparators.Length;
for (int i = 0; i < numComparators; ++i)
{
int c = ReverseMul[i] * comparators[i].Compare(hitA.Slot, hitB.Slot);
if (c != 0)
{
// Short circuit
return c > 0;
}
}
// avoid random sort order that could lead to duplicates (bug #31241):
return hitA.Doc > hitB.Doc;
}
public override bool LessThan(Entry a, Entry b)
{
return LessThan(a, b);
}
}
/// <summary> Creates a hit queue sorted by the given list of fields.
///
/// <p/><b>NOTE</b>: The instances returned by this method
/// pre-allocate a full array of length <c>numHits</c>.
///
/// </summary>
/// <param name="fields">SortField array we are sorting by in priority order (highest
/// priority first); cannot be <c>null</c> or empty
/// </param>
/// <param name="size">The number of hits to retain. Must be greater than zero.
/// </param>
/// <throws> IOException </throws>
public static FieldValueHitQueue<T> Create<T>(SortField[] fields, int size)
where T : FieldValueHitQueue.Entry
{
if (fields.Length == 0)
{
throw new ArgumentException("Sort must contain at least one field");
}
if (fields.Length == 1)
{
return new FieldValueHitQueue.OneComparatorFieldValueHitQueue<T>(fields, size);
}
else
{
return new FieldValueHitQueue.MultiComparatorsFieldValueHitQueue<T>(fields, size);
}
}
}
/// <summary>
/// Expert: A hit queue for sorting by hits by terms in more than one field.
/// Uses <code>FieldCache.DEFAULT</code> for maintaining
/// internal term lookup tables.
///
/// @lucene.experimental
/// @since 2.9 </summary>
/// <seealso cref= IndexSearcher#search(Query,Filter,int,Sort) </seealso>
/// <seealso cref= FieldCache </seealso>
public abstract class FieldValueHitQueue<T> : PriorityQueue<T>
where T : FieldValueHitQueue.Entry
{
// prevent instantiation and extension.
internal FieldValueHitQueue(SortField[] fields, int size)
: base(size)
{
// When we get here, fields.length is guaranteed to be > 0, therefore no
// need to check it again.
// All these are required by this class's API - need to return arrays.
// Therefore even in the case of a single comparator, create an array
// anyway.
this.fields = fields;
int numComparators = fields.Length;
comparators = new FieldComparator[numComparators];
reverseMul = new int[numComparators];
}
public virtual FieldComparator[] Comparators
{
get
{
return comparators;
}
}
public virtual int[] ReverseMul
{
get
{
return reverseMul;
}
}
public virtual void SetComparator(int pos, FieldComparator comparator)
{
if (pos == 0)
{
FirstComparator = comparator;
}
comparators[pos] = comparator;
}
/// <summary>
/// Stores the sort criteria being used. </summary>
protected internal readonly SortField[] fields;
protected internal readonly FieldComparator[] comparators; // use setComparator to change this array
protected internal FieldComparator FirstComparator; // this must always be equal to comparators[0]
protected internal readonly int[] reverseMul;
public abstract bool LessThan(FieldValueHitQueue.Entry a, FieldValueHitQueue.Entry b);
/// <summary>
/// Given a queue Entry, creates a corresponding FieldDoc
/// that contains the values used to sort the given document.
/// These values are not the raw values out of the index, but the internal
/// representation of them. this is so the given search hit can be collated by
/// a MultiSearcher with other search hits.
/// </summary>
/// <param name="entry"> The Entry used to create a FieldDoc </param>
/// <returns> The newly created FieldDoc </returns>
/// <seealso cref= IndexSearcher#search(Query,Filter,int,Sort) </seealso>
internal virtual FieldDoc FillFields(FieldValueHitQueue.Entry entry)
{
int n = Comparators.Length;
IComparable[] fields = new IComparable[n];
for (int i = 0; i < n; ++i)
{
fields[i] = Comparators[i].Value(entry.Slot);
}
//if (maxscore > 1.0f) doc.score /= maxscore; // normalize scores
return new FieldDoc(entry.Doc, entry.Score, fields);
}
/// <summary>
/// Returns the SortFields being used by this hit queue. </summary>
internal virtual SortField[] Fields
{
get
{
return fields;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Drawing;
namespace onlyconnect
{
/// <summary>
/// Utility routines for working with mshtml
/// </summary>
public class utils
{
public utils()
{
//
// TODO: Add constructor logic here
//
}
public static string DecodeHRESULT(int hr)
{
switch (hr)
{
case HRESULT.S_OK: return "S_OK";
case HRESULT.S_FALSE: return "S_FALSE";
case HRESULT.E_UNEXPECTED: return "E_UNEXPECTED";
case HRESULT.E_NOTIMPL: return "E_NOTIMPL";
case HRESULT.E_NOINTERFACE: return "E_NOINTERFACE";
case HRESULT.E_INVALIDARG: return "E_INVALIDARG";
case HRESULT.E_FAIL: return "E_FAIL";
default: return "Unknown";
}
}
public static void LoadUrl(ref HTMLDocument doc, String url)
{
LoadUrl(ref doc, url, true);
}
public static void LoadUrl(ref HTMLDocument doc, String url, bool CreateSite)
{
if (doc == null)
{
throw new HtmlEditorException("Null document passed to LoadDocument");
}
if (CreateSite)
{
//set client site to DownloadOnlySite, to suppress scripts
DownloadOnlySite ds = new DownloadOnlySite();
IOleObject ob = (IOleObject)doc;
ob.SetClientSite(ds);
}
IPersistMoniker persistMoniker = (IPersistMoniker)doc;
IMoniker moniker = null;
int iResult = win32.CreateURLMoniker(null, url, out moniker);
IBindCtx bindContext = null;
iResult = win32.CreateBindCtx(0, out bindContext);
iResult = persistMoniker.Load(0, moniker, bindContext, constants.STGM_READ);
persistMoniker = null;
bindContext = null;
moniker = null;
}
public static void LoadDocument(ref HTMLDocument doc, String documentVal)
{
LoadDocument(ref doc, documentVal, false, true);
}
public static void LoadDocument(ref HTMLDocument doc, String documentVal, bool LoadAsAnsi, bool CreateSite)
{
LoadDocument(ref doc, documentVal, LoadAsAnsi, CreateSite, Encoding.UTF8);
}
public static void LoadDocument(ref HTMLDocument doc, String documentVal, bool LoadAsAnsi, bool CreateSite,Encoding EncodingToAddPreamble)
{
if (doc == null)
{
throw new HtmlEditorException("Null document passed to LoadDocument");
}
IHTMLDocument2 htmldoc = (IHTMLDocument2)doc;
bool isWin98 = (System.Environment.OSVersion.Platform == PlatformID.Win32Windows);
if (documentVal == string.Empty )
{
documentVal = "<html></html>";
}
if (CreateSite)
{
//set client site to DownloadOnlySite, to suppress scripts
DownloadOnlySite ds = new DownloadOnlySite();
IOleObject ob = (IOleObject)doc;
ob.SetClientSite(ds);
}
IStream stream = null;
if (isWin98 | LoadAsAnsi)
{
win32.CreateStreamOnHGlobal(Marshal.StringToHGlobalAnsi(documentVal), 1, out
stream);
}
else
{
if (!isBOMPresent(documentVal))
//add bytemark if needed
{
if (EncodingToAddPreamble != null)
{
byte[] preamble = EncodingToAddPreamble.GetPreamble();
String byteOrderMark = EncodingToAddPreamble.GetString(preamble, 0, preamble.Length);
documentVal = byteOrderMark + documentVal;
}
}
win32.CreateStreamOnHGlobal(Marshal.StringToHGlobalUni(documentVal), 1, out stream);
}
if (stream == null)
{
throw new HtmlEditorException("Could not allocate document stream");
}
if (isWin98)
{
//fix string termination on Win98
ulong thesize = 0;
IntPtr ptr = IntPtr.Zero;
int iSizeOfInt64 = Marshal.SizeOf(typeof(Int64));
ptr = Marshal.AllocHGlobal(iSizeOfInt64);
if (ptr == IntPtr.Zero)
{
throw new HtmlEditorException("Could not load document");
}
//seek to end of stream
stream.Seek(0, 2, ptr);
//read the size
thesize = (ulong)Marshal.ReadInt64(ptr);
//free the pointer
Marshal.FreeHGlobal(ptr);
//truncate the stream
stream.SetSize((long)thesize);
//2nd param, 0 is beginning, 1 is current, 2 is end
if (thesize != (ulong)documentVal.Length + 1)
{
//fix the size by truncating the stream
Debug.Assert(true, "Size of stream is unexpected", "The size of the stream is not equal to the length of the string passed to it.");
stream.SetSize(documentVal.Length + 1);
}
}
//set stream to start
stream.Seek(0, 0, IntPtr.Zero);
//2nd param, 0 is beginning, 1 is current, 2 is end
IPersistStreamInit persistentStreamInit = (IPersistStreamInit)
doc;
if (persistentStreamInit != null)
{
int iRetVal = 0;
iRetVal = persistentStreamInit.InitNew();
if (iRetVal == HRESULT.S_OK)
{
iRetVal = persistentStreamInit.Load(stream);
if (iRetVal != HRESULT.S_OK)
{
throw new HtmlEditorException("Could not load document");
}
}
else
{
throw new HtmlEditorException("Could not load document");
}
persistentStreamInit = null;
}
else
{
throw new HtmlEditorException("Could not load document");
}
stream = null;
}
public static String GetDocumentSource(ref HTMLDocument doc)
{
return GetDocumentSource(ref doc, EncodingType.Auto);
}
public static String GetDocumentSource(ref HTMLDocument doc, Encoding enc)
{
if (doc == null) return null;
bool IsUnicodeDetermined = false;
Encoding theEncoding = enc;
if (theEncoding == null)
{
theEncoding = Encoding.GetEncoding(0);
//Windows default
}
if (theEncoding != Encoding.GetEncoding(0))
{
//Don't try to detect unicode if we were
//passed an encoding other than the default
IsUnicodeDetermined = true;
}
// use the routine from htmlwrapper
MemoryStream memstream = new MemoryStream();
ComStream cstream = new ComStream(memstream);
IPersistStreamInit pStreamInit = (IPersistStreamInit)doc;
pStreamInit.Save(cstream, false);
StringBuilder Result = new StringBuilder();
//goto start of stream
memstream.Seek(0, SeekOrigin.Begin);
int iSize = 2048;
byte[] bytedata = new byte[2048];
int iBOMLength;
while (true)
{
iBOMLength = 0;
iSize = memstream.Read(bytedata, 0, bytedata.Length);
if (iSize > 0)
{
if (!IsUnicodeDetermined)
{
//look for byte order mark
bool IsUTF16LE = false;
bool IsUTF16BE = false;
bool IsUTF8 = false;
bool IsBOMPresent = false;
if ((bytedata[0] == 0xFF) & (bytedata[1] == 0xFE))//UTF16LE
{
IsUTF16LE = true;
IsBOMPresent = true;
}
if ((bytedata[0] == 0xFE) & (bytedata[1] == 0xFF))// UTF16BE
{
IsUTF16BE = true;
IsBOMPresent = true;
}
if ((bytedata[0] == 0xEF) & (bytedata[1] == 0xBB) & (bytedata[2] == 0xBF)) //UTF8
{
IsUTF8 = true;
IsBOMPresent = true;
}
//look for alternate zeroes
if (!IsUTF16LE & !IsUTF16BE & !IsUTF8)
{
if ((bytedata[1] == 0) & (bytedata[3] == 0) & (bytedata[5] == 0) & (bytedata[7] == 0))
{
IsUTF16LE = true; //best guess
}
}
if (IsUTF16LE)
{
theEncoding = Encoding.Unicode;
}
else if (IsUTF16BE)
{
theEncoding = Encoding.BigEndianUnicode;
}
else if (IsUTF8)
{
theEncoding = Encoding.UTF8;
}
if (IsBOMPresent)
{
//strip out the BOM
iBOMLength = theEncoding.GetPreamble().Length;
}
//don't repeat the test
IsUnicodeDetermined = true;
}
Result.Append(theEncoding.GetString(bytedata, iBOMLength, iSize - iBOMLength));
}
else
{
break;
}
}
memstream.Close();
return Result.ToString();
}
public static String GetDocumentSource(ref HTMLDocument doc, EncodingType theDocumentEncoding)
{
Encoding theEncoding;
switch (theDocumentEncoding)
{
case EncodingType.Auto:
IHTMLDocument2 htmldoc = (IHTMLDocument2)doc;
String theCharSet = htmldoc.GetCharset();
theEncoding = Encoding.GetEncoding(theCharSet);
Debug.Assert(theEncoding != null,"Auto Encoding is null");
break;
case EncodingType.ASCII:
theEncoding = new ASCIIEncoding();
break;
case EncodingType.Unicode:
theEncoding = new UnicodeEncoding();
break;
case EncodingType.UTF7:
theEncoding = new UTF7Encoding();
break;
case EncodingType.UTF8:
theEncoding = new UTF8Encoding();
break;
case EncodingType.WindowsCurrent:
theEncoding = Encoding.GetEncoding(0);
break;
default:
theEncoding = Encoding.GetEncoding(0);
break;
}
return GetDocumentSource(ref doc, theEncoding);
}
internal static uint GetCsColor(Color col)
{
return (uint)(col.R + (col.G * 256) + (col.B * 65536));
}
private static bool isBOMPresent(string sVal)
{
if (sVal.Length < 4)
{
return false;
}
byte[] preamblebytes;
preamblebytes = Encoding.UTF8.GetBytes(sVal.ToCharArray(0, 4));
if (isStartOfArrayEqual(preamblebytes,Encoding.UTF8.GetPreamble()))
{
return true;
}
preamblebytes = Encoding.Unicode.GetBytes(sVal.ToCharArray(0, 4));
if (isStartOfArrayEqual(preamblebytes,Encoding.Unicode.GetPreamble()))
{
return true;
}
preamblebytes = Encoding.BigEndianUnicode.GetBytes(sVal.ToCharArray(0, 4));
if (isStartOfArrayEqual(preamblebytes, Encoding.BigEndianUnicode.GetPreamble()))
{
return true;
}
return false;
}
private static bool isStartOfArrayEqual(byte[] arr1, byte[] arr2)
{
//test whether arr1 is the same as arr2 up to the length of arr2
//compare the length
if (arr1.Length < arr2.Length)
return false;
//length is same, compare bytes
for (int i = 0; i < arr2.Length; i++)
if (arr1[i] != arr2[i])
return false;
return true;
}
}
}
| |
namespace StripeTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Stripe;
using Xunit;
public class SourceServiceTest : BaseStripeTest
{
private const string CustomerId = "cus_123";
private const string SourceId = "src_123";
private readonly SourceService service;
private readonly SourceAttachOptions attachOptions;
private readonly SourceCreateOptions createOptions;
private readonly SourceListOptions listOptions;
private readonly SourceUpdateOptions updateOptions;
private readonly SourceVerifyOptions verifyOptions;
public SourceServiceTest(
StripeMockFixture stripeMockFixture,
MockHttpClientFixture mockHttpClientFixture)
: base(stripeMockFixture, mockHttpClientFixture)
{
this.service = new SourceService(this.StripeClient);
this.attachOptions = new SourceAttachOptions
{
Source = SourceId,
};
this.createOptions = new SourceCreateOptions
{
Type = SourceType.AchCreditTransfer,
Currency = "usd",
Mandate = new SourceMandateOptions
{
Acceptance = new SourceMandateAcceptanceOptions
{
Date = DateTime.Parse("Mon, 01 Jan 2001 00:00:00Z"),
Ip = "127.0.0.1",
NotificationMethod = "manual",
Status = "accepted",
UserAgent = "User-Agent",
},
},
Owner = new SourceOwnerOptions
{
Address = new AddressOptions
{
State = "CA",
City = "City",
Line1 = "Line1",
Line2 = "Line2",
PostalCode = "90210",
Country = "US",
},
Email = "email@stripe.com",
Name = "Owner Name",
Phone = "5555555555",
},
Receiver = new SourceReceiverOptions
{
RefundAttributesMethod = "manual",
},
};
this.listOptions = new SourceListOptions
{
Limit = 1,
};
this.updateOptions = new SourceUpdateOptions
{
Metadata = new Dictionary<string, string>
{
{ "key", "value" },
},
};
this.verifyOptions = new SourceVerifyOptions
{
Values = new List<string> { "32", "45" },
};
}
[Fact]
public void Attach()
{
var source = this.service.Attach(CustomerId, this.attachOptions);
this.AssertRequest(HttpMethod.Post, "/v1/customers/cus_123/sources");
Assert.NotNull(source);
// We can't test the object returned as stripe-mock returns an Account
// Assert.Equal("source", source.Object);
}
[Fact]
public async Task AttachAsync()
{
var source = await this.service.AttachAsync(CustomerId, this.attachOptions);
this.AssertRequest(HttpMethod.Post, "/v1/customers/cus_123/sources");
Assert.NotNull(source);
// We can't test the object returned as stripe-mock returns an Account
// Assert.Equal("source", source.Object);
}
[Fact]
public void Create()
{
var source = this.service.Create(this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/sources");
Assert.NotNull(source);
Assert.Equal("source", source.Object);
}
[Fact]
public async Task CreateAsync()
{
var source = await this.service.CreateAsync(this.createOptions);
this.AssertRequest(HttpMethod.Post, "/v1/sources");
Assert.NotNull(source);
Assert.Equal("source", source.Object);
}
[Fact]
public void Detach()
{
var source = this.service.Detach(CustomerId, SourceId);
this.AssertRequest(HttpMethod.Delete, "/v1/customers/cus_123/sources/src_123");
Assert.NotNull(source);
// We can't test the object returned as stripe-mock returns an Account
// Assert.Equal("source", source.Object);
}
[Fact]
public async Task DetachAsync()
{
var source = await this.service.DetachAsync(CustomerId, SourceId);
this.AssertRequest(HttpMethod.Delete, "/v1/customers/cus_123/sources/src_123");
Assert.NotNull(source);
// We can't test the object returned as stripe-mock returns an Account
// Assert.Equal("source", source.Object);
}
[Fact]
public void Get()
{
var source = this.service.Get(SourceId);
this.AssertRequest(HttpMethod.Get, "/v1/sources/src_123");
Assert.NotNull(source);
Assert.Equal("source", source.Object);
}
[Fact]
public async Task GetAsync()
{
var source = await this.service.GetAsync(SourceId);
this.AssertRequest(HttpMethod.Get, "/v1/sources/src_123");
Assert.NotNull(source);
Assert.Equal("source", source.Object);
}
[Fact]
public void GetWithClientSecret()
{
var options = new SourceGetOptions
{
ClientSecret = "src_client_secret_123",
};
var source = this.service.Get(SourceId, options);
this.AssertRequest(HttpMethod.Get, "/v1/sources/src_123");
Assert.NotNull(source);
Assert.Equal("source", source.Object);
}
[Fact]
public void List()
{
var sources = this.service.List(CustomerId, this.listOptions);
this.AssertRequest(HttpMethod.Get, "/v1/customers/cus_123/sources");
Assert.NotNull(sources);
Assert.Equal("list", sources.Object);
Assert.Single(sources.Data);
// We can't test the object returned as stripe-mock returns an Account
// Assert.Equal("source", sources.Data[0].Object);
}
[Fact]
public async Task ListAsync()
{
var sources = await this.service.ListAsync(CustomerId, this.listOptions);
this.AssertRequest(HttpMethod.Get, "/v1/customers/cus_123/sources");
Assert.NotNull(sources);
Assert.Equal("list", sources.Object);
Assert.Single(sources.Data);
// We can't test the object returned as stripe-mock returns an Account
// Assert.Equal("source", sources.Data[0].Object);
}
[Fact]
public void ListAutoPaging()
{
var sources = this.service.ListAutoPaging(CustomerId, this.listOptions).ToList();
Assert.NotNull(sources);
}
[Fact]
public void Update()
{
var source = this.service.Update(SourceId, this.updateOptions);
this.AssertRequest(HttpMethod.Post, "/v1/sources/src_123");
Assert.NotNull(source);
Assert.Equal("source", source.Object);
}
[Fact]
public async Task UpdateAsync()
{
var source = await this.service.UpdateAsync(SourceId, this.updateOptions);
this.AssertRequest(HttpMethod.Post, "/v1/sources/src_123");
Assert.NotNull(source);
Assert.Equal("source", source.Object);
}
[Fact]
public void Verify()
{
var source = this.service.Verify(SourceId, this.verifyOptions);
this.AssertRequest(HttpMethod.Post, "/v1/sources/src_123/verify");
Assert.NotNull(source);
Assert.Equal("source", source.Object);
}
[Fact]
public async Task VerifyAsync()
{
var source = await this.service.VerifyAsync(SourceId, this.verifyOptions);
this.AssertRequest(HttpMethod.Post, "/v1/sources/src_123/verify");
Assert.NotNull(source);
Assert.Equal("source", source.Object);
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Rest.Azure;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System;
using Microsoft.Azure.Management.Sql.Models;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
namespace Microsoft.Azure.Commands.Sql.ElasticPool.Services
{
/// <summary>
/// This class is responsible for all the REST communication with the audit REST endpoints
/// </summary>
public class AzureSqlElasticPoolCommunicator
{
/// <summary>
/// The Sql client to be used by this end points communicator
/// </summary>
private static Management.Sql.SqlManagementClient SqlClient { get; set; }
/// <summary>
/// The old version of Sql client to be used by this end points communicator
/// </summary>
public Management.Sql.LegacySdk.SqlManagementClient LegacySqlClient { get; set; }
/// <summary>
/// Gets or set the Azure subscription
/// </summary>
private static IAzureSubscription Subscription { get; set; }
/// <summary>
/// Gets or sets the Azure profile
/// </summary>
public IAzureContext Context { get; set; }
/// <summary>
/// Creates a communicator for Azure Sql Elastic Pool
/// </summary>
/// <param name="profile"></param>
/// <param name="subscription"></param>
public AzureSqlElasticPoolCommunicator(IAzureContext context)
{
Context = context;
if (context.Subscription != Subscription)
{
Subscription = context.Subscription;
SqlClient = null;
}
}
/// <summary>
/// Gets the Azure Sql Database Elastic Pool
/// </summary>
public Management.Sql.Models.ElasticPool Get(string resourceGroupName, string serverName, string elasticPoolName)
{
return GetCurrentSqlClient().ElasticPools.Get(resourceGroupName, serverName, elasticPoolName);
}
/// <summary>
/// Gets the Azure Sql Database
/// </summary>
public Management.Sql.Models.Database GetDatabase(string resourceGroupName, string serverName, string databaseName)
{
return GetCurrentSqlClient().Databases.Get(resourceGroupName, serverName, databaseName);
}
/// <summary>
/// List Azure Sql databases in the Elastic Pool
/// </summary>
public IList<Management.Sql.Models.Database> ListDatabases(string resourceGroupName, string serverName, string elasticPoolName)
{
return GetCurrentSqlClient().Databases.ListByElasticPool(resourceGroupName, serverName, elasticPoolName).ToList();
}
/// <summary>
/// Lists Azure Sql Databases Elastic Pool
/// </summary>
public IList<Management.Sql.Models.ElasticPool> List(string resourceGroupName, string serverName)
{
return GetCurrentSqlClient().ElasticPools.ListByServer(resourceGroupName, serverName).ToList();
}
/// <summary>
/// Creates an Elastic Pool
/// </summary>
public Management.Sql.Models.ElasticPool Create(string resourceGroupName, string serverName, string elasticPoolName, Management.Sql.Models.ElasticPool parameters)
{
// Occasionally after PUT elastic pool, if we poll for operation results immediately then
// the polling may fail with 404. This is mitigated in the client by adding a brief wait.
var client = GetCurrentSqlClient();
AzureOperationResponse<Management.Sql.Models.ElasticPool> createOrUpdateResponse =
client.ElasticPools.BeginCreateOrUpdateWithHttpMessagesAsync(
resourceGroupName, serverName, elasticPoolName, parameters).Result;
// Sleep 5 seconds
TestMockSupport.Delay(5000);
return client.GetPutOrPatchOperationResultAsync(
createOrUpdateResponse, null, CancellationToken.None).Result.Body;
}
/// <summary>
/// Updates an Elastic Pool using Patch
/// </summary>
public Management.Sql.Models.ElasticPool CreateOrUpdate(string resourceGroupName, string serverName, string elasticPoolName, ElasticPoolUpdate parameters)
{
return GetCurrentSqlClient().ElasticPools.Update(resourceGroupName, serverName, elasticPoolName, parameters);
}
/// <summary>
/// Deletes an Elastic Pool
/// </summary>
public void Remove(string resourceGroupName, string serverName, string elasticPoolName)
{
GetCurrentSqlClient().ElasticPools.Delete(resourceGroupName, serverName, elasticPoolName);
}
/// <summary>
/// Gets Elastic Pool Activity
/// </summary>
public IList<ElasticPoolActivity> ListActivity(string resourceGroupName, string serverName, string elasticPoolName)
{
return GetCurrentSqlClient().ElasticPoolActivities.ListByElasticPool(resourceGroupName, serverName, elasticPoolName).ToList();
}
/// <summary>
/// Gets Elastic Pool Operations
/// </summary>
/// <param name="resourceGroupName"></param>
/// <param name="serverName"></param>
/// <param name="elasticPoolName"></param>
/// <returns></returns>
public IList<ElasticPoolOperation> ListOperation(string resourceGroupName, string serverName, string elasticPoolName)
{
return GetCurrentSqlClient().ElasticPoolOperations.ListByElasticPool(resourceGroupName, serverName, elasticPoolName).ToList();
}
/// <summary>
/// Cancel elastic pool activities
/// </summary>
public void CancelOperation(string resourceGroupName, string serverName, string elasticPoolName, Guid operationId)
{
GetCurrentSqlClient().ElasticPoolOperations.Cancel(resourceGroupName, serverName, elasticPoolName, operationId);
}
/// <summary>
/// Gets Elastic Pool Database Activity
/// </summary>
internal IList<Management.Sql.Models.ElasticPoolDatabaseActivity> ListDatabaseActivity(string resourceGroupName, string serverName, string poolName)
{
return GetCurrentSqlClient().ElasticPoolDatabaseActivities.ListByElasticPool(resourceGroupName, serverName, poolName).ToList();
}
/// <summary>
/// Retrieve the SQL Management client for the currently selected subscription, adding the session and request
/// id tracing headers for the current cmdlet invocation.
/// </summary>
/// <returns>The SQL Management client for the currently selected subscription.</returns>
private Management.Sql.LegacySdk.SqlManagementClient GetLegacySqlClient()
{
// Get the SQL management client for the current subscription
if (LegacySqlClient == null)
{
LegacySqlClient = AzureSession.Instance.ClientFactory.CreateClient<Management.Sql.LegacySdk.SqlManagementClient>(Context, AzureEnvironment.Endpoint.ResourceManager);
}
return LegacySqlClient;
}
/// <summary>
/// Retrieve the SQL Management client for the currently selected subscription, adding the session and request
/// id tracing headers for the current cmdlet invocation.
/// </summary>
/// <returns>The SQL Management client for the currently selected subscription.</returns>
private Management.Sql.SqlManagementClient GetCurrentSqlClient()
{
// Get the SQL management client for the current subscription
if (SqlClient == null)
{
SqlClient = AzureSession.Instance.ClientFactory.CreateArmClient<Management.Sql.SqlManagementClient>(Context, AzureEnvironment.Endpoint.ResourceManager);
}
return SqlClient;
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Reflection;
namespace 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 CollectionUtil = Lucene.Net.Util.CollectionUtil;
using Directory = Lucene.Net.Store.Directory;
using InfoStream = Lucene.Net.Util.InfoStream;
/// <summary>
/// This class keeps track of each SegmentInfos instance that
/// is still "live", either because it corresponds to a
/// segments_N file in the <see cref="Directory"/> (a "commit", i.e. a
/// committed <see cref="SegmentInfos"/>) or because it's an in-memory
/// <see cref="SegmentInfos"/> that a writer is actively updating but has
/// not yet committed. This class uses simple reference
/// counting to map the live <see cref="SegmentInfos"/> instances to
/// individual files in the <see cref="Directory"/>.
/// <para/>
/// The same directory file may be referenced by more than
/// one <see cref="IndexCommit"/>, i.e. more than one <see cref="SegmentInfos"/>.
/// Therefore we count how many commits reference each file.
/// When all the commits referencing a certain file have been
/// deleted, the refcount for that file becomes zero, and the
/// file is deleted.
/// <para/>
/// A separate deletion policy interface
/// (<see cref="IndexDeletionPolicy"/>) is consulted on creation (OnInit)
/// and once per commit (OnCommit), to decide when a commit
/// should be removed.
/// <para/>
/// It is the business of the <see cref="IndexDeletionPolicy"/> to choose
/// when to delete commit points. The actual mechanics of
/// file deletion, retrying, etc, derived from the deletion
/// of commit points is the business of the <see cref="IndexFileDeleter"/>.
/// <para/>
/// The current default deletion policy is
/// <see cref="KeepOnlyLastCommitDeletionPolicy"/>, which removes all
/// prior commits when a new commit has completed. This
/// matches the behavior before 2.2.
/// <para/>
/// Note that you must hold the <c>write.lock</c> before
/// instantiating this class. It opens segments_N file(s)
/// directly with no retry logic.
/// </summary>
internal sealed class IndexFileDeleter : IDisposable
{
/// <summary>
/// Files that we tried to delete but failed (likely
/// because they are open and we are running on Windows),
/// so we will retry them again later:
/// </summary>
private IList<string> deletable;
/// <summary>
/// Reference count for all files in the index.
/// Counts how many existing commits reference a file.
/// </summary>
private IDictionary<string, RefCount> refCounts = new Dictionary<string, RefCount>();
/// <summary>
/// Holds all commits (segments_N) currently in the index.
/// this will have just 1 commit if you are using the
/// default delete policy (KeepOnlyLastCommitDeletionPolicy).
/// Other policies may leave commit points live for longer
/// in which case this list would be longer than 1:
/// </summary>
private IList<CommitPoint> commits = new List<CommitPoint>();
/// <summary>
/// Holds files we had incref'd from the previous
/// non-commit checkpoint:
/// </summary>
private readonly List<string> lastFiles = new List<string>();
/// <summary>
/// Commits that the IndexDeletionPolicy have decided to delete:
/// </summary>
private IList<CommitPoint> commitsToDelete = new List<CommitPoint>();
private readonly InfoStream infoStream;
private Directory directory;
private IndexDeletionPolicy policy;
internal readonly bool startingCommitDeleted;
private SegmentInfos lastSegmentInfos;
/// <summary>
/// Change to true to see details of reference counts when
/// infoStream is enabled
/// </summary>
public static bool VERBOSE_REF_COUNTS = false;
// Used only for assert
private readonly IndexWriter writer;
// called only from assert
private bool IsLocked
{
//LUCENENET TODO: This always returns true - probably incorrect
get { return writer == null || true /*Monitor. IsEntered(Writer)*/; }
}
/// <summary>
/// Initialize the deleter: find all previous commits in
/// the <see cref="Directory"/>, incref the files they reference, call
/// the policy to let it delete commits. this will remove
/// any files not referenced by any of the commits. </summary>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
public IndexFileDeleter(Directory directory, IndexDeletionPolicy policy, SegmentInfos segmentInfos, InfoStream infoStream, IndexWriter writer, bool initialIndexExists)
{
this.infoStream = infoStream;
this.writer = writer;
string currentSegmentsFile = segmentInfos.GetSegmentsFileName();
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "init: current segments file is \"" + currentSegmentsFile + "\"; deletionPolicy=" + policy);
}
this.policy = policy;
this.directory = directory;
// First pass: walk the files and initialize our ref
// counts:
long currentGen = segmentInfos.Generation;
CommitPoint currentCommitPoint = null;
string[] files = null;
try
{
files = directory.ListAll();
}
#pragma warning disable 168
catch (DirectoryNotFoundException e)
#pragma warning restore 168
{
// it means the directory is empty, so ignore it.
files = new string[0];
}
if (currentSegmentsFile != null)
{
Regex r = IndexFileNames.CODEC_FILE_PATTERN;
foreach (string fileName in files)
{
if (!fileName.EndsWith("write.lock", StringComparison.Ordinal) && !fileName.Equals(IndexFileNames.SEGMENTS_GEN, StringComparison.Ordinal)
&& (r.IsMatch(fileName) || fileName.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal)))
{
// Add this file to refCounts with initial count 0:
GetRefCount(fileName);
if (fileName.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal))
{
// this is a commit (segments or segments_N), and
// it's valid (<= the max gen). Load it, then
// incref all files it refers to:
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "init: load commit \"" + fileName + "\"");
}
SegmentInfos sis = new SegmentInfos();
try
{
sis.Read(directory, fileName);
}
#pragma warning disable 168
catch (FileNotFoundException e)
#pragma warning restore 168
{
// LUCENE-948: on NFS (and maybe others), if
// you have writers switching back and forth
// between machines, it's very likely that the
// dir listing will be stale and will claim a
// file segments_X exists when in fact it
// doesn't. So, we catch this and handle it
// as if the file does not exist
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "init: hit FileNotFoundException when loading commit \"" + fileName + "\"; skipping this commit point");
}
sis = null;
}
// LUCENENET specific - .NET (thankfully) only has one FileNotFoundException, so we don't need this
//catch (NoSuchFileException)
//{
// // LUCENE-948: on NFS (and maybe others), if
// // you have writers switching back and forth
// // between machines, it's very likely that the
// // dir listing will be stale and will claim a
// // file segments_X exists when in fact it
// // doesn't. So, we catch this and handle it
// // as if the file does not exist
// if (infoStream.IsEnabled("IFD"))
// {
// infoStream.Message("IFD", "init: hit FileNotFoundException when loading commit \"" + fileName + "\"; skipping this commit point");
// }
// sis = null;
//}
// LUCENENET specific - since NoSuchDirectoryException subclasses FileNotFoundException
// in Lucene, we need to catch it here to be on the safe side.
catch (System.IO.DirectoryNotFoundException)
{
// LUCENE-948: on NFS (and maybe others), if
// you have writers switching back and forth
// between machines, it's very likely that the
// dir listing will be stale and will claim a
// file segments_X exists when in fact it
// doesn't. So, we catch this and handle it
// as if the file does not exist
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "init: hit FileNotFoundException when loading commit \"" + fileName + "\"; skipping this commit point");
}
sis = null;
}
catch (IOException e)
{
if (SegmentInfos.GenerationFromSegmentsFileName(fileName) <= currentGen && directory.FileLength(fileName) > 0)
{
throw e;
}
else
{
// Most likely we are opening an index that
// has an aborted "future" commit, so suppress
// exc in this case
sis = null;
}
}
if (sis != null)
{
CommitPoint commitPoint = new CommitPoint(commitsToDelete, directory, sis);
if (sis.Generation == segmentInfos.Generation)
{
currentCommitPoint = commitPoint;
}
commits.Add(commitPoint);
IncRef(sis, true);
if (lastSegmentInfos == null || sis.Generation > lastSegmentInfos.Generation)
{
lastSegmentInfos = sis;
}
}
}
}
}
}
if (currentCommitPoint == null && currentSegmentsFile != null && initialIndexExists)
{
// We did not in fact see the segments_N file
// corresponding to the segmentInfos that was passed
// in. Yet, it must exist, because our caller holds
// the write lock. this can happen when the directory
// listing was stale (eg when index accessed via NFS
// client with stale directory listing cache). So we
// try now to explicitly open this commit point:
SegmentInfos sis = new SegmentInfos();
try
{
sis.Read(directory, currentSegmentsFile);
}
catch (IOException e)
{
throw new CorruptIndexException("failed to locate current segments_N file \"" + currentSegmentsFile + "\"" + e.ToString(), e);
}
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "forced open of current segments file " + segmentInfos.GetSegmentsFileName());
}
currentCommitPoint = new CommitPoint(commitsToDelete, directory, sis);
commits.Add(currentCommitPoint);
IncRef(sis, true);
}
// We keep commits list in sorted order (oldest to newest):
CollectionUtil.TimSort(commits);
// Now delete anything with ref count at 0. These are
// presumably abandoned files eg due to crash of
// IndexWriter.
foreach (KeyValuePair<string, RefCount> entry in refCounts)
{
RefCount rc = entry.Value;
string fileName = entry.Key;
if (0 == rc.count)
{
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "init: removing unreferenced file \"" + fileName + "\"");
}
DeleteFile(fileName);
}
}
// Finally, give policy a chance to remove things on
// startup:
this.policy.OnInit(commits);
// Always protect the incoming segmentInfos since
// sometime it may not be the most recent commit
Checkpoint(segmentInfos, false);
startingCommitDeleted = currentCommitPoint == null ? false : currentCommitPoint.IsDeleted;
DeleteCommits();
}
private void EnsureOpen()
{
if (writer == null)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "this IndexWriter is closed");
}
else
{
writer.EnsureOpen(false);
}
}
public SegmentInfos LastSegmentInfos
{
get
{
return lastSegmentInfos;
}
}
/// <summary>
/// Remove the CommitPoints in the commitsToDelete List by
/// DecRef'ing all files from each SegmentInfos.
/// </summary>
private void DeleteCommits()
{
int size = commitsToDelete.Count;
if (size > 0)
{
// First decref all files that had been referred to by
// the now-deleted commits:
for (int i = 0; i < size; i++)
{
CommitPoint commit = commitsToDelete[i];
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "deleteCommits: now decRef commit \"" + commit.SegmentsFileName + "\"");
}
foreach (string file in commit.files)
{
DecRef(file);
}
}
commitsToDelete.Clear();
// Now compact commits to remove deleted ones (preserving the sort):
size = commits.Count;
int readFrom = 0;
int writeTo = 0;
while (readFrom < size)
{
CommitPoint commit = commits[readFrom];
if (!commit.deleted)
{
if (writeTo != readFrom)
{
commits[writeTo] = commits[readFrom];
}
writeTo++;
}
readFrom++;
}
while (size > writeTo)
{
commits.RemoveAt(size - 1);
size--;
}
}
}
/// <summary>
/// Writer calls this when it has hit an error and had to
/// roll back, to tell us that there may now be
/// unreferenced files in the filesystem. So we re-list
/// the filesystem and delete such files. If <paramref name="segmentName"/>
/// is non-null, we will only delete files corresponding to
/// that segment.
/// </summary>
public void Refresh(string segmentName)
{
Debug.Assert(IsLocked);
string[] files = directory.ListAll();
string segmentPrefix1;
string segmentPrefix2;
if (segmentName != null)
{
segmentPrefix1 = segmentName + ".";
segmentPrefix2 = segmentName + "_";
}
else
{
segmentPrefix1 = null;
segmentPrefix2 = null;
}
Regex r = IndexFileNames.CODEC_FILE_PATTERN;
for (int i = 0; i < files.Length; i++)
{
string fileName = files[i];
//m.reset(fileName);
if ((segmentName == null || fileName.StartsWith(segmentPrefix1, StringComparison.Ordinal) || fileName.StartsWith(segmentPrefix2, StringComparison.Ordinal))
&& !fileName.EndsWith("write.lock", StringComparison.Ordinal) && !refCounts.ContainsKey(fileName) && !fileName.Equals(IndexFileNames.SEGMENTS_GEN, StringComparison.Ordinal)
&& (r.IsMatch(fileName) || fileName.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal)))
{
// Unreferenced file, so remove it
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "refresh [prefix=" + segmentName + "]: removing newly created unreferenced file \"" + fileName + "\"");
}
DeleteFile(fileName);
}
}
}
public void Refresh()
{
// Set to null so that we regenerate the list of pending
// files; else we can accumulate same file more than
// once
Debug.Assert(IsLocked);
deletable = null;
Refresh(null);
}
public void Dispose()
{
// DecRef old files from the last checkpoint, if any:
Debug.Assert(IsLocked);
if (lastFiles.Count > 0)
{
DecRef(lastFiles);
lastFiles.Clear();
}
DeletePendingFiles();
}
/// <summary>
/// Revisits the <see cref="IndexDeletionPolicy"/> by calling its
/// <see cref="IndexDeletionPolicy.OnCommit{T}(IList{T})"/> again with the known commits.
/// this is useful in cases where a deletion policy which holds onto index
/// commits is used. The application may know that some commits are not held by
/// the deletion policy anymore and call
/// <see cref="IndexWriter.DeleteUnusedFiles()"/>, which will attempt to delete the
/// unused commits again.
/// </summary>
internal void RevisitPolicy()
{
Debug.Assert(IsLocked);
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "now revisitPolicy");
}
if (commits.Count > 0)
{
policy.OnCommit(commits);
DeleteCommits();
}
}
public void DeletePendingFiles()
{
Debug.Assert(IsLocked);
if (deletable != null)
{
IList<string> oldDeletable = deletable;
deletable = null;
int size = oldDeletable.Count;
for (int i = 0; i < size; i++)
{
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "delete pending file " + oldDeletable[i]);
}
DeleteFile(oldDeletable[i]);
}
}
}
/// <summary>
/// For definition of "check point" see <see cref="IndexWriter"/> comments:
/// "Clarification: Check Points (and commits)".
/// <para/>
/// Writer calls this when it has made a "consistent
/// change" to the index, meaning new files are written to
/// the index and the in-memory <see cref="SegmentInfos"/> have been
/// modified to point to those files.
/// <para/>
/// This may or may not be a commit (segments_N may or may
/// not have been written).
/// <para/>
/// We simply incref the files referenced by the new
/// <see cref="SegmentInfos"/> and decref the files we had previously
/// seen (if any).
/// <para/>
/// If this is a commit, we also call the policy to give it
/// a chance to remove other commits. If any commits are
/// removed, we decref their files as well.
/// </summary>
public void Checkpoint(SegmentInfos segmentInfos, bool isCommit)
{
Debug.Assert(IsLocked);
//Debug.Assert(Thread.holdsLock(Writer));
long t0 = 0;
if (infoStream.IsEnabled("IFD"))
{
t0 = Time.NanoTime();
infoStream.Message("IFD", "now checkpoint \"" + writer.SegString(writer.ToLiveInfos(segmentInfos).Segments) + "\" [" + segmentInfos.Count + " segments " + "; isCommit = " + isCommit + "]");
}
// Try again now to delete any previously un-deletable
// files (because they were in use, on Windows):
DeletePendingFiles();
// Incref the files:
IncRef(segmentInfos, isCommit);
if (isCommit)
{
// Append to our commits list:
commits.Add(new CommitPoint(commitsToDelete, directory, segmentInfos));
// Tell policy so it can remove commits:
policy.OnCommit(commits);
// Decref files for commits that were deleted by the policy:
DeleteCommits();
}
else
{
// DecRef old files from the last checkpoint, if any:
DecRef(lastFiles);
lastFiles.Clear();
// Save files so we can decr on next checkpoint/commit:
lastFiles.AddRange(segmentInfos.GetFiles(directory, false));
}
if (infoStream.IsEnabled("IFD"))
{
long t1 = Time.NanoTime();
infoStream.Message("IFD", ((t1 - t0) / 1000000) + " msec to checkpoint");
}
}
internal void IncRef(SegmentInfos segmentInfos, bool isCommit)
{
Debug.Assert(IsLocked);
// If this is a commit point, also incRef the
// segments_N file:
foreach (string fileName in segmentInfos.GetFiles(directory, isCommit))
{
IncRef(fileName);
}
}
internal void IncRef(ICollection<string> files)
{
Debug.Assert(IsLocked);
foreach (string file in files)
{
IncRef(file);
}
}
internal void IncRef(string fileName)
{
Debug.Assert(IsLocked);
RefCount rc = GetRefCount(fileName);
if (infoStream.IsEnabled("IFD"))
{
if (VERBOSE_REF_COUNTS)
{
infoStream.Message("IFD", " IncRef \"" + fileName + "\": pre-incr count is " + rc.count);
}
}
rc.IncRef();
}
internal void DecRef(ICollection<string> files)
{
Debug.Assert(IsLocked);
foreach (string file in files)
{
DecRef(file);
}
}
internal void DecRef(string fileName)
{
Debug.Assert(IsLocked);
RefCount rc = GetRefCount(fileName);
if (infoStream.IsEnabled("IFD"))
{
if (VERBOSE_REF_COUNTS)
{
infoStream.Message("IFD", " DecRef \"" + fileName + "\": pre-decr count is " + rc.count);
}
}
if (0 == rc.DecRef())
{
// this file is no longer referenced by any past
// commit points nor by the in-memory SegmentInfos:
DeleteFile(fileName);
refCounts.Remove(fileName);
}
}
internal void DecRef(SegmentInfos segmentInfos)
{
Debug.Assert(IsLocked);
foreach (string file in segmentInfos.GetFiles(directory, false))
{
DecRef(file);
}
}
public bool Exists(string fileName)
{
Debug.Assert(IsLocked);
if (!refCounts.ContainsKey(fileName))
{
return false;
}
else
{
return GetRefCount(fileName).count > 0;
}
}
private RefCount GetRefCount(string fileName)
{
Debug.Assert(IsLocked);
RefCount rc;
if (!refCounts.ContainsKey(fileName))
{
rc = new RefCount(fileName);
refCounts[fileName] = rc;
}
else
{
rc = refCounts[fileName];
}
return rc;
}
internal void DeleteFiles(IList<string> files)
{
Debug.Assert(IsLocked);
foreach (string file in files)
{
DeleteFile(file);
}
}
/// <summary>
/// Deletes the specified files, but only if they are new
/// (have not yet been incref'd).
/// </summary>
internal void DeleteNewFiles(ICollection<string> files)
{
Debug.Assert(IsLocked);
foreach (string fileName in files)
{
// NOTE: it's very unusual yet possible for the
// refCount to be present and 0: it can happen if you
// open IW on a crashed index, and it removes a bunch
// of unref'd files, and then you add new docs / do
// merging, and it reuses that segment name.
// TestCrash.testCrashAfterReopen can hit this:
if (!refCounts.ContainsKey(fileName) || refCounts[fileName].count == 0)
{
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "delete new file \"" + fileName + "\"");
}
DeleteFile(fileName);
}
}
}
internal void DeleteFile(string fileName)
{
Debug.Assert(IsLocked);
EnsureOpen();
try
{
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD", "delete \"" + fileName + "\"");
}
directory.DeleteFile(fileName);
} // if delete fails
catch (IOException e)
{
// Some operating systems (e.g. Windows) don't
// permit a file to be deleted while it is opened
// for read (e.g. by another process or thread). So
// we assume that when a delete fails it is because
// the file is open in another process, and queue
// the file for subsequent deletion.
//Debug.Assert(e.Message.Contains("cannot delete"));
if (infoStream.IsEnabled("IFD"))
{
infoStream.Message("IFD",
"unable to remove file \"" + fileName + "\": " + e.ToString() + "; Will re-try later.");
}
if (deletable == null)
{
deletable = new List<string>();
}
deletable.Add(fileName); // add to deletable
}
}
/// <summary>
/// Tracks the reference count for a single index file:
/// </summary>
private sealed class RefCount
{
// fileName used only for better assert error messages
internal readonly string fileName;
internal bool initDone;
internal RefCount(string fileName)
{
this.fileName = fileName;
}
internal int count;
public int IncRef()
{
if (!initDone)
{
initDone = true;
}
else
{
Debug.Assert(count > 0, Thread.CurrentThread.Name + ": RefCount is 0 pre-increment for file \"" + fileName + "\"");
}
return ++count;
}
public int DecRef()
{
Debug.Assert(count > 0, Thread.CurrentThread.Name + ": RefCount is 0 pre-decrement for file \"" + fileName + "\"");
return --count;
}
}
/// <summary>
/// Holds details for each commit point. This class is
/// also passed to the deletion policy. Note: this class
/// has a natural ordering that is inconsistent with
/// equals.
/// </summary>
private sealed class CommitPoint : IndexCommit
{
internal ICollection<string> files;
internal string segmentsFileName;
internal bool deleted;
internal Directory directory;
internal ICollection<CommitPoint> commitsToDelete;
internal long generation;
internal readonly IDictionary<string, string> userData;
internal readonly int segmentCount;
public CommitPoint(ICollection<CommitPoint> commitsToDelete, Directory directory, SegmentInfos segmentInfos)
{
this.directory = directory;
this.commitsToDelete = commitsToDelete;
userData = segmentInfos.UserData;
segmentsFileName = segmentInfos.GetSegmentsFileName();
generation = segmentInfos.Generation;
files = segmentInfos.GetFiles(directory, true);
segmentCount = segmentInfos.Count;
}
public override string ToString()
{
return "IndexFileDeleter.CommitPoint(" + segmentsFileName + ")";
}
public override int SegmentCount
{
get
{
return segmentCount;
}
}
public override string SegmentsFileName
{
get
{
return segmentsFileName;
}
}
public override ICollection<string> FileNames
{
get
{
return files;
}
}
public override Directory Directory
{
get
{
return directory;
}
}
public override long Generation
{
get
{
return generation;
}
}
public override IDictionary<string, string> UserData
{
get
{
return userData;
}
}
/// <summary>
/// Called only by the deletion policy, to remove this
/// commit point from the index.
/// </summary>
public override void Delete()
{
if (!deleted)
{
deleted = true;
commitsToDelete.Add(this);
}
}
public override bool IsDeleted
{
get
{
return deleted;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System
{
public partial class String
{
private static unsafe int CompareOrdinalIgnoreCaseHelper(string strA, string strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
int charA = 0, charB = 0;
while (length != 0)
{
charA = *a;
charB = *b;
Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
//Return the (case-insensitive) difference between them.
if (charA != charB)
return charA - charB;
// Next char
a++; b++;
length--;
}
return strA.Length - strB.Length;
}
}
//
// Search/Query methods
//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool EqualsHelper(string strA, string strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(strA.Length == strB.Length);
return SpanHelpers.SequenceEqual(
ref Unsafe.As<char, byte>(ref strA.GetRawStringData()),
ref Unsafe.As<char, byte>(ref strB.GetRawStringData()),
((nuint)strA.Length) * 2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(indexA >= 0 && indexB >= 0);
Debug.Assert(countA >= 0 && countB >= 0);
Debug.Assert(indexA + countA <= strA.Length && indexB + countB <= strB.Length);
return SpanHelpers.SequenceCompareTo(ref Unsafe.Add(ref strA.GetRawStringData(), indexA), countA, ref Unsafe.Add(ref strB.GetRawStringData(), indexB), countB);
}
private static unsafe bool EqualsIgnoreCaseAsciiHelper(string strA, string strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(strA.Length == strB.Length);
int length = strA.Length;
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
while (length != 0)
{
int charA = *a;
int charB = *b;
Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
// Ordinal equals or lowercase equals if the result ends up in the a-z range
if (charA == charB ||
((charA | 0x20) == (charB | 0x20) &&
(uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a')))
{
a++;
b++;
length--;
}
else
{
return false;
}
}
return true;
}
}
private static unsafe int CompareOrdinalHelper(string strA, string strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
// NOTE: This may be subject to change if eliminating the check
// in the callers makes them small enough to be inlined
Debug.Assert(strA._firstChar == strB._firstChar,
"For performance reasons, callers of this method should " +
"check/short-circuit beforehand if the first char is the same.");
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
// Check if the second chars are different here
// The reason we check if _firstChar is different is because
// it's the most common case and allows us to avoid a method call
// to here.
// The reason we check if the second char is different is because
// if the first two chars the same we can increment by 4 bytes,
// leaving us word-aligned on both 32-bit (12 bytes into the string)
// and 64-bit (16 bytes) platforms.
// For empty strings, the second char will be null due to padding.
// The start of the string is the type pointer + string length, which
// takes up 8 bytes on 32-bit, 12 on x64. For empty strings the null
// terminator immediately follows, leaving us with an object
// 10/14 bytes in size. Since everything needs to be a multiple
// of 4/8, this will get padded and zeroed out.
// For one-char strings the second char will be the null terminator.
// NOTE: If in the future there is a way to read the second char
// without pinning the string (e.g. System.Runtime.CompilerServices.Unsafe
// is exposed to mscorlib, or a future version of C# allows inline IL),
// then do that and short-circuit before the fixed.
if (*(a + 1) != *(b + 1)) goto DiffOffset1;
// Since we know that the first two chars are the same,
// we can increment by 2 here and skip 4 bytes.
// This leaves us 8-byte aligned, which results
// on better perf for 64-bit platforms.
length -= 2; a += 2; b += 2;
// unroll the loop
#if BIT64
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto DiffOffset0;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto DiffOffset4;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto DiffOffset8;
length -= 12; a += 12; b += 12;
}
#else // BIT64
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto DiffOffset0;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto DiffOffset2;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8;
length -= 10; a += 10; b += 10;
}
#endif // BIT64
// Fallback loop:
// go back to slower code path and do comparison on 4 bytes at a time.
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) goto DiffNextInt;
length -= 2;
a += 2;
b += 2;
}
// At this point, we have compared all the characters in at least one string.
// The longer string will be larger.
return strA.Length - strB.Length;
#if BIT64
DiffOffset8: a += 4; b += 4;
DiffOffset4: a += 4; b += 4;
#else // BIT64
// Use jumps instead of falling through, since
// otherwise going to DiffOffset8 will involve
// 8 add instructions before getting to DiffNextInt
DiffOffset8: a += 8; b += 8; goto DiffOffset0;
DiffOffset6: a += 6; b += 6; goto DiffOffset0;
DiffOffset4: a += 2; b += 2;
DiffOffset2: a += 2; b += 2;
#endif // BIT64
DiffOffset0:
// If we reached here, we already see a difference in the unrolled loop above
#if BIT64
if (*(int*)a == *(int*)b)
{
a += 2; b += 2;
}
#endif // BIT64
DiffNextInt:
if (*a != *b) return *a - *b;
DiffOffset1:
Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
return *(a + 1) - *(b + 1);
}
}
// Provides a culture-correct string comparison. StrA is compared to StrB
// to determine whether it is lexicographically less, equal, or greater, and then returns
// either a negative integer, 0, or a positive integer; respectively.
//
public static int Compare(string strA, string strB)
{
return Compare(strA, strB, StringComparison.CurrentCulture);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase
//
public static int Compare(string strA, string strB, bool ignoreCase)
{
var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
return Compare(strA, strB, comparisonType);
}
// Provides a more flexible function for string comparison. See StringComparison
// for meaning of different comparisonType.
public static int Compare(string strA, string strB, StringComparison comparisonType)
{
if (object.ReferenceEquals(strA, strB))
{
CheckStringComparison(comparisonType);
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
CheckStringComparison(comparisonType);
return -1;
}
if (strB == null)
{
CheckStringComparison(comparisonType);
return 1;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CompareInfo.Invariant.Compare(strA, strB, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.Compare(strA, strB, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
// Most common case: first character is different.
// Returns false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
case StringComparison.OrdinalIgnoreCase:
#if CORECLR
// If both strings are ASCII strings, we can take the fast path.
if (strA.IsAscii() && strB.IsAscii())
{
return CompareOrdinalIgnoreCaseHelper(strA, strB);
}
#endif
return CompareInfo.CompareOrdinalIgnoreCase(strA, strB);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
//
public static int Compare(string strA, string strB, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
return culture.CompareInfo.Compare(strA, strB, options);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase, and the culture is set
// by culture
//
public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo culture)
{
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, strB, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of given length is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(string strA, int indexA, string strB, int indexB, int length)
{
// NOTE: It's important we call the boolean overload, and not the StringComparison
// one. The two have some subtly different behavior (see notes in the former).
return Compare(strA, indexA, strB, indexB, length, ignoreCase: false);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of given length is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean.
//
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase)
{
// Ideally we would just forward to the string.Compare overload that takes
// a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase.
// That function will return early if an optimization can be applied, e.g. if
// (object)strA == strB && indexA == indexB then it will return 0 straightaway.
// There are a couple of subtle behavior differences that prevent us from doing so
// however:
// - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works
// since that method also returns early for nulls before validation. It shouldn't
// for this overload.
// - Since we originally forwarded to CompareInfo.Compare for all of the argument
// validation logic, the ArgumentOutOfRangeExceptions thrown will contain different
// parameter names.
// Therefore, we have to duplicate some of the logic here.
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean,
// and the culture is set by culture.
//
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo culture)
{
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, indexA, strB, indexB, length, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(string strA, int indexA, string strB, int indexB, int length, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
return culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType)
{
CheckStringComparison(comparisonType);
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
{
string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CompareInfo.Invariant.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.OrdinalIgnoreCase:
return CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Compares strA and strB using an ordinal (code-point) comparison.
//
public static int CompareOrdinal(string strA, string strB)
{
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
// Most common case, first character is different.
// This will return false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int CompareOrdinal(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
=> SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(strA), strA.Length, ref MemoryMarshal.GetReference(strB), strB.Length);
// Compares strA and strB using an ordinal (code-point) comparison.
//
public static int CompareOrdinal(string strA, int indexA, string strB, int indexB, int length)
{
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
// COMPAT: Checking for nulls should become before the arguments are validated,
// but other optimizations which allow us to return early should come after.
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeCount);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
if (lengthA < 0 || lengthB < 0)
{
string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
}
// Compares this String to another String (cast as object), returning an integer that
// indicates the relationship. This method returns a value less than 0 if this is less than value, 0
// if this is equal to value, or a value greater than 0 if this is greater than value.
//
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
string other = value as string;
if (other == null)
{
throw new ArgumentException(SR.Arg_MustBeString);
}
return CompareTo(other); // will call the string-based overload
}
// Determines the sorting relation of StrB to the current instance.
//
public int CompareTo(string strB)
{
return string.Compare(this, strB, StringComparison.CurrentCulture);
}
// Determines whether a specified string is a suffix of the current instance.
//
// The case-sensitive and culture-sensitive option is set by options,
// and the default culture is used.
//
public bool EndsWith(string value)
{
return EndsWith(value, StringComparison.CurrentCulture);
}
public bool EndsWith(string value, StringComparison comparisonType)
{
if ((object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
CheckStringComparison(comparisonType);
return true;
}
if (value.Length == 0)
{
CheckStringComparison(comparisonType);
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CompareInfo.Invariant.IsSuffix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IsSuffix(this, value, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return this.Length < value.Length ? false : (CompareOrdinalHelper(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
case StringComparison.OrdinalIgnoreCase:
return this.Length < value.Length ? false : (CompareInfo.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public bool EndsWith(string value, bool ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture;
return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public bool EndsWith(char value)
{
int thisLen = Length;
return thisLen != 0 && this[thisLen - 1] == value;
}
// Determines whether two strings match.
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
string str = obj as string;
if (str == null)
return false;
if (this.Length != str.Length)
return false;
return EqualsHelper(this, str);
}
// Determines whether two strings match.
public bool Equals(string value)
{
if (object.ReferenceEquals(this, value))
return true;
// NOTE: No need to worry about casting to object here.
// If either side of an == comparison between strings
// is null, Roslyn generates a simple ceq instruction
// instead of calling string.op_Equality.
if (value == null)
return false;
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
}
public bool Equals(string value, StringComparison comparisonType)
{
if ((object)this == (object)value)
{
CheckStringComparison(comparisonType);
return true;
}
if ((object)value == null)
{
CheckStringComparison(comparisonType);
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0);
case StringComparison.InvariantCulture:
return (CompareInfo.Invariant.Compare(this, value, CompareOptions.None) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CompareInfo.Invariant.Compare(this, value, CompareOptions.IgnoreCase) == 0);
case StringComparison.Ordinal:
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length != value.Length)
return false;
#if CORECLR
// If both strings are ASCII strings, we can take the fast path.
if (this.IsAscii() && value.IsAscii())
{
return EqualsIgnoreCaseAsciiHelper(this, value);
}
#endif
return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Determines whether two Strings match.
public static bool Equals(string a, string b)
{
if ((object)a == (object)b)
{
return true;
}
if ((object)a == null || (object)b == null || a.Length != b.Length)
{
return false;
}
return EqualsHelper(a, b);
}
public static bool Equals(string a, string b, StringComparison comparisonType)
{
if ((object)a == (object)b)
{
CheckStringComparison(comparisonType);
return true;
}
if ((object)a == null || (object)b == null)
{
CheckStringComparison(comparisonType);
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0);
case StringComparison.InvariantCulture:
return (CompareInfo.Invariant.Compare(a, b, CompareOptions.None) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CompareInfo.Invariant.Compare(a, b, CompareOptions.IgnoreCase) == 0);
case StringComparison.Ordinal:
if (a.Length != b.Length)
return false;
return EqualsHelper(a, b);
case StringComparison.OrdinalIgnoreCase:
if (a.Length != b.Length)
return false;
#if CORECLR
// If both strings are ASCII strings, we can take the fast path.
if (a.IsAscii() && b.IsAscii())
{
return EqualsIgnoreCaseAsciiHelper(a, b);
}
#endif
return (CompareInfo.CompareOrdinalIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public static bool operator ==(string a, string b)
{
return string.Equals(a, b);
}
public static bool operator !=(string a, string b)
{
return !string.Equals(a, b);
}
// Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
// they will return the same hash code.
public override int GetHashCode()
{
return Marvin.ComputeHash32(ref Unsafe.As<char, byte>(ref _firstChar), _stringLength * 2, Marvin.DefaultSeed);
}
// Gets a hash code for this string and this comparison. If strings A and B and comparison C are such
// that string.Equals(A, B, C), then they will return the same hash code with this comparison C.
public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this);
// Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile
// hash table).
internal int GetLegacyNonRandomizedHashCode()
{
unsafe
{
fixed (char* src = &_firstChar)
{
Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary");
#if BIT64
int hash1 = 5381;
#else // !BIT64 (32)
int hash1 = (5381<<16) + 5381;
#endif
int hash2 = hash1;
#if BIT64
int c;
char* s = src;
while ((c = s[0]) != 0)
{
hash1 = ((hash1 << 5) + hash1) ^ c;
c = s[1];
if (c == 0)
break;
hash2 = ((hash2 << 5) + hash2) ^ c;
s += 2;
}
#else // !BIT64 (32)
// 32 bit machines.
int* pint = (int *)src;
int len = this.Length;
while (len > 2)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1];
pint += 2;
len -= 4;
}
if (len > 0)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
}
#endif
return hash1 + (hash2 * 1566083941);
}
}
}
// Determines whether a specified string is a prefix of the current instance
//
public bool StartsWith(string value)
{
if ((object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
return StartsWith(value, StringComparison.CurrentCulture);
}
public bool StartsWith(string value, StringComparison comparisonType)
{
if ((object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
CheckStringComparison(comparisonType);
return true;
}
if (value.Length == 0)
{
CheckStringComparison(comparisonType);
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CompareInfo.Invariant.IsPrefix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IsPrefix(this, value, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
if (this.Length < value.Length || _firstChar != value._firstChar)
{
return false;
}
return (value.Length == 1) ?
true : // First char is the same and thats all there is to compare
SpanHelpers.SequenceEqual(
ref Unsafe.As<char, byte>(ref this.GetRawStringData()),
ref Unsafe.As<char, byte>(ref value.GetRawStringData()),
((nuint)value.Length) * 2);
case StringComparison.OrdinalIgnoreCase:
if (this.Length < value.Length)
{
return false;
}
return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, value.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public bool StartsWith(string value, bool ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture;
return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public bool StartsWith(char value) => Length != 0 && _firstChar == value;
internal static void CheckStringComparison(StringComparison comparisonType)
{
// Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase]
if ((uint)(comparisonType - StringComparison.CurrentCulture) > (StringComparison.OrdinalIgnoreCase - StringComparison.CurrentCulture))
{
ThrowHelper.ThrowArgumentException(ExceptionResource.NotSupported_StringComparison, ExceptionArgument.comparisonType);
}
}
}
}
| |
using Pabo.Calendar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GrantApp
{
/// <summary>
/// The first page that is displayed after logging in.
/// Asks as menu for adding / removing database elements and displays upcoming notifications.
/// </summary>
public partial class MainPage : Form
{
/// <summary>
/// Class that represents a message and a grant.
/// Used to display messages for grants.
/// </summary>
private class Alert {
public string message;
public int grant_id;
public bool is_timeline_date;
public DateTime date;
public Alert(string message, int grant_id, DateTime date, bool is_timeline_date) {
this.message = message;
this.grant_id = grant_id;
this.date = date;
this.is_timeline_date = is_timeline_date;
}
public override string ToString() {
return String.Format("{0} ({1:MMM dd, yyyy})", message, date);
}
}
//associates alerts with dates
private Dictionary<DateTime, List<Alert>> alerts;
/// <summary>
/// Loads main page and displays alerts.
/// </summary>
public MainPage()
{
InitializeComponent();
this.monthCalendar2.ActiveMonth.Month = DateTime.Today.Month;
this.monthCalendar2.ActiveMonth.Year = DateTime.Today.Year;
alerts = new Dictionary<DateTime, List<Alert>>();
this.Activated += new EventHandler(this.formActivated);
//parameters of year select are max and min of the month calendar object
yearSpinner.Minimum = monthCalendar2.MinDate.Year;
yearSpinner.Maximum = monthCalendar2.MaxDate.Year;
yearSpinner.Value = monthCalendar2.ActiveMonth.Year;
//when year select is changed, change calendar
yearSpinner.ValueChanged += delegate(object o, EventArgs e) {
monthCalendar2.ActiveMonth.Year = (int)yearSpinner.Value;
};
//when calendar is changed, rotate year select
monthCalendar2.MonthChanged += delegate(object o, Pabo.Calendar.MonthChangedEventArgs e) {
yearSpinner.Value = monthCalendar2.ActiveMonth.Year;
};
monthCalendar2.DaySelected += monthCalendar2_DaySelected;
todayAlerts.DoubleClick += todaysAlerts_DoubleClick;
upcomingAlerts.DoubleClick += upcomingAlerts_DoubleClick;
//only show message on today's alerts, not date
todayAlerts.DisplayMember = "message";
//clear old values from changelog
cleanseChangelog();
}
/// <summary>
/// Clears entries in change log that are over 30 days old.
/// Called on start up when main page is loading.
/// </summary>
private void cleanseChangelog()
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
//find date on month earlier
DateTime dateOneMonthEarlier = DateTime.Now.AddDays(Settings.EraseChangelogEntriesThisManyDaysOld);
//remove entries before this date
var deleteEntries =
from dbchangelog in db.changelogs
where dbchangelog.date < dateOneMonthEarlier
select dbchangelog;
//delete
foreach (var log in deleteEntries)
{
db.changelogs.DeleteOnSubmit(log);
}
//try submitting changes
try
{
db.SubmitChanges();
}
catch (Exception e)
{
MessageBox.Show("A database error occured: old changelog values were not removed on start up.");
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
}
/// <summary>
/// Called when focus returns to main page.
/// Updates calendar to reflect new upcoming dates.
/// </summary>
void formActivated(object sender, EventArgs e)
{
PopulateCalendar();
}
/// <summary>
/// Called when a date is selected in the calendar.
/// Displays alerts for selected date below the calendar.
/// </summary>
void monthCalendar2_DaySelected(object sender, DaySelectedEventArgs e)
{
List<string> temp = new List<String>();
//clear old alerts
todayAlerts.Items.Clear();
//add alerts for selected date
var d = monthCalendar2.SelectedDates[0];
if (alerts.ContainsKey(d)) {
todayAlerts.Items.AddRange(alerts[d].ToArray());
}
}
/// <summary>
/// Colors dates in calendar depending on alerts for that date.
/// </summary>
private void PopulateCalendar()
{
//reset
monthCalendar2.ResetDateInfo();
alerts.Clear();
upcomingAlerts.Items.Clear();
Dictionary<DateTime, DateItem> list = new Dictionary<DateTime, DateItem>();
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
//for every grant
foreach (var g in (from g in db.grants
select new {
g.grant_name,
g.due_date,
g.grant_id
}))
{
//color due date red
if (g.due_date != null) {
var d = g.due_date.Value.Date;
list[d] = new Pabo.Calendar.DateItem() {
Date = d,
BackColor1 = Color.Red,
};
//add alert to list
if (!alerts.ContainsKey(d)) alerts.Add(d, new List<Alert>());
alerts[d].Add(new Alert("Due date for " + g.grant_name, g.grant_id, d, false));
}
}
foreach (var td in db.timeline_dates) {
var d = td.date.Date;
list[d] = new DateItem() {
Date = d,
BackColor1 = Color.FromName(td.color ?? "Cyan")
};
//add alert to list
if (!alerts.ContainsKey(d)) alerts.Add(d, new List<Alert>());
alerts[d].Add(new Alert(td.name, td.grant_id, d, true));
}
}
monthCalendar2.AddDateInfo(list.Values.ToArray());
var q = from a in alerts
where a.Key > DateTime.Today
&& a.Key <= DateTime.Today.AddMonths(1)
orderby a.Key
select a;
foreach (var pair in q) {
foreach (Alert s in pair.Value) {
upcomingAlerts.Items.Add(s);
}
}
}
/// <summary>
/// Opens the grant manager window.
/// </summary>
private void grants_Click(object sender, EventArgs e)
{
// carry current window state over to next view
GrantManager gm = new GrantManager();
gm.WindowState = this.WindowState;
gm.ShowDialog(this);
PopulateCalendar();
}
/// <summary>
/// Opens grantor manager window.
/// </summary>
private void grantors_Click(object sender, EventArgs e)
{
// carry current window state over to next view
GrantorManager gm = new GrantorManager();
gm.WindowState = this.WindowState;
gm.ShowDialog(this);
}
/// <summary>
/// Opens project manager window.
/// </summary>
private void projects_Click(object sender, EventArgs e)
{
// carry current window state over to next view
ProjectManager pm = new ProjectManager();
pm.WindowState = this.WindowState;
pm.ShowDialog(this);
}
/// <summary>
/// Opens admin menu.
/// </summary>
private void admin_Click(object sender, EventArgs eargs)
{
new Administration().ShowDialog(this);
}
/// <summary>
/// Called when an alert in the "today" list is double clicked.
/// Allows editing the grant (to possibly change completion date, etc).
/// </summary>
private void todaysAlerts_DoubleClick(object sender, EventArgs e)
{
Alert a = todayAlerts.SelectedItem as Alert;
if (a != null)
{
if (a.is_timeline_date) {
new TimelineManager(a.grant_id).ShowDialog(this);
} else {
new AddGrant(a.grant_id).ShowDialog(this);
}
}
}
/// <summary>
/// Called when an alert in the "upcoming" list is double clicked.
/// Allows editing the grant (to possibly change completion date, etc).
/// </summary>
private void upcomingAlerts_DoubleClick(object sender, EventArgs e) {
Alert a = upcomingAlerts.SelectedItem as Alert;
if (a != null) {
if (a.is_timeline_date) {
new TimelineManager(a.grant_id).ShowDialog(this);
} else {
new AddGrant(a.grant_id).ShowDialog(this);
}
}
}
}
}
| |
namespace FakeItEasy.Creation
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using FakeItEasy.Core;
using FakeItEasy.Creation.CastleDynamicProxy;
using FakeItEasy.Creation.DelegateProxies;
internal class FakeObjectCreator : IFakeObjectCreator, IMethodInterceptionValidator
{
private readonly DefaultCreationStrategy defaultCreationStrategy;
private readonly DelegateCreationStrategy delegateCreationStrategy;
public FakeObjectCreator(
FakeCallProcessorProvider.Factory fakeCallProcessorProviderFactory,
IMethodInterceptionValidator castleMethodInterceptionValidator,
IMethodInterceptionValidator delegateMethodInterceptionValidator)
{
this.defaultCreationStrategy = new DefaultCreationStrategy(castleMethodInterceptionValidator, fakeCallProcessorProviderFactory);
this.delegateCreationStrategy = new DelegateCreationStrategy(delegateMethodInterceptionValidator, fakeCallProcessorProviderFactory);
}
public CreationResult CreateFake(
Type typeOfFake,
IProxyOptions proxyOptions,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
if (!resolutionContext.TryBeginToResolve(typeOfFake))
{
return CreationResult.FailedToCreateFake(typeOfFake, "Recursive dependency detected. Already resolving " + typeOfFake + '.');
}
try
{
return this.CreateFakeWithoutLoopDetection(
typeOfFake,
proxyOptions,
resolver,
resolutionContext);
}
finally
{
resolutionContext.EndResolve(typeOfFake);
}
}
public CreationResult CreateFakeWithoutLoopDetection(
Type typeOfFake,
IProxyOptions proxyOptions,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
if (typeOfFake.IsInterface)
{
return this.defaultCreationStrategy.CreateFakeInterface(typeOfFake, proxyOptions);
}
return DelegateCreationStrategy.IsResponsibleForCreating(typeOfFake)
? this.delegateCreationStrategy.CreateFake(typeOfFake, proxyOptions)
: this.defaultCreationStrategy.CreateFake(typeOfFake, proxyOptions, resolver, resolutionContext);
}
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Seems appropriate here.")]
public bool MethodCanBeInterceptedOnInstance(MethodInfo method, object? callTarget, [NotNullWhen(false)] out string? failReason)
{
if (callTarget is not null && DelegateCreationStrategy.IsResponsibleForCreating(callTarget.GetType()))
{
return this.delegateCreationStrategy.MethodCanBeInterceptedOnInstance(method, callTarget, out failReason);
}
return this.defaultCreationStrategy.MethodCanBeInterceptedOnInstance(method, callTarget, out failReason);
}
private class DelegateCreationStrategy
{
private readonly FakeCallProcessorProvider.Factory fakeCallProcessorProviderFactory;
private readonly IMethodInterceptionValidator methodInterceptionValidator;
public DelegateCreationStrategy(
IMethodInterceptionValidator methodInterceptionValidator,
FakeCallProcessorProvider.Factory fakeCallProcessorProviderFactory)
{
this.methodInterceptionValidator = methodInterceptionValidator;
this.fakeCallProcessorProviderFactory = fakeCallProcessorProviderFactory;
}
public static bool IsResponsibleForCreating(Type typeOfFake) => typeof(Delegate).IsAssignableFrom(typeOfFake);
public CreationResult CreateFake(Type typeOfFake, IProxyOptions proxyOptions)
{
if (proxyOptions.Attributes.Any())
{
return CreationResult.FailedToCreateFake(typeOfFake, "Faked delegates cannot have custom attributes applied to them.");
}
if (proxyOptions.ArgumentsForConstructor is not null && proxyOptions.ArgumentsForConstructor.Any())
{
return CreationResult.FailedToCreateFake(typeOfFake, "Faked delegates cannot be made using explicit constructor arguments.");
}
if (proxyOptions.AdditionalInterfacesToImplement.Any())
{
return CreationResult.FailedToCreateFake(typeOfFake, "Faked delegates cannot be made to implement additional interfaces.");
}
var fakeCallProcessorProvider = this.fakeCallProcessorProviderFactory(typeOfFake, proxyOptions);
var proxyGeneratorResult = DelegateProxyGenerator.GenerateProxy(typeOfFake, fakeCallProcessorProvider);
return proxyGeneratorResult.ProxyWasSuccessfullyGenerated
? CreationResult.SuccessfullyCreated(proxyGeneratorResult.GeneratedProxy)
: CreationResult.FailedToCreateFake(typeOfFake, proxyGeneratorResult.ReasonForFailure!);
}
public bool MethodCanBeInterceptedOnInstance(MethodInfo method, object callTarget, [NotNullWhen(false)]out string? failReason) =>
this.methodInterceptionValidator.MethodCanBeInterceptedOnInstance(method, callTarget, out failReason);
}
private class DefaultCreationStrategy
{
private readonly FakeCallProcessorProvider.Factory fakeCallProcessorProviderFactory;
private readonly IMethodInterceptionValidator methodInterceptionValidator;
private readonly ConcurrentDictionary<Type, Type[]> parameterTypesCache;
public DefaultCreationStrategy(
IMethodInterceptionValidator methodInterceptionValidator,
FakeCallProcessorProvider.Factory fakeCallProcessorProviderFactory)
{
this.methodInterceptionValidator = methodInterceptionValidator;
this.fakeCallProcessorProviderFactory = fakeCallProcessorProviderFactory;
this.parameterTypesCache = new ConcurrentDictionary<Type, Type[]>();
}
public CreationResult CreateFakeInterface(Type typeOfFake, IProxyOptions proxyOptions)
{
if (proxyOptions.ArgumentsForConstructor is not null)
{
throw new ArgumentException(DynamicProxyMessages.ArgumentsForConstructorOnInterfaceType);
}
var fakeCallProcessorProvider = this.fakeCallProcessorProviderFactory(typeOfFake, proxyOptions);
var proxyGeneratorResult = CastleDynamicProxyGenerator.GenerateInterfaceProxy(
typeOfFake,
proxyOptions.AdditionalInterfacesToImplement,
proxyOptions.Attributes,
fakeCallProcessorProvider);
return proxyGeneratorResult.ProxyWasSuccessfullyGenerated
? CreationResult.SuccessfullyCreated(proxyGeneratorResult.GeneratedProxy)
: CreationResult.FailedToCreateFake(typeOfFake, proxyGeneratorResult.ReasonForFailure!);
}
public CreationResult CreateFake(
Type typeOfFake,
IProxyOptions proxyOptions,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
if (!CastleDynamicProxyGenerator.CanGenerateProxy(typeOfFake, out string? reasonCannotGenerate))
{
return CreationResult.FailedToCreateFake(typeOfFake, reasonCannotGenerate);
}
if (proxyOptions.ArgumentsForConstructor is not null)
{
var proxyGeneratorResult = this.GenerateProxy(typeOfFake, proxyOptions, proxyOptions.ArgumentsForConstructor);
return proxyGeneratorResult.ProxyWasSuccessfullyGenerated
? CreationResult.SuccessfullyCreated(proxyGeneratorResult.GeneratedProxy)
: CreationResult.FailedToCreateFake(typeOfFake, proxyGeneratorResult.ReasonForFailure!);
}
return this.TryCreateFakeWithDummyArgumentsForConstructor(
typeOfFake,
proxyOptions,
resolver,
resolutionContext);
}
public bool MethodCanBeInterceptedOnInstance(MethodInfo method, object? callTarget, [NotNullWhen(false)]out string? failReason) =>
this.methodInterceptionValidator.MethodCanBeInterceptedOnInstance(method, callTarget, out failReason);
private static IEnumerable<Type[]> GetUsableParameterTypeListsInOrder(Type type)
{
var allConstructors = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// Always try the parameterless constructor even if there are no constructors on the type. Some proxy generators
// can proxy types without constructors, such as interfaces.
if (!allConstructors.Any())
{
yield return Type.EmptyTypes;
yield break;
}
// Offer up all the constructors as possibilities.
// The 0-length constructor has always been tried first, which is advantageous because it's very easy to
// resolve the arguments. On the other hand, it can result in a less-configurable, Fake with more concrete
// (non-Faked) collaborators.
foreach (var parameterTypeList in allConstructors
.Select(c => c.GetParameters())
.OrderByDescending(pa => pa.Length == 0 ? int.MaxValue : pa.Length)
.Select(pa => pa.Select(p => p.ParameterType).ToArray()))
{
yield return parameterTypeList;
}
}
private static IEnumerable<object?> GetArgumentsForConstructor(ResolvedConstructor constructor) =>
constructor.Arguments.Select(x => x.ResolvedValue);
private CreationResult TryCreateFakeWithDummyArgumentsForConstructor(
Type typeOfFake,
IProxyOptions proxyOptions,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext)
{
// Save the constructors as we try them. Avoids eager evaluation and double evaluation
// of constructors enumerable.
var consideredConstructors = new List<ResolvedConstructor>();
if (this.parameterTypesCache.TryGetValue(typeOfFake, out Type[]? cachedParameterTypes))
{
var constructor = new ResolvedConstructor(cachedParameterTypes, resolver, resolutionContext);
if (constructor.WasSuccessfullyResolved)
{
var argumentsForConstructor = GetArgumentsForConstructor(constructor);
var result = this.GenerateProxy(typeOfFake, proxyOptions, argumentsForConstructor);
if (result.ProxyWasSuccessfullyGenerated)
{
return CreationResult.SuccessfullyCreated(result.GeneratedProxy);
}
constructor.ReasonForFailure = result.ReasonForFailure!;
}
consideredConstructors.Add(constructor);
}
else
{
foreach (var parameterTypes in GetUsableParameterTypeListsInOrder(typeOfFake))
{
var constructor = new ResolvedConstructor(parameterTypes, resolver, resolutionContext);
if (constructor.WasSuccessfullyResolved)
{
var argumentsForConstructor = GetArgumentsForConstructor(constructor);
var result = this.GenerateProxy(typeOfFake, proxyOptions, argumentsForConstructor);
if (result.ProxyWasSuccessfullyGenerated)
{
this.parameterTypesCache.TryAdd(typeOfFake, parameterTypes);
return CreationResult.SuccessfullyCreated(result.GeneratedProxy);
}
constructor.ReasonForFailure = result.ReasonForFailure!;
}
consideredConstructors.Add(constructor);
}
}
return CreationResult.FailedToCreateFake(typeOfFake, consideredConstructors);
}
private ProxyGeneratorResult GenerateProxy(Type typeOfFake, IProxyOptions proxyOptions, IEnumerable<object?> argumentsForConstructor)
{
var fakeCallProcessorProvider = this.fakeCallProcessorProviderFactory(typeOfFake, proxyOptions);
return CastleDynamicProxyGenerator.GenerateClassProxy(
typeOfFake,
proxyOptions.AdditionalInterfacesToImplement,
argumentsForConstructor,
proxyOptions.Attributes,
fakeCallProcessorProvider);
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Text;
using System.Web;
using ASC.Core;
using ASC.Core.Users;
using ASC.Web.Community.Modules.Wiki.Resources;
using ASC.Web.Community.Product;
using ASC.Web.Core;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.UserControls.Common.HelpCenter;
using ASC.Web.Studio.UserControls.Common.InviteLink;
using ASC.Web.Studio.UserControls.Common.Support;
using ASC.Web.Studio.UserControls.Common.UserForum;
using Newtonsoft.Json.Linq;
namespace ASC.Web.Community.Controls
{
public partial class NavigationSidePanel : System.Web.UI.UserControl
{
public static String Location = VirtualPathUtility.ToAbsolute("~/Products/Community/Controls/NavigationSidePanel.ascx");
protected string CurrentPage { get; set; }
protected bool IsInBlogs { get; set; }
protected bool IsInEvents { get; set; }
protected bool IsInSettings { get; set; }
protected bool IsInBookmarks { get; set; }
protected bool IsInWiki { get; set; }
protected bool IsBlogsAvailable { get; set; }
protected bool IsEventsAvailable { get; set; }
protected bool IsForumsAvailable { get; set; }
protected bool IsBookmarksAvailable { get; set; }
protected bool IsWikiAvailable { get; set; }
protected bool IsBirthdaysAvailable { get; set; }
protected bool IsAdmin { get; set; }
protected bool IsVisitor { get; set; }
protected bool IsFullAdministrator { get; set; }
protected int TopicID
{
get
{
int result;
return int.TryParse(Request["t"], out result) ? result : 0;
}
}
protected int ForumID
{
get
{
int result;
return int.TryParse(Request["f"], out result) ? result : 0;
}
}
protected bool InAParticularTopic { get; set; }
protected bool MakeCreateNewTopic { get; set; }
protected bool ForumsHasThreadCategories { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
IsAdmin = WebItemSecurity.IsProductAdministrator(CommunityProduct.ID, SecurityContext.CurrentAccount.ID);
IsVisitor = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor();
IsFullAdministrator = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin();
InitCurrentPage();
InitPermission();
InitModulesState();
var help = (HelpCenter)LoadControl(HelpCenter.Location);
help.IsSideBar = true;
HelpHolder.Controls.Add(help);
SupportHolder.Controls.Add(LoadControl(Support.Location));
UserForumHolder.Controls.Add(LoadControl(UserForum.Location));
InviteUserHolder.Controls.Add(LoadControl(InviteLink.Location));
}
private void InitPermission()
{
foreach (var module in WebItemManager.Instance.GetSubItems(CommunityProduct.ID))
{
switch (module.GetSysName())
{
case "community-blogs":
IsBlogsAvailable = true;
break;
case "community-news":
IsEventsAvailable = true;
break;
case "community-forum":
InitForumsData();
break;
case "community-bookmarking":
IsBookmarksAvailable = true;
break;
case "community-wiki":
IsWikiAvailable = true;
break;
case "community-birthdays":
IsBirthdaysAvailable = true;
break;
}
}
}
private void InitCurrentPage()
{
var currentPath = HttpContext.Current.Request.Path;
if (currentPath.IndexOf("Modules/Blogs", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "blogs";
if (currentPath.IndexOf("AllBlogs.aspx", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "allblogs";
}
}
else if (currentPath.IndexOf("Modules/News", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "events";
if (currentPath.IndexOf("EditPoll.aspx", StringComparison.OrdinalIgnoreCase) > 0)
{
}
else if (currentPath.IndexOf("EditNews.aspx", StringComparison.OrdinalIgnoreCase) > 0)
{
}
else
{
var type = Request["type"];
if (!string.IsNullOrEmpty(type))
{
switch (type)
{
case "News":
CurrentPage = "news";
break;
case "Order":
CurrentPage = "order";
break;
case "Advert":
CurrentPage = "advert";
break;
case "Poll":
CurrentPage = "poll";
break;
}
}
}
}
else if (currentPath.IndexOf("Modules/Forum", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "forum";
if (currentPath.IndexOf("ManagementCenter.aspx", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "forumeditor";
}
if (currentPath.IndexOf("Posts.aspx", StringComparison.OrdinalIgnoreCase) > 0)
{
InAParticularTopic = true;
MakeCreateNewTopic = true;
}
}
else if (currentPath.IndexOf("Modules/Bookmarking", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "bookmarking";
if (currentPath.IndexOf("FavouriteBookmarks.aspx", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "bookmarkingfavourite";
}
}
else if (currentPath.IndexOf("Modules/Wiki", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "wiki";
if (currentPath.IndexOf("ListCategories.aspx", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "wikicategories";
}
if (currentPath.IndexOf("ListPages.aspx", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "wikiindex";
var type = Request["n"];
if (type != null)
{
CurrentPage = "wikinew";
}
type = Request["f"];
if (type != null)
{
CurrentPage = "wikirecently";
}
}
if (currentPath.IndexOf("ListFiles.aspx", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "wikifiles";
}
var page = Request["page"];
if (!string.IsNullOrEmpty(page))
{
if (page.StartsWith("Category:"))
CurrentPage = "wikicategories";
if (page == WikiUCResource.HelpPageCaption)
CurrentPage = "wikihelp";
}
}
else if (currentPath.IndexOf("Modules/Birthdays", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "birthdays";
}
else if (currentPath.IndexOf("Help.aspx", StringComparison.OrdinalIgnoreCase) > 0)
{
CurrentPage = "help";
}
else
{
CurrentPage = "blogs";
}
}
private void InitModulesState()
{
IsInBlogs = CurrentPage == "allblogs";
IsInEvents = CurrentPage == "news" ||
CurrentPage == "order" ||
CurrentPage == "advert" ||
CurrentPage == "poll";
IsInSettings = CurrentPage == "forumeditor";
IsInBookmarks = CurrentPage == "bookmarkingfavourite";
IsInWiki = CurrentPage == "wikicategories" ||
CurrentPage == "wikiindex" ||
CurrentPage == "wikinew" ||
CurrentPage == "wikirecently" ||
CurrentPage == "wikifiles" ||
CurrentPage == "wikihelp";
}
private void InitForumsData()
{
IsForumsAvailable = true;
var apiServer = new Api.ApiServer();
var apiResponse = apiServer.GetApiResponse(String.Format("{0}community/forum/count.json", SetupInfo.WebApiBaseUrl), "GET");
var obj = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(apiResponse)));
var count = 0;
if (Int32.TryParse(obj["response"].ToString(), out count))
ForumsHasThreadCategories = count > 0;
if (InAParticularTopic && TopicID > 0)
{
apiServer = new Api.ApiServer();
apiResponse = apiServer.GetApiResponse(String.Format("{0}community/forum/topic/{1}.json", SetupInfo.WebApiBaseUrl, TopicID), "GET");
obj = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(apiResponse)));
if (obj["response"] != null)
{
obj = JObject.Parse(obj["response"].ToString());
var status = 0;
if (Int32.TryParse(obj["status"].ToString(), out status))
MakeCreateNewTopic = status != 1 && status != 3;
}
}
}
protected string GetDefaultSettingsPageUrl()
{
var defaultUrl = VirtualPathUtility.ToAbsolute("~/Management.aspx") + "?type=" + (int)ASC.Web.Studio.Utility.ManagementType.AccessRights + "#community";
if (IsForumsAvailable)
{
defaultUrl = VirtualPathUtility.ToAbsolute("~/Products/Community/Modules/Forum/ManagementCenter.aspx");
}
return defaultUrl;
}
}
}
| |
using ClosedXML.Excel.CalcEngine.Exceptions;
using ClosedXML.Excel.CalcEngine.Functions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClosedXML.Excel.CalcEngine
{
internal static class MathTrig
{
private static readonly Random _rnd = new Random();
public static void Register(CalcEngine ce)
{
ce.RegisterFunction("ABS", 1, Abs);
ce.RegisterFunction("ACOS", 1, Acos);
ce.RegisterFunction("ACOSH", 1, Acosh);
ce.RegisterFunction("ACOT", 1, Acot);
ce.RegisterFunction("ACOTH", 1, Acoth);
ce.RegisterFunction("ARABIC", 1, Arabic);
ce.RegisterFunction("ASIN", 1, Asin);
ce.RegisterFunction("ASINH", 1, Asinh);
ce.RegisterFunction("ATAN", 1, Atan);
ce.RegisterFunction("ATAN2", 2, Atan2);
ce.RegisterFunction("ATANH", 1, Atanh);
ce.RegisterFunction("BASE", 2, 3, Base);
ce.RegisterFunction("CEILING", 1, Ceiling);
ce.RegisterFunction("COMBIN", 2, Combin);
ce.RegisterFunction("COMBINA", 2, CombinA);
ce.RegisterFunction("COS", 1, Cos);
ce.RegisterFunction("COSH", 1, Cosh);
ce.RegisterFunction("COT", 1, Cot);
ce.RegisterFunction("COTH", 1, Coth);
ce.RegisterFunction("CSC", 1, Csc);
ce.RegisterFunction("CSCH", 1, Csch);
ce.RegisterFunction("DECIMAL", 2, MathTrig.Decimal);
ce.RegisterFunction("DEGREES", 1, Degrees);
ce.RegisterFunction("EVEN", 1, Even);
ce.RegisterFunction("EXP", 1, Exp);
ce.RegisterFunction("FACT", 1, Fact);
ce.RegisterFunction("FACTDOUBLE", 1, FactDouble);
ce.RegisterFunction("FLOOR", 1, 2, Floor);
ce.RegisterFunction("FLOOR.MATH", 1, 3, FloorMath);
ce.RegisterFunction("GCD", 1, 255, Gcd);
ce.RegisterFunction("INT", 1, Int);
ce.RegisterFunction("LCM", 1, 255, Lcm);
ce.RegisterFunction("LN", 1, Ln);
ce.RegisterFunction("LOG", 1, 2, Log);
ce.RegisterFunction("LOG10", 1, Log10);
ce.RegisterFunction("MDETERM", 1, MDeterm);
ce.RegisterFunction("MINVERSE", 1, MInverse);
ce.RegisterFunction("MMULT", 2, MMult);
ce.RegisterFunction("MOD", 2, Mod);
ce.RegisterFunction("MROUND", 2, MRound);
ce.RegisterFunction("MULTINOMIAL", 1, 255, Multinomial);
ce.RegisterFunction("ODD", 1, Odd);
ce.RegisterFunction("PI", 0, Pi);
ce.RegisterFunction("POWER", 2, Power);
ce.RegisterFunction("PRODUCT", 1, 255, Product);
ce.RegisterFunction("QUOTIENT", 2, Quotient);
ce.RegisterFunction("RADIANS", 1, Radians);
ce.RegisterFunction("RAND", 0, Rand);
ce.RegisterFunction("RANDBETWEEN", 2, RandBetween);
ce.RegisterFunction("ROMAN", 1, 2, Roman);
ce.RegisterFunction("ROUND", 2, Round);
ce.RegisterFunction("ROUNDDOWN", 2, RoundDown);
ce.RegisterFunction("ROUNDUP", 1, 2, RoundUp);
ce.RegisterFunction("SEC", 1, Sec);
ce.RegisterFunction("SECH", 1, Sech);
ce.RegisterFunction("SERIESSUM", 4, SeriesSum);
ce.RegisterFunction("SIGN", 1, Sign);
ce.RegisterFunction("SIN", 1, Sin);
ce.RegisterFunction("SINH", 1, Sinh);
ce.RegisterFunction("SQRT", 1, Sqrt);
ce.RegisterFunction("SQRTPI", 1, SqrtPi);
ce.RegisterFunction("SUBTOTAL", 2, 255, Subtotal);
ce.RegisterFunction("SUM", 1, int.MaxValue, Sum);
ce.RegisterFunction("SUMIF", 2, 3, SumIf);
ce.RegisterFunction("SUMIFS", 3, 255, SumIfs);
ce.RegisterFunction("SUMPRODUCT", 1, 30, SumProduct);
ce.RegisterFunction("SUMSQ", 1, 255, SumSq);
//ce.RegisterFunction("SUMX2MY2", SumX2MY2, 1);
//ce.RegisterFunction("SUMX2PY2", SumX2PY2, 1);
//ce.RegisterFunction("SUMXMY2", SumXMY2, 1);
ce.RegisterFunction("TAN", 1, Tan);
ce.RegisterFunction("TANH", 1, Tanh);
ce.RegisterFunction("TRUNC", 1, Trunc);
}
private static object Abs(List<Expression> p)
{
return Math.Abs(p[0]);
}
private static object Acos(List<Expression> p)
{
double input = p[0];
if (Math.Abs(input) > 1)
throw new NumberException();
return Math.Acos(p[0]);
}
private static object Asin(List<Expression> p)
{
double input = p[0];
if (Math.Abs(input) > 1)
throw new NumberException();
return Math.Asin(input);
}
private static object Atan(List<Expression> p)
{
return Math.Atan(p[0]);
}
private static object Atan2(List<Expression> p)
{
double x = p[0];
double y = p[1];
if (x == 0 && y == 0)
throw new DivisionByZeroException();
return Math.Atan2(y, x);
}
private static object Ceiling(List<Expression> p)
{
return Math.Ceiling(p[0]);
}
private static object Cos(List<Expression> p)
{
return Math.Cos(p[0]);
}
private static object Cosh(List<Expression> p)
{
return Math.Cosh(p[0]);
}
private static object Cot(List<Expression> p)
{
var tan = (double)Math.Tan(p[0]);
if (tan == 0)
throw new DivisionByZeroException();
return 1 / tan;
}
private static object Coth(List<Expression> p)
{
double input = p[0];
if (input == 0)
throw new DivisionByZeroException();
return 1 / Math.Tanh(input);
}
private static object Csc(List<Expression> p)
{
double input = p[0];
if (input == 0)
throw new DivisionByZeroException();
return 1 / Math.Sin(input);
}
private static object Csch(List<Expression> p)
{
if (Math.Abs((double)p[0].Evaluate()) < Double.Epsilon)
throw new DivisionByZeroException();
return 1 / Math.Sinh(p[0]);
}
private static object Decimal(List<Expression> p)
{
string source = p[0];
double radix = p[1];
if (radix < 2 || radix > 36)
throw new NumberException();
var asciiValues = Encoding.ASCII.GetBytes(source.ToUpperInvariant());
double result = 0;
int i = 0;
foreach (byte digit in asciiValues)
{
if (digit > 90)
{
throw new NumberException();
}
int digitNumber = digit >= 48 && digit < 58
? digit - 48
: digit - 55;
if (digitNumber > radix - 1)
throw new NumberException();
result = result * radix + digitNumber;
i++;
}
return result;
}
private static object Exp(List<Expression> p)
{
return Math.Exp(p[0]);
}
private static object Floor(List<Expression> p)
{
double number = p[0];
double significance = 1;
if (p.Count > 1)
significance = p[1];
if (significance < 0)
{
number = -number;
significance = -significance;
return -Math.Floor(number / significance) * significance;
}
else if (significance == 1)
return Math.Floor(number);
else
return Math.Floor(number / significance) * significance;
}
private static object FloorMath(List<Expression> p)
{
double number = p[0];
double significance = 1;
if (p.Count > 1) significance = p[1];
double mode = 0;
if (p.Count > 2) mode = p[2];
if (number >= 0)
return Math.Floor(number / Math.Abs(significance)) * Math.Abs(significance);
else if (mode >= 0)
return Math.Floor(number / Math.Abs(significance)) * Math.Abs(significance);
else
return -Math.Floor(-number / Math.Abs(significance)) * Math.Abs(significance);
}
private static object Int(List<Expression> p)
{
return Math.Floor(p[0]);
}
private static object Ln(List<Expression> p)
{
return Math.Log(p[0]);
}
private static object Log(List<Expression> p)
{
var lbase = p.Count > 1 ? (double)p[1] : 10;
return Math.Log(p[0], lbase);
}
private static object Log10(List<Expression> p)
{
return Math.Log10(p[0]);
}
private static object Pi(List<Expression> p)
{
return Math.PI;
}
private static object Power(List<Expression> p)
{
return Math.Pow(p[0], p[1]);
}
private static object Rand(List<Expression> p)
{
return _rnd.NextDouble();
}
private static object RandBetween(List<Expression> p)
{
return _rnd.Next((int)(double)p[0], (int)(double)p[1]);
}
private static object Sign(List<Expression> p)
{
return Math.Sign(p[0]);
}
private static object Sin(List<Expression> p)
{
return Math.Sin(p[0]);
}
private static object Sinh(List<Expression> p)
{
return Math.Sinh(p[0]);
}
private static object Sqrt(List<Expression> p)
{
return Math.Sqrt(p[0]);
}
private static object Sum(List<Expression> p)
{
var tally = new Tally();
foreach (var e in p)
{
tally.Add(e);
}
return tally.Sum();
}
private static object SumIf(List<Expression> p)
{
// get parameters
var range = p[0] as IEnumerable; // range of values to match the criteria against
var sumRange = p.Count < 3 ?
p[0] as XObjectExpression :
p[2] as XObjectExpression; // range of values to sum up
var criteria = p[1].Evaluate(); // the criteria to evaluate
// build list of values in range and sumRange
var rangeValues = new List<object>();
foreach (var value in range)
{
rangeValues.Add(value);
}
var sumRangeValues = new List<object>();
foreach (var value in sumRange)
{
sumRangeValues.Add(value);
}
// compute total
var ce = new CalcEngine();
var tally = new Tally();
for (var i = 0; i < Math.Max(rangeValues.Count, sumRangeValues.Count); i++)
{
var targetValue = i < rangeValues.Count ? rangeValues[i] : string.Empty;
if (CalcEngineHelpers.ValueSatisfiesCriteria(targetValue, criteria, ce))
{
var value = i < sumRangeValues.Count ? sumRangeValues[i] : 0d;
tally.AddValue(value);
}
}
// done
return tally.Sum();
}
private static object SumIfs(List<Expression> p)
{
// get parameters
var sumRange = p[0] as IEnumerable;
var sumRangeValues = new List<object>();
foreach (var value in sumRange)
{
sumRangeValues.Add(value);
}
var ce = new CalcEngine();
var tally = new Tally();
int numberOfCriteria = p.Count / 2; // int division returns floor() automatically, that's what we want.
// prepare criteria-parameters:
var criteriaRanges = new Tuple<object, IList<object>>[numberOfCriteria];
for (int criteriaPair = 0; criteriaPair < numberOfCriteria; criteriaPair++)
{
var criteriaRange = p[criteriaPair * 2 + 1] as IEnumerable;
if (criteriaRange == null)
throw new CellReferenceException($"Expected parameter {criteriaPair * 2 + 2} to be a range");
var criterion = p[criteriaPair * 2 + 2].Evaluate();
var criteriaRangeValues = criteriaRange.Cast<Object>().ToList();
criteriaRanges[criteriaPair] = new Tuple<object, IList<object>>(
criterion,
criteriaRangeValues);
}
for (var i = 0; i < sumRangeValues.Count; i++)
{
bool shouldUseValue = true;
foreach (var criteriaPair in criteriaRanges)
{
if (!CalcEngineHelpers.ValueSatisfiesCriteria(
i < criteriaPair.Item2.Count ? criteriaPair.Item2[i] : string.Empty,
criteriaPair.Item1,
ce))
{
shouldUseValue = false;
break; // we're done with the inner loop as we can't ever get true again.
}
}
if (shouldUseValue)
tally.AddValue(sumRangeValues[i]);
}
// done
return tally.Sum();
}
private static object SumProduct(List<Expression> p)
{
// all parameters should be IEnumerable
if (p.Any(param => !(param is IEnumerable)))
throw new NoValueAvailableException();
var counts = p.Cast<IEnumerable>().Select(param =>
{
int i = 0;
foreach (var item in param)
i++;
return i;
})
.Distinct();
// All parameters should have the same length
if (counts.Count() > 1)
throw new NoValueAvailableException();
var values = p
.Cast<IEnumerable>()
.Select(range =>
{
var results = new List<double>();
foreach (var c in range)
{
if (c.IsNumber())
results.Add(c.CastTo<double>());
else
results.Add(0.0);
}
return results;
})
.ToArray();
return Enumerable.Range(0, counts.Single())
.Aggregate(0d, (t, i) =>
t + values.Aggregate(1d,
(product, list) => product * list[i]
)
);
}
private static object Tan(List<Expression> p)
{
return Math.Tan(p[0]);
}
private static object Tanh(List<Expression> p)
{
return Math.Tanh(p[0]);
}
private static object Trunc(List<Expression> p)
{
return (double)(int)((double)p[0]);
}
public static double DegreesToRadians(double degrees)
{
return (Math.PI / 180.0) * degrees;
}
public static double RadiansToDegrees(double radians)
{
return (180.0 / Math.PI) * radians;
}
public static double GradsToRadians(double grads)
{
return (grads / 200.0) * Math.PI;
}
public static double RadiansToGrads(double radians)
{
return (radians / Math.PI) * 200.0;
}
public static double DegreesToGrads(double degrees)
{
return (degrees / 9.0) * 10.0;
}
public static double GradsToDegrees(double grads)
{
return (grads / 10.0) * 9.0;
}
public static double ASinh(double x)
{
return (Math.Log(x + Math.Sqrt(x * x + 1.0)));
}
private static object Acosh(List<Expression> p)
{
double number = p[0];
if (number < 1)
throw new NumberException();
return XLMath.ACosh(p[0]);
}
private static object Acot(List<Expression> p)
{
double x = Math.Atan(1.0 / p[0]);
// Acot in Excel calculates the modulus of the function above.
// as the % operator is not the modulus, but the remainder, we have to calculate the modulus by hand:
while (x < 0)
x = x + Math.PI;
return x;
}
private static object Acoth(List<Expression> p)
{
double number = p[0];
if (Math.Abs(number) < 1)
throw new NumberException();
return 0.5 * Math.Log((number + 1) / (number - 1));
}
private static object Arabic(List<Expression> p)
{
string input = ((string)p[0]).Trim();
try
{
if (input == "")
return 0;
if (input == "-")
throw new NumberException();
else if (input[0] == '-')
return -XLMath.RomanToArabic(input.Substring(1));
else
return XLMath.RomanToArabic(input);
}
catch (ArgumentOutOfRangeException)
{
throw new CellValueException();
}
catch
{
throw;
}
}
private static object Asinh(List<Expression> p)
{
return XLMath.ASinh(p[0]);
}
private static object Atanh(List<Expression> p)
{
double input = p[0];
if (Math.Abs(input) >= 1)
throw new NumberException();
return XLMath.ATanh(p[0]);
}
private static object Base(List<Expression> p)
{
long number;
int radix;
int minLength = 0;
var rawNumber = p[0].Evaluate();
if (rawNumber is long || rawNumber is int || rawNumber is byte || rawNumber is double || rawNumber is float)
number = Convert.ToInt64(rawNumber);
else
throw new CellValueException();
var rawRadix = p[1].Evaluate();
if (rawRadix is long || rawRadix is int || rawRadix is byte || rawRadix is double || rawRadix is float)
radix = Convert.ToInt32(rawRadix);
else
throw new CellValueException();
if (p.Count > 2)
{
var rawMinLength = p[2].Evaluate();
if (rawMinLength is long || rawMinLength is int || rawMinLength is byte || rawMinLength is double || rawMinLength is float)
minLength = Convert.ToInt32(rawMinLength);
else
throw new CellValueException();
}
if (number < 0 || radix < 2 || radix > 36)
throw new NumberException();
return XLMath.ChangeBase(number, radix).PadLeft(minLength, '0');
}
private static object Combin(List<Expression> p)
{
Int32 n;
Int32 k;
var rawN = p[0].Evaluate();
var rawK = p[1].Evaluate();
if (rawN is long || rawN is int || rawN is byte || rawN is double || rawN is float)
n = (int)Math.Floor((double)rawN);
else
throw new NumberException();
if (rawK is long || rawK is int || rawK is byte || rawK is double || rawK is float)
k = (int)Math.Floor((double)rawK);
else
throw new NumberException();
n = (int)p[0];
k = (int)p[1];
if (n < 0 || n < k || k < 0)
throw new NumberException();
return XLMath.Combin(n, k);
}
private static object CombinA(List<Expression> p)
{
Int32 number = (int)p[0]; // casting truncates towards 0 as specified
Int32 chosen = (int)p[1];
if (number < 0 || number < chosen)
throw new NumberException();
if (chosen < 0)
throw new NumberException();
int n = number + chosen - 1;
int k = number - 1;
return n == k || k == 0
? 1
: (long)XLMath.Combin(n, k);
}
private static object Degrees(List<Expression> p)
{
return p[0] * (180.0 / Math.PI);
}
private static object Fact(List<Expression> p)
{
var input = p[0].Evaluate();
if (!(input is long || input is int || input is byte || input is double || input is float))
throw new CellValueException();
var num = Math.Floor((double)input);
double fact = 1.0;
if (num < 0)
throw new NumberException();
if (num > 1)
for (int i = 2; i <= num; i++)
fact *= i;
return fact;
}
private static object FactDouble(List<Expression> p)
{
var input = p[0].Evaluate();
if (!(input is long || input is int || input is byte || input is double || input is float))
throw new CellValueException();
var num = Math.Floor(p[0]);
double fact = 1.0;
if (num < -1)
throw new NumberException();
if (num > 1)
{
var start = Math.Abs(num % 2) < XLHelper.Epsilon ? 2 : 1;
for (int i = start; i <= num; i = i + 2)
fact *= i;
}
return fact;
}
private static object Gcd(List<Expression> p)
{
return p.Select(v => (int)v).Aggregate(Gcd);
}
private static int Gcd(int a, int b)
{
return b == 0 ? a : Gcd(b, a % b);
}
private static object Lcm(List<Expression> p)
{
return p.Select(v => (int)v).Aggregate(Lcm);
}
private static int Lcm(int a, int b)
{
if (a == 0 || b == 0) return 0;
return a * (b / Gcd(a, b));
}
private static object Mod(List<Expression> p)
{
double number = p[0];
double divisor = p[1];
return number - Math.Floor(number / divisor) * divisor;
}
private static object MRound(List<Expression> p)
{
var n = (Decimal)(Double)p[0];
var k = (Decimal)(Double)p[1];
var mod = n % k;
var mult = Math.Floor(n / k);
var div = k / 2;
if (Math.Abs(mod - div) <= (Decimal)XLHelper.Epsilon) return (k * mult) + k;
return k * mult;
}
private static object Multinomial(List<Expression> p)
{
return Multinomial(p.Select(v => (double)v).ToList());
}
private static double Multinomial(List<double> numbers)
{
double numbersSum = 0;
foreach (var number in numbers)
numbersSum += number;
double maxNumber = numbers.Max();
var denomFactorPowers = new double[(uint)numbers.Max() + 1];
foreach (var number in numbers)
for (int i = 2; i <= number; i++)
denomFactorPowers[i]++;
for (int i = 2; i < denomFactorPowers.Length; i++)
denomFactorPowers[i]--; // reduce with nominator;
int currentFactor = 2;
double currentPower = 1;
double result = 1;
for (double i = maxNumber + 1; i <= numbersSum; i++)
{
double tempDenom = 1;
while (tempDenom < result && currentFactor < denomFactorPowers.Length)
{
if (currentPower > denomFactorPowers[currentFactor])
{
currentFactor++;
currentPower = 1;
}
else
{
tempDenom *= currentFactor;
currentPower++;
}
}
result = result / tempDenom * i;
}
return result;
}
private static object Odd(List<Expression> p)
{
var num = (int)Math.Ceiling(p[0]);
var addValue = num >= 0 ? 1 : -1;
return XLMath.IsOdd(num) ? num : num + addValue;
}
private static object Even(List<Expression> p)
{
var num = (int)Math.Ceiling(p[0]);
var addValue = num >= 0 ? 1 : -1;
return XLMath.IsEven(num) ? num : num + addValue;
}
private static object Product(List<Expression> p)
{
if (p.Count == 0) return 0;
Double total = 1;
p.ForEach(v => total *= v);
return total;
}
private static object Quotient(List<Expression> p)
{
Double n = p[0];
Double k = p[1];
return (int)(n / k);
}
private static object Radians(List<Expression> p)
{
return p[0] * Math.PI / 180.0;
}
private static object Roman(List<Expression> p)
{
if (p.Count == 1
|| (Boolean.TryParse(p[1]._token.Value.ToString(), out bool boolTemp) && boolTemp)
|| (Int32.TryParse(p[1]._token.Value.ToString(), out int intTemp) && intTemp == 1))
return XLMath.ToRoman((int)p[0]);
throw new ArgumentException("Can only support classic roman types.");
}
private static object Round(List<Expression> p)
{
var value = (Double)p[0];
var digits = (Int32)(Double)p[1];
if (digits >= 0)
{
return Math.Round(value, digits, MidpointRounding.AwayFromZero);
}
else
{
digits = Math.Abs(digits);
double temp = value / Math.Pow(10, digits);
temp = Math.Round(temp, 0, MidpointRounding.AwayFromZero);
return temp * Math.Pow(10, digits);
}
}
private static object RoundDown(List<Expression> p)
{
var value = (Double)p[0];
var digits = (Int32)(Double)p[1];
if (value >= 0)
return Math.Floor(value * Math.Pow(10, digits)) / Math.Pow(10, digits);
return Math.Ceiling(value * Math.Pow(10, digits)) / Math.Pow(10, digits);
}
private static object RoundUp(List<Expression> p)
{
var value = (Double)p[0];
var digits = (Int32)(Double)p[1];
if (value >= 0)
return Math.Ceiling(value * Math.Pow(10, digits)) / Math.Pow(10, digits);
return Math.Floor(value * Math.Pow(10, digits)) / Math.Pow(10, digits);
}
private static object Sec(List<Expression> p)
{
if (double.TryParse(p[0], out double number))
return 1.0 / Math.Cos(number);
else
throw new CellValueException();
}
private static object Sech(List<Expression> p)
{
return 1.0 / Math.Cosh(p[0]);
}
private static object SeriesSum(List<Expression> p)
{
var x = (Double)p[0];
var n = (Double)p[1];
var m = (Double)p[2];
var obj = p[3] as XObjectExpression;
if (obj == null)
return p[3] * Math.Pow(x, n);
Double total = 0;
Int32 i = 0;
foreach (var e in obj)
{
total += (double)e * Math.Pow(x, n + i * m);
i++;
}
return total;
}
private static object SqrtPi(List<Expression> p)
{
var num = (Double)p[0];
return Math.Sqrt(Math.PI * num);
}
private static object Subtotal(List<Expression> p)
{
var fId = (int)(Double)p[0];
var tally = new Tally(p.Skip(1));
switch (fId)
{
case 1:
return tally.Average();
case 2:
return tally.Count(true);
case 3:
return tally.Count(false);
case 4:
return tally.Max();
case 5:
return tally.Min();
case 6:
return tally.Product();
case 7:
return tally.Std();
case 8:
return tally.StdP();
case 9:
return tally.Sum();
case 10:
return tally.Var();
case 11:
return tally.VarP();
default:
throw new ArgumentException("Function not supported.");
}
}
private static object SumSq(List<Expression> p)
{
var t = new Tally(p);
return t.NumericValues().Sum(v => Math.Pow(v, 2));
}
private static object MMult(List<Expression> p)
{
Double[,] A = GetArray(p[0]);
Double[,] B = GetArray(p[1]);
if (A.GetLength(0) != B.GetLength(0) || A.GetLength(1) != B.GetLength(1))
throw new ArgumentException("Ranges must have the same number of rows and columns.");
var C = new double[A.GetLength(0), A.GetLength(1)];
for (int i = 0; i < A.GetLength(0); i++)
{
for (int j = 0; j < B.GetLength(1); j++)
{
for (int k = 0; k < A.GetLength(1); k++)
{
C[i, j] += A[i, k] * B[k, j];
}
}
}
return C;
}
private static double[,] GetArray(Expression expression)
{
var oExp1 = expression as XObjectExpression;
if (oExp1 == null) return new[,] { { (Double)expression } };
var range = (oExp1.Value as CellRangeReference).Range;
var rowCount = range.RowCount();
var columnCount = range.ColumnCount();
var arr = new double[rowCount, columnCount];
for (int row = 0; row < rowCount; row++)
{
for (int column = 0; column < columnCount; column++)
{
arr[row, column] = range.Cell(row + 1, column + 1).GetDouble();
}
}
return arr;
}
private static object MDeterm(List<Expression> p)
{
var arr = GetArray(p[0]);
var m = new XLMatrix(arr);
return m.Determinant();
}
private static object MInverse(List<Expression> p)
{
var arr = GetArray(p[0]);
var m = new XLMatrix(arr);
return m.Invert().mat;
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Atom
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Xml;
using Microsoft.Data.OData.Metadata;
#endregion Namespaces
/// <summary>
/// OData ATOM deserializer for ATOM metadata on entries.
/// </summary>
internal sealed class ODataAtomEntryMetadataDeserializer : ODataAtomEpmDeserializer
{
#region Atomized strings
/// <summary>The empty namespace used for attributes in no namespace.</summary>
private readonly string EmptyNamespace;
/// <summary>Schema namespace for Atom.</summary>
private readonly string AtomNamespace;
#endregion
/// <summary>
/// Feed ATOM metadata deserializer for deserializing the atom:source element in an entry.
/// This is created on-demand only when needed, but then it's cached.
/// </summary>
private ODataAtomFeedMetadataDeserializer sourceMetadataDeserializer;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="atomInputContext">The ATOM input context to read from.</param>
internal ODataAtomEntryMetadataDeserializer(ODataAtomInputContext atomInputContext)
: base(atomInputContext)
{
DebugUtils.CheckNoExternalCallers();
XmlNameTable nameTable = this.XmlReader.NameTable;
this.EmptyNamespace = nameTable.Add(string.Empty);
this.AtomNamespace = nameTable.Add(AtomConstants.AtomNamespace);
}
/// <summary>
/// Feed ATOM metadata deserializer for deserializing the atom:source element in an entry.
/// This is created on-demand only when needed, but then it's cached.
/// </summary>
private ODataAtomFeedMetadataDeserializer SourceMetadataDeserializer
{
get
{
return this.sourceMetadataDeserializer ??
(this.sourceMetadataDeserializer = new ODataAtomFeedMetadataDeserializer(this.AtomInputContext, true));
}
}
/// <summary>
/// Reads an element in ATOM namespace in the content of the entry element.
/// </summary>
/// <param name="entryState">The reader entry state for the entry being read.</param>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element (atom:*) - the ATOM element to read.
/// Post-Condition: Any - the node after the ATOM element which was read.
/// </remarks>
internal void ReadAtomElementInEntryContent(IODataAtomReaderEntryState entryState)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(entryState != null, "entryState != null");
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace, "Only atom:* elements can be read by this method.");
ODataEntityPropertyMappingCache cachedEpm = entryState.CachedEpm;
EpmTargetPathSegment epmTargetPathSegment = null;
if (cachedEpm != null)
{
epmTargetPathSegment = cachedEpm.EpmTargetTree.SyndicationRoot;
}
EpmTargetPathSegment subSegment;
if (this.ShouldReadElement(epmTargetPathSegment, this.XmlReader.LocalName, out subSegment))
{
switch (this.XmlReader.LocalName)
{
case AtomConstants.AtomAuthorElementName:
this.ReadAuthorElement(entryState, subSegment);
return;
case AtomConstants.AtomContributorElementName:
this.ReadContributorElement(entryState, subSegment);
return;
case AtomConstants.AtomUpdatedElementName:
{
AtomEntryMetadata entryMetadata = entryState.AtomEntryMetadata;
if (this.UseClientFormatBehavior)
{
if (this.ShouldReadSingletonElement(entryMetadata.UpdatedString != null))
{
entryMetadata.UpdatedString = this.ReadAtomDateConstructAsString();
return;
}
}
else
{
if (this.ShouldReadSingletonElement(entryMetadata.Updated.HasValue))
{
entryMetadata.Updated = this.ReadAtomDateConstruct();
return;
}
}
}
break;
case AtomConstants.AtomPublishedElementName:
{
AtomEntryMetadata entryMetadata = entryState.AtomEntryMetadata;
if (this.UseClientFormatBehavior)
{
if (this.ShouldReadSingletonElement(entryMetadata.PublishedString != null))
{
entryMetadata.PublishedString = this.ReadAtomDateConstructAsString();
return;
}
}
else
{
if (this.ShouldReadSingletonElement(entryMetadata.Published.HasValue))
{
entryMetadata.Published = this.ReadAtomDateConstruct();
return;
}
}
}
break;
case AtomConstants.AtomRightsElementName:
if (this.ShouldReadSingletonElement(entryState.AtomEntryMetadata.Rights != null))
{
entryState.AtomEntryMetadata.Rights = this.ReadAtomTextConstruct();
return;
}
break;
case AtomConstants.AtomSourceElementName:
if (this.ShouldReadSingletonElement(entryState.AtomEntryMetadata.Source != null))
{
entryState.AtomEntryMetadata.Source = this.ReadAtomSourceInEntryContent();
return;
}
break;
case AtomConstants.AtomSummaryElementName:
if (this.ShouldReadSingletonElement(entryState.AtomEntryMetadata.Summary != null))
{
entryState.AtomEntryMetadata.Summary = this.ReadAtomTextConstruct();
return;
}
break;
case AtomConstants.AtomTitleElementName:
if (this.ShouldReadSingletonElement(entryState.AtomEntryMetadata.Title != null))
{
entryState.AtomEntryMetadata.Title = this.ReadAtomTextConstruct();
return;
}
break;
default:
break;
}
}
// Skip everything we didn't read.
this.XmlReader.Skip();
}
/// <summary>
/// Reads the atom:link element in the entry content.
/// </summary>
/// <param name="relation">The value of the rel attribute for the link element.</param>
/// <param name="hrefStringValue">The value of the href attribute for the link element.</param>
/// <returns>An <see cref="AtomLinkMetadata"/> instance storing the information about this link, or null if link info doesn't need to be stored.</returns>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element (atom:link) - the atom:link element to read.
/// Post-Condition: XmlNodeType.Element (atom:link) - the atom:link element which was read.
/// </remarks>
internal AtomLinkMetadata ReadAtomLinkElementInEntryContent(string relation, string hrefStringValue)
{
DebugUtils.CheckNoExternalCallers();
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(
this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace && this.XmlReader.LocalName == AtomConstants.AtomLinkElementName,
"Only atom:link element can be read by this method.");
AtomLinkMetadata linkMetadata = null;
if (this.ReadAtomMetadata)
{
linkMetadata = new AtomLinkMetadata();
linkMetadata.Relation = relation;
if (this.ReadAtomMetadata)
{
linkMetadata.Href = hrefStringValue == null ? null : this.ProcessUriFromPayload(hrefStringValue, this.XmlReader.XmlBaseUri);
}
// Read the attributes
while (this.XmlReader.MoveToNextAttribute())
{
if (this.XmlReader.NamespaceEquals(this.EmptyNamespace))
{
// Note that it's OK to store values which we don't validate in any way even if we might not need them.
// The EPM reader will ignore them if they're not needed and the fact that we don't validate them means that there are no observable differences
// if we store them. It keeps the code simpler (less ifs).
switch (this.XmlReader.LocalName)
{
case AtomConstants.AtomLinkTypeAttributeName:
linkMetadata.MediaType = this.XmlReader.Value;
break;
case AtomConstants.AtomLinkHrefLangAttributeName:
linkMetadata.HrefLang = this.XmlReader.Value;
break;
case AtomConstants.AtomLinkTitleAttributeName:
linkMetadata.Title = this.XmlReader.Value;
break;
case AtomConstants.AtomLinkLengthAttributeName:
// We must NOT try to parse the value into a number if we don't need it (either ATOM metadata or EPM)
if (this.ReadAtomMetadata)
{
string lengthStringValue = this.XmlReader.Value;
int length;
if (int.TryParse(lengthStringValue, NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out length))
{
linkMetadata.Length = length;
}
else
{
throw new ODataException(Strings.EpmSyndicationWriter_InvalidLinkLengthValue(lengthStringValue));
}
}
break;
default:
// Ignore all other attributes.
break;
}
}
}
}
this.XmlReader.MoveToElement();
return linkMetadata;
}
/// <summary>
/// Reads the atom:category element in the entry content.
/// </summary>
/// <param name="entryState">The reader entry state for the entry being read.</param>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element (atom:category) - the atom:category element to read.
/// Post-Condition: Any - the node after the atom:category which was read.
/// </remarks>
internal void ReadAtomCategoryElementInEntryContent(IODataAtomReaderEntryState entryState)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(entryState != null, "entryState != null");
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(
this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace && this.XmlReader.LocalName == AtomConstants.AtomCategoryElementName,
"Only atom:category element can be read by this method.");
ODataEntityPropertyMappingCache cachedEpm = entryState.CachedEpm;
EpmTargetPathSegment epmTargetPathSegment = null;
if (cachedEpm != null)
{
epmTargetPathSegment = cachedEpm.EpmTargetTree.SyndicationRoot;
}
// Rough estimate if we will need the category for EPM - we can't tell for sure since we don't know the scheme value yet.
bool hasCategoryEpm = epmTargetPathSegment != null && epmTargetPathSegment.SubSegments.Any(segment =>
string.CompareOrdinal(segment.SegmentName, AtomConstants.AtomCategoryElementName) == 0);
// Read the attributes and create the category metadata regardless if we will need it or not.
// We can do this since there's no validation done on any of the values and thus this operation will never fail.
// If we then decide we don't need it, we can safely throw it away.
if (this.ReadAtomMetadata || hasCategoryEpm)
{
AtomCategoryMetadata categoryMetadata = this.ReadAtomCategoryElement();
// No point in trying to figure out if we will need the category for EPM or not here.
// Our EPM syndication reader must handle unneeded categories anyway (if ATOM metadata reading is on)
// So instead of burning the cycles to compute if we need it, just store it anyway.
AtomMetadataReaderUtils.AddCategoryToEntryMetadata(entryState.AtomEntryMetadata, categoryMetadata);
}
else
{
// Skip the element in any case (we only ever consume attributes on it anyway).
this.XmlReader.Skip();
}
}
/// <summary>
/// Reads the atom:category element.
/// </summary>
/// <returns>The ATOM category metadata read.</returns>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element (atom:category) - the atom:category element to read.
/// Post-Condition: Any - the node after the atom:category which was read.
/// </remarks>
internal AtomCategoryMetadata ReadAtomCategoryElement()
{
DebugUtils.CheckNoExternalCallers();
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(
this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace && this.XmlReader.LocalName == AtomConstants.AtomCategoryElementName,
"Only atom:category element can be read by this method.");
AtomCategoryMetadata categoryMetadata = new AtomCategoryMetadata();
// Read the attributes
while (this.XmlReader.MoveToNextAttribute())
{
if (this.XmlReader.NamespaceEquals(this.EmptyNamespace))
{
switch (this.XmlReader.LocalName)
{
case AtomConstants.AtomCategorySchemeAttributeName:
categoryMetadata.Scheme = categoryMetadata.Scheme ?? this.XmlReader.Value;
break;
case AtomConstants.AtomCategoryTermAttributeName:
categoryMetadata.Term = categoryMetadata.Term ?? this.XmlReader.Value;
break;
case AtomConstants.AtomCategoryLabelAttributeName:
categoryMetadata.Label = this.XmlReader.Value;
break;
default:
// Ignore all other attributes.
break;
}
}
else if (this.UseClientFormatBehavior && this.XmlReader.NamespaceEquals(this.AtomNamespace))
{
switch (this.XmlReader.LocalName)
{
case AtomConstants.AtomCategorySchemeAttributeName:
categoryMetadata.Scheme = this.XmlReader.Value;
break;
case AtomConstants.AtomCategoryTermAttributeName:
categoryMetadata.Term = this.XmlReader.Value;
break;
default:
// Ignore all other attributes.
break;
}
}
}
// Skip the element in any case (we only ever consume attributes on it anyway).
this.XmlReader.Skip();
return categoryMetadata;
}
/// <summary>
/// Reads the atom:source element in the entry content.
/// </summary>
/// <returns>The information in the source element as <see cref="AtomFeedMetadata"/>.</returns>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element (atom:source) - the atom:source element to read.
/// Post-Condition: Any - the node after the atom:source which was read.
/// </remarks>
internal AtomFeedMetadata ReadAtomSourceInEntryContent()
{
DebugUtils.CheckNoExternalCallers();
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(
this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace && this.XmlReader.LocalName == AtomConstants.AtomSourceElementName,
"Only atom:source element can be read by this method.");
AtomFeedMetadata atomFeedMetadata = AtomMetadataReaderUtils.CreateNewAtomFeedMetadata();
if (this.XmlReader.IsEmptyElement)
{
// Advance reader past this element.
this.XmlReader.Read();
return atomFeedMetadata;
}
// Read the start tag of the source element.
this.XmlReader.Read();
while (this.XmlReader.NodeType != XmlNodeType.EndElement)
{
if (this.XmlReader.NodeType != XmlNodeType.Element)
{
Debug.Assert(this.XmlReader.NodeType != XmlNodeType.EndElement, "EndElement should have been handled already.");
// Skip everything but elements, including insignificant nodes, text nodes and CDATA nodes.
this.XmlReader.Skip();
continue;
}
if (this.XmlReader.NamespaceEquals(this.AtomNamespace))
{
// Use a feed metadata deserializer to process this element and modify atomFeedMetadata appropriately.
this.SourceMetadataDeserializer.ReadAtomElementAsFeedMetadata(atomFeedMetadata);
}
else
{
// Skip all elements not in the ATOM namespace.
this.XmlReader.Skip();
}
}
// Advance the reader past the end tag of the source element.
this.XmlReader.Read();
return atomFeedMetadata;
}
/// <summary>
/// Reads an author element.
/// </summary>
/// <param name="entryState">The reader entry state for the entry being read.</param>
/// <param name="epmTargetPathSegment">The EPM target path segment for the element to read, or null if no EPM for that element is defined.</param>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element (atom:author) - the atom:author element to read.
/// Post-Condition: Any - the node after the atom:author element which was read.
/// </remarks>
private void ReadAuthorElement(IODataAtomReaderEntryState entryState, EpmTargetPathSegment epmTargetPathSegment)
{
Debug.Assert(entryState != null, "entryState != null");
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(
this.XmlReader.LocalName == AtomConstants.AtomAuthorElementName && this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace,
"Only atom:author elements can be read by this method.");
if (this.ShouldReadCollectionElement(entryState.AtomEntryMetadata.Authors.Any()))
{
AtomMetadataReaderUtils.AddAuthorToEntryMetadata(
entryState.AtomEntryMetadata,
this.ReadAtomPersonConstruct(epmTargetPathSegment));
}
else
{
// Skip the element as we don't care about it
this.XmlReader.Skip();
}
}
/// <summary>
/// Reads a contributor element.
/// </summary>
/// <param name="entryState">The reader entry state for the entry being read.</param>
/// <param name="epmTargetPathSegment">The EPM target path segment for the element to read, or null if no EPM for that element is defined.</param>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element (atom:contributor) - the atom:contributor element to read.
/// Post-Condition: Any - the node after the atom:contributor element which was read.
/// </remarks>
private void ReadContributorElement(IODataAtomReaderEntryState entryState, EpmTargetPathSegment epmTargetPathSegment)
{
Debug.Assert(entryState != null, "entryState != null");
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(
this.XmlReader.LocalName == AtomConstants.AtomContributorElementName && this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace,
"Only atom:contributor elements can be read by this method.");
if (this.ShouldReadCollectionElement(entryState.AtomEntryMetadata.Contributors.Any()))
{
AtomMetadataReaderUtils.AddContributorToEntryMetadata(
entryState.AtomEntryMetadata,
this.ReadAtomPersonConstruct(epmTargetPathSegment));
}
else
{
this.XmlReader.Skip();
}
}
/// <summary>
/// Determines if a person element should be read or skipped.
/// </summary>
/// <param name="someAlreadyExist">true if some elements from the collection in question already exist; false if this is the first one.</param>
/// <returns>true if the collection element should be read; false if it should be skipped.</returns>
private bool ShouldReadCollectionElement(bool someAlreadyExist)
{
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(
this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace &&
(this.XmlReader.LocalName == AtomConstants.AtomAuthorElementName ||
this.XmlReader.LocalName == AtomConstants.AtomContributorElementName),
"This method should only be called if the reader is on an element which can appear in ATOM entry multiple times.");
// Only read multiple author/contributor elements if ATOM metadata reading is on.
// If we're reading it only because of single property EPM, then we should only read the first one and completely skip
// the others, to avoid failures in places where WCF DS didn't fail before (and we really don't care about those values anyway).
return this.ReadAtomMetadata || !someAlreadyExist;
}
/// <summary>
/// Determines if we should read an element which is allowed to appear only once in ATOM.
/// </summary>
/// <param name="alreadyExists">true if we already found such element before; false if this is the first occurence.</param>
/// <returns>true if the element should be processed; false if the element should be skipped.</returns>
/// <remarks>The method may throw if multiple occurences of such element occure and they should be treated as an error.</remarks>
private bool ShouldReadSingletonElement(bool alreadyExists)
{
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(
this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace &&
(this.XmlReader.LocalName == AtomConstants.AtomRightsElementName ||
this.XmlReader.LocalName == AtomConstants.AtomSummaryElementName ||
this.XmlReader.LocalName == AtomConstants.AtomTitleElementName ||
this.XmlReader.LocalName == AtomConstants.AtomPublishedElementName ||
this.XmlReader.LocalName == AtomConstants.AtomUpdatedElementName ||
this.XmlReader.LocalName == AtomConstants.AtomSourceElementName),
"This method should only be called if the reader is on an element which can appear in ATOM entry just once.");
if (alreadyExists)
{
if (this.ReadAtomMetadata || this.AtomInputContext.UseDefaultFormatBehavior)
{
// We should not allow multiple elements per the ATOM spec, when we're reading ATOM metadata.
// The default ODataLib behavior is also to disallow duplicates. EPM behavior is also the same.
throw new ODataException(Strings.ODataAtomMetadataDeserializer_MultipleSingletonMetadataElements(this.XmlReader.LocalName, AtomConstants.AtomEntryElementName));
}
// Otherwise we're reading this only for EPM in WCF DS Client of Server mode,
// in which case any additional elements like this should be skipped.
return false;
}
return true;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.IO;
using System.Web;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using RestSharp;
namespace IO.Swagger.Client
{
/// <summary>
/// API client is mainly responible for making the HTTP call to the API backend.
/// </summary>
public class ApiClient
{
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration and base path (https://api.landregistry.gov.uk/v1).
/// </summary>
public ApiClient()
{
Configuration = Configuration.Default;
RestClient = new RestClient("https://api.landregistry.gov.uk/v1");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default base path (https://api.landregistry.gov.uk/v1).
/// </summary>
/// <param name="config">An instance of Configuration.</param>
public ApiClient(Configuration config = null)
{
if (config == null)
Configuration = Configuration.Default;
else
Configuration = config;
RestClient = new RestClient("https://api.landregistry.gov.uk/v1");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration.
/// </summary>
/// <param name="basePath">The base path.</param>
public ApiClient(String basePath = "https://api.landregistry.gov.uk/v1")
{
if (String.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
RestClient = new RestClient(basePath);
Configuration = Configuration.Default;
}
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The default API client.</value>
[Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")]
public static ApiClient Default;
/// <summary>
/// Gets or sets the Configuration.
/// </summary>
/// <value>An instance of the Configuration.</value>
public Configuration Configuration { get; set; }
/// <summary>
/// Gets or sets the RestClient.
/// </summary>
/// <value>An instance of the RestClient</value>
public RestClient RestClient { get; set; }
// Creates and sets up a RestRequest prior to a call.
private RestRequest PrepareRequest(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = new RestRequest(path, method);
// add user agent header
request.AddHeader("User-Agent", Configuration.HttpUserAgent);
// add path parameter, if any
foreach(var param in pathParams)
request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
// add header parameter, if any
foreach(var param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(var param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(var param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(var param in fileParams)
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
if (postBody != null) // http body (model or byte[]) parameter
{
if (postBody.GetType() == typeof(String))
{
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
}
else if (postBody.GetType() == typeof(byte[]))
{
request.AddParameter(contentType, postBody, ParameterType.RequestBody);
}
}
return request;
}
/// <summary>
/// Makes the HTTP request (Sync).
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content Type of the request</param>
/// <returns>Object</returns>
public Object CallApi(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
var response = RestClient.Execute(request);
return (Object) response;
}
/// <summary>
/// Makes the asynchronous HTTP request.
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content type.</param>
/// <returns>The Task instance.</returns>
public async System.Threading.Tasks.Task<Object> CallApiAsync(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
var response = await RestClient.ExecuteTaskAsync(request);
return (Object)response;
}
/// <summary>
/// Escape string (url-encoded).
/// </summary>
/// <param name="str">String to be escaped.</param>
/// <returns>Escaped string.</returns>
public string EscapeString(string str)
{
return UrlEncode(str);
}
/// <summary>
/// Create FileParameter based on Stream.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <param name="stream">Input stream.</param>
/// <returns>FileParameter.</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream)
return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name));
else
return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided");
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <returns>Formatted string.</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTime)obj).ToString (Configuration.DateTimeFormat);
else if (obj is DateTimeOffset)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat);
else if (obj is IList)
{
var flattenedString = new StringBuilder();
foreach (var param in (IList)obj)
{
if (flattenedString.Length > 0)
flattenedString.Append(",");
flattenedString.Append(param);
}
return flattenedString.ToString();
}
else
return Convert.ToString (obj);
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
public object Deserialize(IRestResponse response, Type type)
{
IList<Parameter> headers = response.Headers;
if (type == typeof(byte[])) // return byte array
{
return response.RawBytes;
}
if (type == typeof(Stream))
{
if (headers != null)
{
var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
? Path.GetTempPath()
: Configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, response.RawBytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(response.RawBytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return ConvertType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an input (model) into JSON string
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>JSON string.</returns>
public String Serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Select the Content-Type header's value from the given content-type array:
/// if JSON exists in the given array, use it;
/// otherwise use the first one defined in 'consumes'
/// </summary>
/// <param name="contentTypes">The Content-Type array to select from.</param>
/// <returns>The Content-Type header to use.</returns>
public String SelectHeaderContentType(String[] contentTypes)
{
if (contentTypes.Length == 0)
return null;
if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return contentTypes[0]; // use the first content type specified in 'consumes'
}
/// <summary>
/// Select the Accept header's value from the given accepts array:
/// if JSON exists in the given array, use it;
/// otherwise use all of them (joining into a string)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public String SelectHeaderAccept(String[] accepts)
{
if (accepts.Length == 0)
return null;
if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return String.Join(",", accepts);
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">String to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Dynamically cast the object into target type.
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="source">Object to be casted</param>
/// <param name="dest">Target type</param>
/// <returns>Casted object</returns>
public static dynamic ConvertType(dynamic source, Type dest)
{
return Convert.ChangeType(source, dest);
}
/// <summary>
/// Convert stream to byte array
/// Credit/Ref: http://stackoverflow.com/a/221941/677735
/// </summary>
/// <param name="input">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// URL encode a string
/// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50
/// </summary>
/// <param name="input">String to be URL encoded</param>
/// <returns>Byte array</returns>
public static string UrlEncode(string input)
{
const int maxLength = 32766;
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length <= maxLength)
{
return Uri.EscapeDataString(input);
}
StringBuilder sb = new StringBuilder(input.Length * 2);
int index = 0;
while (index < input.Length)
{
int length = Math.Min(input.Length - index, maxLength);
string subString = input.Substring(index, length);
sb.Append(Uri.EscapeDataString(subString));
index += subString.Length;
}
return sb.ToString();
}
/// <summary>
/// Sanitize filename by removing the path
/// </summary>
/// <param name="filename">Filename</param>
/// <returns>Filename</returns>
public static string SanitizeFilename(string filename)
{
Match match = Regex.Match(filename, @".*[/\\](.*)$");
if (match.Success)
{
return match.Groups[1].Value;
}
else
{
return filename;
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Client.Methods.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Org.Apache.Http.Client.Methods
{
/// <summary>
/// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpEntityEnclosingRequestBase
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpEntityEnclosingRequestBase", AccessFlags = 1057)]
public abstract partial class HttpEntityEnclosingRequestBase : global::Org.Apache.Http.Client.Methods.HttpRequestBase, global::Org.Apache.Http.IHttpEntityEnclosingRequest
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpEntityEnclosingRequestBase() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getEntity
/// </java-name>
[Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.IHttpEntity GetEntity() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHttpEntity);
}
/// <java-name>
/// setEntity
/// </java-name>
[Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)]
public virtual void SetEntity(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tells if this request should use the expect-continue handshake. The expect continue handshake gives the server a chance to decide whether to accept the entity enclosing request before the possibly lengthy entity is sent across the wire. </para>
/// </summary>
/// <returns>
/// <para>true if the expect continue handshake should be used, false if not. </para>
/// </returns>
/// <java-name>
/// expectContinue
/// </java-name>
[Dot42.DexImport("expectContinue", "()Z", AccessFlags = 1)]
public virtual bool ExpectContinue() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public override object Clone() /* MethodBuilder.Create */
{
return default(object);
}
[Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IRequestLine GetRequestLine() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IRequestLine);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)]
public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.ProtocolVersion);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)]
public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)]
public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
/// <java-name>
/// getEntity
/// </java-name>
public global::Org.Apache.Http.IHttpEntity Entity
{
[Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)]
get{ return GetEntity(); }
[Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)]
set{ SetEntity(value); }
}
public global::Org.Apache.Http.IRequestLine RequestLine
{
[Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)]
get{ return GetRequestLine(); }
}
public global::Org.Apache.Http.ProtocolVersion ProtocolVersion
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)]
get{ return GetProtocolVersion(); }
}
public global::Org.Apache.Http.IHeader[] AllHeaders
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
get{ return GetAllHeaders(); }
}
public global::Org.Apache.Http.Params.IHttpParams Params
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
get{ return GetParams(); }
[Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)]
set{ SetParams(value); }
}
}
/// <summary>
/// <para>HTTP DELETE method </para><para>The HTTP DELETE method is defined in section 9.7 of : <blockquote><para>The DELETE method requests that the origin server delete the resource identified by the Request-URI. [...] The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. </para></blockquote></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpDelete
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpDelete", AccessFlags = 33)]
public partial class HttpDelete : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "DELETE";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpDelete() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpDelete(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpDelete(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>HTTP HEAD method. </para><para>The HTTP HEAD method is defined in section 9.4 of : <blockquote><para>The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpHead
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpHead", AccessFlags = 33)]
public partial class HttpHead : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "HEAD";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpHead() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpHead(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpHead(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>HTTP GET method. </para><para>The HTTP GET method is defined in section 9.3 of : <blockquote><para>The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. </para></blockquote></para><para>GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).</para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpGet
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpGet", AccessFlags = 33)]
public partial class HttpGet : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "GET";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpGet() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpGet(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpGet(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpRequestBase
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpRequestBase", AccessFlags = 1057)]
public abstract partial class HttpRequestBase : global::Org.Apache.Http.Message.AbstractHttpMessage, global::Org.Apache.Http.Client.Methods.IHttpUriRequest, global::Org.Apache.Http.Client.Methods.IAbortableHttpRequest, global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpRequestBase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the protocol version this message is compatible with. </para>
/// </summary>
/// <java-name>
/// getProtocolVersion
/// </java-name>
[Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)]
public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.ProtocolVersion);
}
/// <summary>
/// <para>Returns the URI this request uses, such as <code></code>. </para>
/// </summary>
/// <java-name>
/// getURI
/// </java-name>
[Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)]
public virtual global::System.Uri GetURI() /* MethodBuilder.Create */
{
return default(global::System.Uri);
}
/// <summary>
/// <para>Returns the request line of this request. </para>
/// </summary>
/// <returns>
/// <para>the request line. </para>
/// </returns>
/// <java-name>
/// getRequestLine
/// </java-name>
[Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.IRequestLine GetRequestLine() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IRequestLine);
}
/// <java-name>
/// setURI
/// </java-name>
[Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)]
public virtual void SetURI(global::System.Uri uri) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionRequest
/// </java-name>
[Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1)]
public virtual void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setReleaseTrigger
/// </java-name>
[Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1)]
public virtual void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para>
/// </summary>
/// <java-name>
/// abort
/// </java-name>
[Dot42.DexImport("abort", "()V", AccessFlags = 1)]
public virtual void Abort() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if the request execution has been aborted.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isAborted
/// </java-name>
[Dot42.DexImport("isAborted", "()Z", AccessFlags = 1)]
public virtual bool IsAborted() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public virtual object Clone() /* MethodBuilder.Create */
{
return default(object);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)]
public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)]
public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetMethod(); }
}
/// <summary>
/// <para>Returns the protocol version this message is compatible with. </para>
/// </summary>
/// <java-name>
/// getProtocolVersion
/// </java-name>
public global::Org.Apache.Http.ProtocolVersion ProtocolVersion
{
[Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)]
get{ return GetProtocolVersion(); }
}
/// <summary>
/// <para>Returns the URI this request uses, such as <code></code>. </para>
/// </summary>
/// <java-name>
/// getURI
/// </java-name>
public global::System.Uri URI
{
[Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)]
get{ return GetURI(); }
[Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)]
set{ SetURI(value); }
}
/// <summary>
/// <para>Returns the request line of this request. </para>
/// </summary>
/// <returns>
/// <para>the request line. </para>
/// </returns>
/// <java-name>
/// getRequestLine
/// </java-name>
public global::Org.Apache.Http.IRequestLine RequestLine
{
[Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)]
get{ return GetRequestLine(); }
}
public global::Org.Apache.Http.IHeader[] AllHeaders
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
get{ return GetAllHeaders(); }
}
}
/// <summary>
/// <para>HTTP POST method. </para><para>The HTTP POST method is defined in section 9.5 of : <blockquote><para>The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions: <ul><li><para>Annotation of existing resources </para></li><li><para>Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles </para></li><li><para>Providing a block of data, such as the result of submitting a form, to a data-handling process </para></li><li><para>Extending a database through an append operation </para></li></ul></para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpPost
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpPost", AccessFlags = 33)]
public partial class HttpPost : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "POST";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpPost() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpPost(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpPost(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>Interface representing an HTTP request that can be aborted by shutting down the underlying HTTP connection.</para><para><para></para><para></para><title>Revision:</title><para>639600 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/AbortableHttpRequest
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/AbortableHttpRequest", AccessFlags = 1537)]
public partial interface IAbortableHttpRequest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Sets the ClientConnectionRequest callback that can be used to abort a long-lived request for a connection. If the request is already aborted, throws an IOException.</para><para><para>ClientConnectionManager </para><simplesectsep></simplesectsep><para>ThreadSafeClientConnManager </para></para>
/// </summary>
/// <java-name>
/// setConnectionRequest
/// </java-name>
[Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1025)]
void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the ConnectionReleaseTrigger callback that can be used to abort an active connection. Typically, this will be the ManagedClientConnection itself. If the request is already aborted, throws an IOException. </para>
/// </summary>
/// <java-name>
/// setReleaseTrigger
/// </java-name>
[Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1025)]
void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para>
/// </summary>
/// <java-name>
/// abort
/// </java-name>
[Dot42.DexImport("abort", "()V", AccessFlags = 1025)]
void Abort() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>HTTP OPTIONS method. </para><para>The HTTP OPTIONS method is defined in section 9.2 of : <blockquote><para>The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpOptions
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpOptions", AccessFlags = 33)]
public partial class HttpOptions : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "OPTIONS";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpOptions() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpOptions(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpOptions(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getAllowedMethods
/// </java-name>
[Dot42.DexImport("getAllowedMethods", "(Lorg/apache/http/HttpResponse;)Ljava/util/Set;", AccessFlags = 1, Signature = "(Lorg/apache/http/HttpResponse;)Ljava/util/Set<Ljava/lang/String;>;")]
public virtual global::Java.Util.ISet<string> GetAllowedMethods(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<string>);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>Extended version of the HttpRequest interface that provides convenience methods to access request properties such as request URI and method type.</para><para><para></para><para></para><title>Revision:</title><para>659191 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpUriRequest
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpUriRequest", AccessFlags = 1537)]
public partial interface IHttpUriRequest : global::Org.Apache.Http.IHttpRequest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetMethod() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the URI this request uses, such as <code></code>. </para>
/// </summary>
/// <java-name>
/// getURI
/// </java-name>
[Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1025)]
global::System.Uri GetURI() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Aborts execution of the request.</para><para></para>
/// </summary>
/// <java-name>
/// abort
/// </java-name>
[Dot42.DexImport("abort", "()V", AccessFlags = 1025)]
void Abort() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Tests if the request execution has been aborted.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isAborted
/// </java-name>
[Dot42.DexImport("isAborted", "()Z", AccessFlags = 1025)]
bool IsAborted() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>HTTP PUT method. </para><para>The HTTP PUT method is defined in section 9.6 of : <blockquote><para>The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpPut
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpPut", AccessFlags = 33)]
public partial class HttpPut : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "PUT";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpPut() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpPut(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpPut(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>HTTP TRACE method. </para><para>The HTTP TRACE method is defined in section 9.6 of : <blockquote><para>The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a Max-Forwards value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpTrace
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpTrace", AccessFlags = 33)]
public partial class HttpTrace : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "TRACE";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpTrace() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpTrace(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpTrace(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.Mget6
{
public partial class Mget6YamlTests
{
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class Fields1Tests : YamlTestsBase
{
[Test]
public void Fields1Test()
{
//do index
_body = new {
foo= "bar"
};
this.Do(()=> _client.Index("test_1", "test", "1", _body));
//do cluster.health
this.Do(()=> _client.ClusterHealth(nv=>nv
.AddQueryString("wait_for_status", @"yellow")
));
//do mget
_body = new {
docs= new dynamic[] {
new {
_id= "1"
},
new {
_id= "1",
fields= "foo"
},
new {
_id= "1",
fields= new [] {
"foo"
}
},
new {
_id= "1",
fields= new [] {
"foo",
"_source"
}
}
}
};
this.Do(()=> _client.Mget("test_1", "test", _body));
//is_false _response.docs[0].fields;
this.IsFalse(_response.docs[0].fields);
//match _response.docs[0]._source:
this.IsMatch(_response.docs[0]._source, new {
foo= "bar"
});
//match _response.docs[1].fields.foo:
this.IsMatch(_response.docs[1].fields.foo, new [] {
@"bar"
});
//is_false _response.docs[1]._source;
this.IsFalse(_response.docs[1]._source);
//match _response.docs[2].fields.foo:
this.IsMatch(_response.docs[2].fields.foo, new [] {
@"bar"
});
//is_false _response.docs[2]._source;
this.IsFalse(_response.docs[2]._source);
//match _response.docs[3].fields.foo:
this.IsMatch(_response.docs[3].fields.foo, new [] {
@"bar"
});
//match _response.docs[3]._source:
this.IsMatch(_response.docs[3]._source, new {
foo= "bar"
});
//do mget
_body = new {
docs= new dynamic[] {
new {
_id= "1"
},
new {
_id= "1",
fields= "foo"
},
new {
_id= "1",
fields= new [] {
"foo"
}
},
new {
_id= "1",
fields= new [] {
"foo",
"_source"
}
}
}
};
this.Do(()=> _client.Mget("test_1", "test", _body, nv=>nv
.AddQueryString("fields", @"foo")
));
//match _response.docs[0].fields.foo:
this.IsMatch(_response.docs[0].fields.foo, new [] {
@"bar"
});
//is_false _response.docs[0]._source;
this.IsFalse(_response.docs[0]._source);
//match _response.docs[1].fields.foo:
this.IsMatch(_response.docs[1].fields.foo, new [] {
@"bar"
});
//is_false _response.docs[1]._source;
this.IsFalse(_response.docs[1]._source);
//match _response.docs[2].fields.foo:
this.IsMatch(_response.docs[2].fields.foo, new [] {
@"bar"
});
//is_false _response.docs[2]._source;
this.IsFalse(_response.docs[2]._source);
//match _response.docs[3].fields.foo:
this.IsMatch(_response.docs[3].fields.foo, new [] {
@"bar"
});
//match _response.docs[3]._source:
this.IsMatch(_response.docs[3]._source, new {
foo= "bar"
});
//do mget
_body = new {
docs= new dynamic[] {
new {
_id= "1"
},
new {
_id= "1",
fields= "foo"
},
new {
_id= "1",
fields= new [] {
"foo"
}
},
new {
_id= "1",
fields= new [] {
"foo",
"_source"
}
}
}
};
this.Do(()=> _client.Mget("test_1", "test", _body, nv=>nv
.AddQueryString("fields", new [] {
@"foo"
})
));
//match _response.docs[0].fields.foo:
this.IsMatch(_response.docs[0].fields.foo, new [] {
@"bar"
});
//is_false _response.docs[0]._source;
this.IsFalse(_response.docs[0]._source);
//match _response.docs[1].fields.foo:
this.IsMatch(_response.docs[1].fields.foo, new [] {
@"bar"
});
//is_false _response.docs[1]._source;
this.IsFalse(_response.docs[1]._source);
//match _response.docs[2].fields.foo:
this.IsMatch(_response.docs[2].fields.foo, new [] {
@"bar"
});
//is_false _response.docs[2]._source;
this.IsFalse(_response.docs[2]._source);
//match _response.docs[3].fields.foo:
this.IsMatch(_response.docs[3].fields.foo, new [] {
@"bar"
});
//match _response.docs[3]._source:
this.IsMatch(_response.docs[3]._source, new {
foo= "bar"
});
//do mget
_body = new {
docs= new dynamic[] {
new {
_id= "1"
},
new {
_id= "1",
fields= "foo"
},
new {
_id= "1",
fields= new [] {
"foo"
}
},
new {
_id= "1",
fields= new [] {
"foo",
"_source"
}
}
}
};
this.Do(()=> _client.Mget("test_1", "test", _body, nv=>nv
.AddQueryString("fields", new [] {
@"foo",
@"_source"
})
));
//match _response.docs[0].fields.foo:
this.IsMatch(_response.docs[0].fields.foo, new [] {
@"bar"
});
//match _response.docs[0]._source:
this.IsMatch(_response.docs[0]._source, new {
foo= "bar"
});
//match _response.docs[1].fields.foo:
this.IsMatch(_response.docs[1].fields.foo, new [] {
@"bar"
});
//is_false _response.docs[1]._source;
this.IsFalse(_response.docs[1]._source);
//match _response.docs[2].fields.foo:
this.IsMatch(_response.docs[2].fields.foo, new [] {
@"bar"
});
//is_false _response.docs[2]._source;
this.IsFalse(_response.docs[2]._source);
//match _response.docs[3].fields.foo:
this.IsMatch(_response.docs[3].fields.foo, new [] {
@"bar"
});
//match _response.docs[3]._source:
this.IsMatch(_response.docs[3]._source, new {
foo= "bar"
});
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace fyiReporting.RDL
{
///<summary>
/// Runtime data structure representing the group hierarchy
///</summary>
internal class MatrixEntry
{
Row _r; // needed for sort
Dictionary<string, MatrixEntry> _HashData; // Hash table of data values
List<MatrixEntry> _SortedData; // Sorted List version of the data
string _hash; // item that is used for hash
BitArray _Rows; // rows
MatrixEntry _Parent; // parent
ColumnGrouping _ColumnGroup; // Column grouping
RowGrouping _RowGroup; // Row grouping
int _FirstRow; // First row in _Rows marked true
int _LastRow; // Last row in _Rows marked true
int _rowCount; // we save the rowCount so we can delay creating bitArray
int _StaticColumn=0; // this is the index to which column to use (always 0 when dynamic)
int _StaticRow=0; // this is the index to which row to use (always 0 when dynamic)
Rows _Data; // set dynamically when needed
internal MatrixEntry(Row r, string hash, MatrixEntry p, int rowCount)
{
_r = r;
_hash = hash;
_HashData = new Dictionary<string, MatrixEntry>();
_ColumnGroup = null;
_RowGroup = null;
_SortedData = null;
_Data = null;
_rowCount = rowCount;
_Rows = null;
_Parent = p;
_FirstRow = -1;
_LastRow = -1;
}
internal Dictionary<string, MatrixEntry> HashData
{
get { return _HashData; }
}
internal Rows Data
{
get { return _Data; }
set { _Data = value; }
}
internal string HashItem
{
get { return _hash; }
}
internal List<MatrixEntry> GetSortedData(Report rpt)
{
if (_SortedData == null && _HashData != null && _HashData.Count > 0)
{
_SortedData = new List<MatrixEntry>(_HashData.Values);
_SortedData.Sort(new MatrixEntryComparer(rpt, GetSortBy()));
_HashData = null; // we only keep one
}
return _SortedData;
}
internal MatrixEntry Parent
{
get { return _Parent; }
}
internal ColumnGrouping ColumnGroup
{
get { return _ColumnGroup; }
set { _ColumnGroup = value; }
}
internal int StaticRow
{
get { return _StaticRow; }
set { _StaticRow = value; }
}
internal int StaticColumn
{
get { return _StaticColumn; }
set { _StaticColumn = value; }
}
internal RowGrouping RowGroup
{
get { return _RowGroup; }
set { _RowGroup = value; }
}
internal int FirstRow
{
get { return _FirstRow; }
set
{
if (_FirstRow == -1)
_FirstRow = value;
}
}
internal int LastRow
{
get { return _LastRow; }
set
{
if (value >= _LastRow)
_LastRow = value;
}
}
internal BitArray Rows
{
get
{
if (_Rows == null)
_Rows = new BitArray(_rowCount);
return _Rows;
}
set { _Rows = value; }
}
internal Row R
{
get { return _r; }
}
Sorting GetSortBy()
{
MatrixEntry me=null;
foreach (MatrixEntry m in this.HashData.Values)
{ // just get the first one
me = m;
break;
}
if (me == null)
return null;
Sorting sb = null;
if (me.RowGroup != null)
{
if (me.RowGroup.DynamicRows != null)
sb = me.RowGroup.DynamicRows.Sorting;
}
else if (me.ColumnGroup != null)
{
if (me.ColumnGroup.DynamicColumns != null)
sb = me.ColumnGroup.DynamicColumns.Sorting;
}
return sb;
}
}
class MatrixEntryComparer : System.Collections.Generic.IComparer<MatrixEntry>
{
Report _rpt;
Sorting _Sorting;
public MatrixEntryComparer(Report rpt, Sorting s)
{
_rpt = rpt;
_Sorting = s;
}
#region IComparer Members
public int Compare(MatrixEntry m1, MatrixEntry m2)
{
if (_Sorting == null)
return m1.HashItem.CompareTo(m2.HashItem);
object o1 = null, o2 = null;
TypeCode tc = TypeCode.Object;
int rc;
try
{
foreach (SortBy sb in _Sorting.Items)
{
IExpr e = sb.SortExpression.Expr;
o1 = e.Evaluate(_rpt, m1.R);
o2 = e.Evaluate(_rpt, m2.R);
tc = e.GetTypeCode();
rc = Filter.ApplyCompare(tc, o1, o2);
if (rc != 0)
return sb.Direction == SortDirectionEnum.Ascending? rc : -rc;
}
}
catch (Exception e) // this really shouldn't happen
{
_rpt.rl.LogError(8,
string.Format("Matrix Sort rows exception\r\nArguments: {0} {1}\r\nTypecode: {2}\r\n{3}\r\n{4}",
o1, o2, tc.ToString(), e.Message, e.StackTrace));
return m1.HashItem.CompareTo(m2.HashItem);
}
return 0; // treat as the same
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
using AutoRest.Core;
using AutoRest.Core.Logging;
using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.Extensions;
using AutoRest.Go.Model;
using AutoRest.Go.Properties;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using AutoRest.Extensions.Azure;
namespace AutoRest.Go
{
public class TransformerGo : CodeModelTransformer<CodeModelGo>
{
private readonly Dictionary<IModelType, IModelType> _normalizedTypes;
public TransformerGo()
{
_normalizedTypes = new Dictionary<IModelType, IModelType>();
}
public override CodeModelGo TransformCodeModel(CodeModel cm)
{
var cmg = cm as CodeModelGo;
SwaggerExtensions.ProcessGlobalParameters(cmg);
// Add the current package name as a reserved keyword
CodeNamerGo.Instance.ReserveNamespace(cm.Namespace);
FixStutteringTypeNames(cmg);
TransformEnumTypes(cmg);
TransformMethods(cmg);
TransformModelTypes(cmg);
AzureExtensions.ProcessParameterizedHost(cmg);
return cmg;
}
private void TransformEnumTypes(CodeModelGo cmg)
{
// fix up any enum types that are missing a name.
// NOTE: this must be done before the next code block
foreach (var mt in cmg.ModelTypes)
{
foreach (var property in mt.Properties)
{
// gosdk: For now, inherit Enumerated type names from the composite type field name
if (property.ModelType is EnumTypeGo)
{
var enumType = property.ModelType as EnumTypeGo;
if (!enumType.IsNamed)
{
enumType.SetName(property.Name);
}
}
}
}
// And add any others with a defined name and value list (but not already located)
foreach (var mt in cmg.ModelTypes)
{
var namedEnums = mt.Properties.Where(p => p.ModelType is EnumTypeGo && (p.ModelType as EnumTypeGo).IsNamed);
foreach (var p in namedEnums)
{
if (!cmg.EnumTypes.Any(etm => etm.Equals(p.ModelType)))
{
cmg.Add(new EnumTypeGo(p.ModelType as EnumType));
}
};
}
// now normalize the names
// NOTE: this must be done after all enum types have been accounted for
foreach (var enumType in cmg.EnumTypes)
{
enumType.SetName(CodeNamer.Instance.GetTypeName(enumType.Name.FixedValue));
foreach (var v in enumType.Values)
{
v.Name = CodeNamer.Instance.GetEnumMemberName(v.Name);
}
}
// Ensure all enumerated type values have the simplest possible unique names
// -- The code assumes that all public type names are unique within the client and that the values
// of an enumerated type are unique within that type. To safely promote the enumerated value name
// to the top-level, it must not conflict with other existing types. If it does, prepending the
// value name with the (assumed to be unique) enumerated type name will make it unique.
// First, collect all type names (since these cannot change)
var topLevelNames = new HashSet<string>();
cmg.ModelTypes
.ForEach(mt => topLevelNames.Add(mt.Name));
// Then, note each enumerated type with one or more conflicting values and collect the values from
// those enumerated types without conflicts. do this on a sorted list to ensure consistent naming
cmg.EnumTypes.Cast<EnumTypeGo>().OrderBy(etg => etg.Name.Value)
.ForEach(em =>
{
if (em.Values.Where(v => topLevelNames.Contains(v.Name) || CodeNamerGo.Instance.UserDefinedNames.Contains(v.Name)).Count() > 0)
{
em.HasUniqueNames = false;
}
else
{
em.HasUniqueNames = true;
topLevelNames.UnionWith(em.Values.Select(ev => ev.Name).ToList());
}
});
// add documentation comment if there aren't any
cmg.EnumTypes.Cast<EnumTypeGo>()
.ForEach(em =>
{
if (string.IsNullOrEmpty(em.Documentation))
{
em.Documentation = string.Format("{0} enumerates the values for {1}.", em.Name, em.Name.FixedValue.ToPhrase());
}
});
}
private void TransformModelTypes(CodeModelGo cmg)
{
foreach (var ctg in cmg.ModelTypes.Cast<CompositeTypeGo>())
{
var name = ctg.Name.FixedValue.TrimPackageName(cmg.Namespace);
// ensure that the candidate name isn't already in use
if (name != ctg.Name && cmg.ModelTypes.Any(mt => mt.Name == name))
{
name = $"{name}Type";
}
if (CodeNamerGo.Instance.UserDefinedNames.Contains(name))
{
name = $"{name}{cmg.Namespace.Capitalize()}";
}
ctg.SetName(name);
}
// Find all methods that returned paged results
cmg.Methods.Cast<MethodGo>()
.Where(m => m.IsPageable).ToList()
.ForEach(m =>
{
if (!cmg.PagedTypes.ContainsKey(m.ReturnValue().Body))
{
cmg.PagedTypes.Add(m.ReturnValue().Body, m.NextLink);
}
if (!m.NextMethodExists(cmg.Methods.Cast<MethodGo>()))
{
cmg.NextMethodUndefined.Add(m.ReturnValue().Body);
}
});
// Mark all models returned by one or more methods and note any "next link" fields used with paged data
cmg.ModelTypes.Cast<CompositeTypeGo>()
.Where(mtm =>
{
return cmg.Methods.Cast<MethodGo>().Any(m => m.HasReturnValue() && m.ReturnValue().Body.Equals(mtm));
}).ToList()
.ForEach(mtm =>
{
mtm.IsResponseType = true;
if (cmg.PagedTypes.ContainsKey(mtm))
{
mtm.NextLink = CodeNamerGo.PascalCaseWithoutChar(cmg.PagedTypes[mtm], '.');
mtm.PreparerNeeded = cmg.NextMethodUndefined.Contains(mtm);
}
});
}
private void TransformMethods(CodeModelGo cmg)
{
foreach (var mg in cmg.MethodGroups)
{
mg.Transform(cmg);
}
var wrapperTypes = new Dictionary<string, CompositeTypeGo>();
foreach (var method in cmg.Methods)
{
((MethodGo)method).Transform(cmg);
var scope = new VariableScopeProvider();
foreach (var parameter in method.Parameters)
{
parameter.Name = scope.GetVariableName(parameter.Name);
}
// fix up method return types
if (method.ReturnType.Body.ShouldBeSyntheticType())
{
var ctg = new CompositeTypeGo(method.ReturnType.Body);
if (wrapperTypes.ContainsKey(ctg.Name))
{
method.ReturnType = new Response(wrapperTypes[ctg.Name], method.ReturnType.Headers);
}
else
{
wrapperTypes.Add(ctg.Name, ctg);
cmg.Add(ctg);
method.ReturnType = new Response(ctg, method.ReturnType.Headers);
}
}
}
}
private void FixStutteringTypeNames(CodeModelGo cmg)
{
// Trim the package name from exported types; append a suitable qualifier, if needed, to avoid conflicts.
var exportedTypes = new HashSet<object>();
exportedTypes.UnionWith(cmg.EnumTypes);
exportedTypes.UnionWith(cmg.Methods);
exportedTypes.UnionWith(cmg.ModelTypes);
var stutteringTypes = exportedTypes
.Where(exported =>
(exported is IModelType && (exported as IModelType).Name.FixedValue.StartsWith(cmg.Namespace, StringComparison.OrdinalIgnoreCase)) ||
(exported is Method && (exported as Method).Name.FixedValue.StartsWith(cmg.Namespace, StringComparison.OrdinalIgnoreCase)));
if (stutteringTypes.Any())
{
Logger.Instance.Log(Category.Warning, string.Format(CultureInfo.InvariantCulture, Resources.NamesStutter, stutteringTypes.Count()));
stutteringTypes.ForEach(exported =>
{
var name = exported is IModelType
? (exported as IModelType).Name
: (exported as Method).Name;
Logger.Instance.Log(Category.Warning, string.Format(CultureInfo.InvariantCulture, Resources.StutteringName, name));
name = name.FixedValue.TrimPackageName(cmg.Namespace);
var nameInUse = exportedTypes
.Any(et => (et is IModelType && (et as IModelType).Name.Equals(name)) || (et is Method && (et as Method).Name.Equals(name)));
if (exported is EnumType)
{
(exported as EnumType).Name.FixedValue = CodeNamerGo.AttachTypeName(name, cmg.Namespace, nameInUse, "Enum");
}
else if (exported is CompositeType)
{
(exported as CompositeType).Name.FixedValue = CodeNamerGo.AttachTypeName(name, cmg.Namespace, nameInUse, "Type");
}
else if (exported is Method)
{
(exported as Method).Name = CodeNamerGo.AttachTypeName(name, cmg.Namespace, nameInUse, "Method");
}
});
}
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
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 License
using System;
namespace JsonFx.Utils
{
/// <summary>
/// Character Utility
/// </summary>
/// <remarks>
/// These are either simpler definitions of character classes (e.g. letter is [a-zA-Z]),
/// or they implement platform-agnositic checks (read: "Silverlight workarounds").
/// </remarks>
public static class CharUtility
{
#region Char Methods
/// <summary>
/// Checks if string is null, empty or entirely made up of whitespace
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <remarks>
/// Essentially the same as String.IsNullOrWhiteSpace from .NET 4.0
/// with a simplfied view of whitespace.
/// </remarks>
public static bool IsNullOrWhiteSpace(string value)
{
if (value != null)
{
for (int i=0, length=value.Length; i<length; i++)
{
if (!CharUtility.IsWhiteSpace(value[i]))
{
return false;
}
}
}
return true;
}
/// <summary>
/// Checks if character is line ending, tab or space
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static bool IsWhiteSpace(char ch)
{
return
(ch == ' ') |
(ch == '\n') ||
(ch == '\r') ||
(ch == '\t');
}
/// <summary>
///
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static bool IsControl(char ch)
{
return (ch <= '\u001F');
}
/// <summary>
/// Checks if character matches [A-Za-z]
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static bool IsLetter(char ch)
{
return
((ch >= 'a') && (ch <= 'z')) ||
((ch >= 'A') && (ch <= 'Z'));
}
/// <summary>
/// Checks if character matches [0-9]
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static bool IsDigit(char ch)
{
return (ch >= '0') && (ch <= '9');
}
/// <summary>
/// Checks if character matches [0-9A-Fa-f]
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static bool IsHexDigit(char ch)
{
return
(ch >= '0' && ch <= '9') ||
(ch >= 'A' && ch <= 'F') ||
(ch >= 'a' && ch <= 'f');
}
/// <summary>
/// Gets a 4-bit number as a hex digit
/// </summary>
/// <param name="i">0-15</param>
/// <returns></returns>
public static char GetHexDigit(int i)
{
if (i < 10)
{
return (char)(i + '0');
}
return (char)((i - 10) + 'a');
}
/// <summary>
/// Formats a number as a hex digit
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public static string GetHexString(ulong i)
{
string hex = "";
while (i > 0)
{
hex = String.Concat(CharUtility.GetHexDigit((int)(i % 0x10)), hex);
i >>= 4;
}
return hex;
}
/// <summary>
/// Converts the value of a UTF-16 encoded character or surrogate pair at a specified
/// position in a string into a Unicode code point.
/// </summary>
/// <param name="value"></param>
/// <param name="i"></param>
/// <returns></returns>
public static int ConvertToUtf32(string value, int index)
{
#if SILVERLIGHT
return (int)value[index];
#else
if (char.IsSurrogate(value, index))
{
return ((int)value[index]);
}
else
{
return Char.ConvertToUtf32(value, index);
}
#endif
}
/// <summary>
/// Converts the specified Unicode code point into a UTF-16 encoded string.
/// </summary>
/// <param name="utf32"></param>
/// <returns></returns>
public static string ConvertFromUtf32(int utf32)
{
#if SILVERLIGHT
if (utf32 <= 0xFFFF)
{
return new string((char)utf32, 1);
}
utf32 -= 0x10000;
return new string(
new char[]
{
(char)((utf32 / 0x400) + 0xD800),
(char)((utf32 % 0x400) + 0xDC00)
});
#else
return Char.ConvertFromUtf32(utf32);
#endif
}
#endregion Char Methods
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using Dbg = System.Management.Automation.Diagnostics;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Management.Automation.Provider;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.InteropServices;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using DWORD = System.UInt32;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the base class from which all signature commands
/// are derived.
/// </summary>
public abstract class SignatureCommandsBase : PSCmdlet
{
/// <summary>
/// Gets or sets the path to the file for which to get or set the
/// digital signature.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")]
public string[] FilePath
{
get
{
return _path;
}
set
{
_path = value;
}
}
private string[] _path;
/// <summary>
/// Gets or sets the literal path to the file for which to get or set the
/// digital signature.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")]
[Alias("PSPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LiteralPath
{
get
{
return _path;
}
set
{
_path = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath = false;
/// <summary>
/// Gets or sets the digital signature to be written to
/// the output pipeline.
/// </summary>
protected Signature Signature
{
get { return _signature; }
set { _signature = value; }
}
private Signature _signature;
/// <summary>
/// Gets or sets the file type of the byte array containing the content with
/// digital signature.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] SourcePathOrExtension
{
get
{
return _sourcePathOrExtension;
}
set
{
_sourcePathOrExtension = value;
}
}
private string[] _sourcePathOrExtension;
/// <summary>
/// File contents as a byte array
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public byte[] Content
{
get { return _content; }
set
{
_content = value;
}
}
private byte[] _content;
//
// name of this command
//
private string _commandName;
/// <summary>
/// Initializes a new instance of the SignatureCommandsBase class,
/// using the given command name.
/// </summary>
///
/// <param name="name">
/// The name of the command.
/// </param>
protected SignatureCommandsBase(string name) : base()
{
_commandName = name;
}
//
// hide default ctor
//
private SignatureCommandsBase() : base() { }
/// <summary>
/// Processes records from the input pipeline.
/// For each input object, the command gets or
/// sets the digital signature on the object, and
/// and exports the object.
/// </summary>
protected override void ProcessRecord()
{
if (Content == null)
{
//
// this cannot happen as we have specified the Path
// property to be mandatory parameter
//
Dbg.Assert((FilePath != null) && (FilePath.Length > 0),
"GetSignatureCommand: Param binder did not bind path");
foreach (string p in FilePath)
{
Collection<string> paths = new Collection<string>();
// Expand wildcard characters
if (_isLiteralPath)
{
paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p));
}
else
{
try
{
foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p))
{
paths.Add(tempPath.ProviderPath);
}
}
catch (ItemNotFoundException)
{
WriteError(
SecurityUtils.CreateFileNotFoundErrorRecord(
SignatureCommands.FileNotFound,
"SignatureCommandsBaseFileNotFound", p));
}
}
if (paths.Count == 0)
continue;
bool foundFile = false;
foreach (string path in paths)
{
if (!System.IO.Directory.Exists(path))
{
foundFile = true;
string resolvedFilePath = SecurityUtils.GetFilePathOfExistingFile(this, path);
if (resolvedFilePath == null)
{
WriteError(SecurityUtils.CreateFileNotFoundErrorRecord(
SignatureCommands.FileNotFound,
"SignatureCommandsBaseFileNotFound",
path));
}
else
{
if ((Signature = PerformAction(resolvedFilePath)) != null)
{
WriteObject(Signature);
}
}
}
}
if (!foundFile)
{
WriteError(SecurityUtils.CreateFileNotFoundErrorRecord(
SignatureCommands.CannotRetrieveFromContainer,
"SignatureCommandsBaseCannotRetrieveFromContainer"));
}
}
}
else
{
foreach (string sourcePathOrExtension in SourcePathOrExtension)
{
if ((Signature = PerformAction(sourcePathOrExtension, Content)) != null)
{
WriteObject(Signature);
}
}
}
}
/// <summary>
/// Performs the action (ie: get signature, or set signature)
/// on the specified file.
/// </summary>
/// <param name="filePath">
/// The name of the file on which to perform the action.
/// </param>
protected abstract Signature PerformAction(string filePath);
/// <summary>
/// Performs the action (ie: get signature, or set signature)
/// on the specified contents.
/// </summary>
/// <param name="fileName">
/// The filename used for type if content is specified.
/// </param>
/// <param name="content">
/// The file contents on which to perform the action.
/// </param>
protected abstract Signature PerformAction(string fileName, byte[] content);
}
/// <summary>
/// Defines the implementation of the 'get-AuthenticodeSignature' cmdlet.
/// This cmdlet extracts the digital signature from the given file.
/// </summary>
[Cmdlet(VerbsCommon.Get, "AuthenticodeSignature", DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113307")]
[OutputType(typeof(Signature))]
public sealed class GetAuthenticodeSignatureCommand : SignatureCommandsBase
{
/// <summary>
/// Initializes a new instance of the GetSignatureCommand class.
/// </summary>
public GetAuthenticodeSignatureCommand() : base("Get-AuthenticodeSignature") { }
/// <summary>
/// Gets the signature from the specified file.
/// </summary>
/// <param name="filePath">
/// The name of the file on which to perform the action.
/// </param>
/// <returns>
/// The signature on the specified file.
/// </returns>
protected override Signature PerformAction(string filePath)
{
return SignatureHelper.GetSignature(filePath, null);
}
/// <summary>
/// Gets the signature from the specified file contents.
/// </summary>
/// <param name="sourcePathOrExtension">The file type associated with the contents</param>
/// <param name="content">
/// The contents of the file on which to perform the action.
/// </param>
/// <returns>
/// The signature on the specified file contents.
/// </returns>
protected override Signature PerformAction(string sourcePathOrExtension, byte[] content)
{
return SignatureHelper.GetSignature(sourcePathOrExtension, System.Text.Encoding.Unicode.GetString(content));
}
}
/// <summary>
/// Defines the implementation of the 'set-AuthenticodeSignature' cmdlet.
/// This cmdlet sets the digital signature on a given file.
/// </summary>
[Cmdlet(VerbsCommon.Set, "AuthenticodeSignature", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113391")]
[OutputType(typeof(Signature))]
public sealed class SetAuthenticodeSignatureCommand : SignatureCommandsBase
{
/// <summary>
/// Initializes a new instance of the SetAuthenticodeSignatureCommand class.
/// </summary>
public SetAuthenticodeSignatureCommand() : base("set-AuthenticodeSignature") { }
/// <summary>
/// Gets or sets the certificate with which to sign the
/// file.
/// </summary>
[Parameter(Position = 1, Mandatory = true)]
public X509Certificate2 Certificate
{
get
{
return _certificate;
}
set
{
_certificate = value;
}
}
private X509Certificate2 _certificate;
/// <summary>
/// Gets or sets the additional certificates to
/// include in the digital signature.
/// Use 'signer' to include only the signer's certificate.
/// Use 'notroot' to include all certificates in the certificate
/// chain, except for the root authority.
/// Use 'all' to include all certificates in the certificate chain.
///
/// Defaults to 'notroot'.
/// </summary>
///
[Parameter(Mandatory = false)]
[ValidateSet("signer", "notroot", "all")]
public string IncludeChain
{
get
{
return _includeChain;
}
set
{
_includeChain = value;
}
}
private string _includeChain = "notroot";
/// <summary>
/// Gets or sets the Url of the time stamping server.
/// The time stamping server certifies the exact time
/// that the certificate was added to the file.
/// </summary>
[Parameter(Mandatory = false)]
public string TimestampServer
{
get
{
return _timestampServer;
}
set
{
if (value == null)
{
value = String.Empty;
}
_timestampServer = value;
}
}
private string _timestampServer = "";
/// <summary>
/// Gets or sets the hash algorithm used for signing.
/// This string value must represent the name of a Cryptographic Algorithm
/// Identifier supported by Windows.
/// </summary>
[Parameter(Mandatory = false)]
public string HashAlgorithm
{
get
{
return _hashAlgorithm;
}
set
{
_hashAlgorithm = value;
}
}
private string _hashAlgorithm = null;
/// <summary>
/// Property that sets force parameter.
/// </summary>
[Parameter()]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
private bool _force;
/// <summary>
/// Sets the digital signature on the specified file.
/// </summary>
/// <param name="filePath">
/// The name of the file on which to perform the action.
/// </param>
/// <returns>
/// The signature on the specified file.
/// </returns>
protected override Signature PerformAction(string filePath)
{
SigningOption option = GetSigningOption(IncludeChain);
if (Certificate == null)
{
throw PSTraceSource.NewArgumentNullException("certificate");
}
//
// if the cert is not good for signing, we cannot
// process any more files. Exit the command.
//
if (!SecuritySupport.CertIsGoodForSigning(Certificate))
{
Exception e = PSTraceSource.NewArgumentException(
"certificate",
SignatureCommands.CertNotGoodForSigning);
throw e;
}
if (!ShouldProcess(filePath))
return null;
FileInfo readOnlyFileInfo = null;
try
{
if (this.Force)
{
try
{
// remove readonly attributes on the file
FileInfo fInfo = new FileInfo(filePath);
if (fInfo != null)
{
// Save some disk write time by checking whether file is readonly..
if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// remember to reset the read-only attribute later
readOnlyFileInfo = fInfo;
//Make sure the file is not read only
fInfo.Attributes &= ~(FileAttributes.ReadOnly);
}
}
}
// These are the known exceptions for File.Load and StreamWriter.ctor
catch (ArgumentException e)
{
ErrorRecord er = new ErrorRecord(
e,
"ForceArgumentException",
ErrorCategory.WriteError,
filePath
);
WriteError(er);
return null;
}
catch (IOException e)
{
ErrorRecord er = new ErrorRecord(
e,
"ForceIOException",
ErrorCategory.WriteError,
filePath
);
WriteError(er);
return null;
}
catch (UnauthorizedAccessException e)
{
ErrorRecord er = new ErrorRecord(
e,
"ForceUnauthorizedAccessException",
ErrorCategory.PermissionDenied,
filePath
);
WriteError(er);
return null;
}
catch (NotSupportedException e)
{
ErrorRecord er = new ErrorRecord(
e,
"ForceNotSupportedException",
ErrorCategory.WriteError,
filePath
);
WriteError(er);
return null;
}
catch (System.Security.SecurityException e)
{
ErrorRecord er = new ErrorRecord(
e,
"ForceSecurityException",
ErrorCategory.PermissionDenied,
filePath
);
WriteError(er);
return null;
}
}
//
// ProcessRecord() code in base class has already
// ascertained that filePath really represents an existing
// file. Thus we can safely call GetFileSize() below.
//
if (SecurityUtils.GetFileSize(filePath) < 4)
{
// Note that the message param comes first
string message = String.Format(
System.Globalization.CultureInfo.CurrentCulture,
UtilsStrings.FileSmallerThan4Bytes, filePath);
PSArgumentException e = new PSArgumentException(message, "filePath");
ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord(
e,
"SignatureCommandsBaseFileSmallerThan4Bytes"
);
WriteError(er);
return null;
}
return SignatureHelper.SignFile(option,
filePath,
Certificate,
TimestampServer,
_hashAlgorithm);
}
finally
{
// reset the read-only attribute
if (null != readOnlyFileInfo)
{
readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly;
}
}
}
/// <summary>
/// Not implemented
/// </summary>
protected override Signature PerformAction(string sourcePathOrExtension, byte[] content)
{
throw new NotImplementedException();
}
private struct SigningOptionInfo
{
internal SigningOption option;
internal string optionName;
internal SigningOptionInfo(SigningOption o, string n)
{
option = o;
optionName = n;
}
}
/// <summary>
/// association between SigningOption.* values and the
/// corresponding string names.
/// </summary>
private static readonly SigningOptionInfo[] s_sigOptionInfo =
{
new SigningOptionInfo(SigningOption.AddOnlyCertificate, "signer"),
new SigningOptionInfo(SigningOption.AddFullCertificateChainExceptRoot, "notroot"),
new SigningOptionInfo(SigningOption.AddFullCertificateChain, "all")
};
/// <summary>
/// get SigningOption value corresponding to a string name
/// </summary>
///
/// <param name="optionName"> name of option </param>
///
/// <returns> SigningOption </returns>
///
private static SigningOption GetSigningOption(string optionName)
{
foreach (SigningOptionInfo si in s_sigOptionInfo)
{
if (String.Equals(optionName, si.optionName,
StringComparison.OrdinalIgnoreCase))
{
return si.option;
}
}
return SigningOption.AddFullCertificateChainExceptRoot;
}
}
}
| |
/*
* 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.Net;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Client;
namespace OpenSim.Tests.Common
{
public class TestClient : IClientAPI, IClientCore
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing");
private Scene m_scene;
// Properties so that we can get at received data for test purposes
public List<uint> ReceivedKills { get; private set; }
public List<UUID> ReceivedOfflineNotifications { get; private set; }
public List<UUID> ReceivedOnlineNotifications { get; private set; }
public List<UUID> ReceivedFriendshipTerminations { get; private set; }
public List<ImageDataPacket> SentImageDataPackets { get; private set; }
public List<ImagePacketPacket> SentImagePacketPackets { get; private set; }
public List<ImageNotInDatabasePacket> SentImageNotInDatabasePackets { get; private set; }
// Test client specific events - for use by tests to implement some IClientAPI behaviour.
public event Action<RegionInfo, Vector3, Vector3> OnReceivedMoveAgentIntoRegion;
public event Action<ulong, IPEndPoint> OnTestClientInformClientOfNeighbour;
public event TestClientOnSendRegionTeleportDelegate OnTestClientSendRegionTeleport;
public event Action<ISceneEntity, PrimUpdateFlags> OnReceivedEntityUpdate;
public event OnReceivedChatMessageDelegate OnReceivedChatMessage;
public event Action<GridInstantMessage> OnReceivedInstantMessage;
public event Action<UUID> OnReceivedSendRebakeAvatarTextures;
public delegate void TestClientOnSendRegionTeleportDelegate(
ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL);
public delegate void OnReceivedChatMessageDelegate(
string message, byte type, Vector3 fromPos, string fromName,
UUID fromAgentID, UUID ownerID, byte source, byte audible);
// disable warning: public events, part of the public API
#pragma warning disable 67
public event Action<IClientAPI> OnLogout;
public event ObjectPermissions OnObjectPermissions;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event ParcelBuy OnParcelBuy;
public event Action<IClientAPI> OnConnectionClosed;
public event MoveItemsAndLeaveCopy OnMoveItemsAndLeaveCopy;
public event ImprovedInstantMessage OnInstantMessage;
public event ChatMessage OnChatFromClient;
public event TextureRequest OnRequestTexture;
public event RezObject OnRezObject;
public event ModifyTerrain OnModifyTerrain;
public event BakeTerrain OnBakeTerrain;
public event SetAppearance OnSetAppearance;
public event AvatarNowWearing OnAvatarNowWearing;
public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv;
public event UUIDNameRequest OnDetachAttachmentIntoInv;
public event ObjectAttach OnObjectAttach;
public event ObjectDeselect OnObjectDetach;
public event ObjectDrop OnObjectDrop;
public event StartAnim OnStartAnim;
public event StopAnim OnStopAnim;
public event ChangeAnim OnChangeAnim;
public event LinkObjects OnLinkObjects;
public event DelinkObjects OnDelinkObjects;
public event RequestMapBlocks OnRequestMapBlocks;
public event RequestMapName OnMapNameRequest;
public event TeleportLocationRequest OnTeleportLocationRequest;
public event TeleportLandmarkRequest OnTeleportLandmarkRequest;
public event TeleportCancel OnTeleportCancel;
public event DisconnectUser OnDisconnectUser;
public event RequestAvatarProperties OnRequestAvatarProperties;
public event SetAlwaysRun OnSetAlwaysRun;
public event DeRezObject OnDeRezObject;
public event RezRestoreToWorld OnRezRestoreToWorld;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall1 OnRequestWearables;
public event Action<IClientAPI, bool> OnCompleteMovementToRegion;
public event UpdateAgent OnPreAgentUpdate;
public event UpdateAgent OnAgentUpdate;
public event UpdateAgent OnAgentCameraUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
public event AvatarPickerRequest OnAvatarPickerRequest;
public event Action<IClientAPI> OnRequestAvatarsData;
public event AddNewPrim OnAddPrim;
public event RequestGodlikePowers OnRequestGodlikePowers;
public event GodKickUser OnGodKickUser;
public event ObjectDuplicate OnObjectDuplicate;
public event GrabObject OnGrabObject;
public event DeGrabObject OnDeGrabObject;
public event MoveObject OnGrabUpdate;
public event SpinStart OnSpinStart;
public event SpinObject OnSpinUpdate;
public event SpinStop OnSpinStop;
public event ViewerEffectEventHandler OnViewerEffect;
public event FetchInventory OnAgentDataUpdateRequest;
public event TeleportLocationRequest OnSetStartLocationRequest;
public event UpdateShape OnUpdatePrimShape;
public event ObjectExtraParams OnUpdateExtraParams;
public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily;
public event ObjectSelect OnObjectSelect;
public event ObjectRequest OnObjectRequest;
public event GenericCall7 OnObjectDescription;
public event GenericCall7 OnObjectName;
public event GenericCall7 OnObjectClickAction;
public event GenericCall7 OnObjectMaterial;
public event UpdatePrimFlags OnUpdatePrimFlags;
public event UpdatePrimTexture OnUpdatePrimTexture;
public event ClientChangeObject onClientChangeObject;
public event UpdateVector OnUpdatePrimGroupPosition;
public event UpdateVector OnUpdatePrimSinglePosition;
public event UpdatePrimRotation OnUpdatePrimGroupRotation;
public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation;
public event UpdateVector OnUpdatePrimScale;
public event UpdateVector OnUpdatePrimGroupScale;
public event StatusChange OnChildAgentStatus;
public event GenericCall2 OnStopMovement;
public event Action<UUID> OnRemoveAvatar;
public event CreateNewInventoryItem OnCreateNewInventoryItem;
public event LinkInventoryItem OnLinkInventoryItem;
public event CreateInventoryFolder OnCreateNewInventoryFolder;
public event UpdateInventoryFolder OnUpdateInventoryFolder;
public event MoveInventoryFolder OnMoveInventoryFolder;
public event RemoveInventoryFolder OnRemoveInventoryFolder;
public event RemoveInventoryItem OnRemoveInventoryItem;
public event FetchInventoryDescendents OnFetchInventoryDescendents;
public event PurgeInventoryDescendents OnPurgeInventoryDescendents;
public event FetchInventory OnFetchInventory;
public event RequestTaskInventory OnRequestTaskInventory;
public event UpdateInventoryItem OnUpdateInventoryItem;
public event CopyInventoryItem OnCopyInventoryItem;
public event MoveInventoryItem OnMoveInventoryItem;
public event UDPAssetUploadRequest OnAssetUploadRequest;
public event RequestTerrain OnRequestTerrain;
public event RequestTerrain OnUploadTerrain;
public event XferReceive OnXferReceive;
public event RequestXfer OnRequestXfer;
public event ConfirmXfer OnConfirmXfer;
public event AbortXfer OnAbortXfer;
public event RezScript OnRezScript;
public event UpdateTaskInventory OnUpdateTaskInventory;
public event MoveTaskInventory OnMoveTaskItem;
public event RemoveTaskInventory OnRemoveTaskItem;
public event RequestAsset OnRequestAsset;
public event GenericMessage OnGenericMessage;
public event UUIDNameRequest OnNameFromUUIDRequest;
public event UUIDNameRequest OnUUIDGroupNameRequest;
public event ParcelPropertiesRequest OnParcelPropertiesRequest;
public event ParcelDivideRequest OnParcelDivideRequest;
public event ParcelJoinRequest OnParcelJoinRequest;
public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest;
public event ParcelAbandonRequest OnParcelAbandonRequest;
public event ParcelGodForceOwner OnParcelGodForceOwner;
public event ParcelReclaim OnParcelReclaim;
public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest;
public event ParcelAccessListRequest OnParcelAccessListRequest;
public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest;
public event ParcelSelectObjects OnParcelSelectObjects;
public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest;
public event ParcelDeedToGroup OnParcelDeedToGroup;
public event ObjectDeselect OnObjectDeselect;
public event RegionInfoRequest OnRegionInfoRequest;
public event EstateCovenantRequest OnEstateCovenantRequest;
public event EstateChangeInfo OnEstateChangeInfo;
public event EstateManageTelehub OnEstateManageTelehub;
public event CachedTextureRequest OnCachedTextureRequest;
public event ObjectDuplicateOnRay OnObjectDuplicateOnRay;
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event GrantUserFriendRights OnGrantUserRights;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
public event UpdateAvatarProperties OnUpdateAvatarProperties;
public event ObjectIncludeInSearch OnObjectIncludeInSearch;
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event RequestPayPrice OnRequestPayPrice;
public event ObjectSaleInfo OnObjectSaleInfo;
public event ObjectBuy OnObjectBuy;
public event BuyObjectInventory OnBuyObjectInventory;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event RequestObjectPropertiesFamily OnObjectGroupRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
public event SetEstateFlagsRequest OnSetEstateFlagsRequest;
public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture;
public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture;
public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights;
public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest;
public event SetRegionTerrainSettings OnSetRegionTerrainSettings;
public event EstateRestartSimRequest OnEstateRestartSimRequest;
public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest;
public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest;
public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest;
public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest;
public event EstateDebugRegionRequest OnEstateDebugRegionRequest;
public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest;
public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest;
public event ScriptReset OnScriptReset;
public event GetScriptRunning OnGetScriptRunning;
public event SetScriptRunning OnSetScriptRunning;
public event Action<Vector3, bool, bool> OnAutoPilotGo;
public event TerrainUnacked OnUnackedTerrain;
public event RegionHandleRequest OnRegionHandleRequest;
public event ParcelInfoRequest OnParcelInfoRequest;
public event ActivateGesture OnActivateGesture;
public event DeactivateGesture OnDeactivateGesture;
public event ObjectOwner OnObjectOwner;
public event DirPlacesQuery OnDirPlacesQuery;
public event DirFindQuery OnDirFindQuery;
public event DirLandQuery OnDirLandQuery;
public event DirPopularQuery OnDirPopularQuery;
public event DirClassifiedQuery OnDirClassifiedQuery;
public event EventInfoRequest OnEventInfoRequest;
public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime;
public event MapItemRequest OnMapItemRequest;
public event OfferCallingCard OnOfferCallingCard;
public event AcceptCallingCard OnAcceptCallingCard;
public event DeclineCallingCard OnDeclineCallingCard;
public event SoundTrigger OnSoundTrigger;
public event StartLure OnStartLure;
public event TeleportLureRequest OnTeleportLureRequest;
public event NetworkStats OnNetworkStatsUpdate;
public event ClassifiedInfoRequest OnClassifiedInfoRequest;
public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
public event ClassifiedDelete OnClassifiedDelete;
public event ClassifiedGodDelete OnClassifiedGodDelete;
public event EventNotificationAddRequest OnEventNotificationAddRequest;
public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
public event EventGodDelete OnEventGodDelete;
public event ParcelDwellRequest OnParcelDwellRequest;
public event UserInfoRequest OnUserInfoRequest;
public event UpdateUserInfo OnUpdateUserInfo;
public event RetrieveInstantMessages OnRetrieveInstantMessages;
public event PickDelete OnPickDelete;
public event PickGodDelete OnPickGodDelete;
public event PickInfoUpdate OnPickInfoUpdate;
public event AvatarNotesUpdate OnAvatarNotesUpdate;
public event MuteListRequest OnMuteListRequest;
public event AvatarInterestUpdate OnAvatarInterestUpdate;
public event PlacesQuery OnPlacesQuery;
public event FindAgentUpdate OnFindAgent;
public event TrackAgentUpdate OnTrackAgent;
public event NewUserReport OnUserReport;
public event SaveStateHandler OnSaveState;
public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest;
public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest;
public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest;
public event FreezeUserUpdate OnParcelFreezeUser;
public event EjectUserUpdate OnParcelEjectUser;
public event ParcelBuyPass OnParcelBuyPass;
public event ParcelGodMark OnParcelGodMark;
public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest;
public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
public event SimWideDeletesDelegate OnSimWideDeletes;
public event SendPostcard OnSendPostcard;
public event ChangeInventoryItemFlags OnChangeInventoryItemFlags;
public event MuteListEntryUpdate OnUpdateMuteListEntry;
public event MuteListEntryRemove OnRemoveMuteListEntry;
public event GodlikeMessage onGodlikeMessage;
public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate;
public event GenericCall2 OnUpdateThrottles;
#pragma warning restore 67
/// <value>
/// This agent's UUID
/// </value>
private UUID m_agentId;
public ISceneAgent SceneAgent { get; set; }
/// <value>
/// The last caps seed url that this client was given.
/// </value>
public string CapsSeedUrl;
private Vector3 startPos = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 2);
public virtual Vector3 StartPos
{
get { return startPos; }
set { }
}
public virtual UUID AgentId
{
get { return m_agentId; }
}
public UUID SessionId { get; set; }
public UUID SecureSessionId { get; set; }
public virtual string FirstName
{
get { return m_firstName; }
}
private string m_firstName;
public virtual string LastName
{
get { return m_lastName; }
}
private string m_lastName;
public virtual String Name
{
get { return FirstName + " " + LastName; }
}
public int PingTimeMS { get { return 0; } }
public bool IsActive
{
get { return true; }
set { }
}
public bool IsLoggingOut { get; set; }
public UUID ActiveGroupId
{
get { return UUID.Zero; }
set { }
}
public string ActiveGroupName
{
get { return String.Empty; }
set { }
}
public ulong ActiveGroupPowers
{
get { return 0; }
set { }
}
public bool IsGroupMember(UUID groupID)
{
return false;
}
public Dictionary<UUID, ulong> GetGroupPowers()
{
return new Dictionary<UUID, ulong>();
}
public void SetGroupPowers(Dictionary<UUID, ulong> powers) { }
public ulong GetGroupPowers(UUID groupID)
{
return 0;
}
public virtual int NextAnimationSequenceNumber
{
get { return 1; }
}
public IScene Scene
{
get { return m_scene; }
}
public bool SendLogoutPacketWhenClosing
{
set { }
}
private uint m_circuitCode;
public uint CircuitCode
{
get { return m_circuitCode; }
set { m_circuitCode = value; }
}
public IPEndPoint RemoteEndPoint
{
get { return new IPEndPoint(IPAddress.Loopback, (ushort)m_circuitCode); }
}
public List<uint> SelectedObjects {get; private set;}
/// <summary>
/// Constructor
/// </summary>
/// <param name="agentData"></param>
/// <param name="scene"></param>
/// <param name="sceneManager"></param>
public TestClient(AgentCircuitData agentData, Scene scene)
{
m_agentId = agentData.AgentID;
m_firstName = agentData.firstname;
m_lastName = agentData.lastname;
m_circuitCode = agentData.circuitcode;
m_scene = scene;
SessionId = agentData.SessionID;
SecureSessionId = agentData.SecureSessionID;
CapsSeedUrl = agentData.CapsPath;
ReceivedKills = new List<uint>();
ReceivedOfflineNotifications = new List<UUID>();
ReceivedOnlineNotifications = new List<UUID>();
ReceivedFriendshipTerminations = new List<UUID>();
SentImageDataPackets = new List<ImageDataPacket>();
SentImagePacketPackets = new List<ImagePacketPacket>();
SentImageNotInDatabasePackets = new List<ImageNotInDatabasePacket>();
}
/// <summary>
/// Trigger chat coming from this connection.
/// </summary>
/// <param name="channel"></param>
/// <param name="type"></param>
/// <param name="message"></param>
public bool Chat(int channel, ChatTypeEnum type, string message)
{
ChatMessage handlerChatFromClient = OnChatFromClient;
if (handlerChatFromClient != null)
{
OSChatMessage args = new OSChatMessage();
args.Channel = channel;
args.From = Name;
args.Message = message;
args.Type = type;
args.Scene = Scene;
args.Sender = this;
args.SenderUUID = AgentId;
handlerChatFromClient(this, args);
}
return true;
}
/// <summary>
/// Attempt a teleport to the given region.
/// </summary>
/// <param name="regionHandle"></param>
/// <param name="position"></param>
/// <param name="lookAt"></param>
public void Teleport(ulong regionHandle, Vector3 position, Vector3 lookAt)
{
OnTeleportLocationRequest(this, regionHandle, position, lookAt, 16);
}
public void CompleteMovement()
{
if (OnCompleteMovementToRegion != null)
OnCompleteMovementToRegion(this, true);
}
/// <summary>
/// Emulate sending an IM from the viewer to the simulator.
/// </summary>
/// <param name='im'></param>
public void HandleImprovedInstantMessage(GridInstantMessage im)
{
ImprovedInstantMessage handlerInstantMessage = OnInstantMessage;
if (handlerInstantMessage != null)
handlerInstantMessage(this, im);
}
public virtual void ActivateGesture(UUID assetId, UUID gestureId)
{
}
public virtual void SendWearables(AvatarWearable[] wearables, int serial)
{
}
public virtual void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry)
{
}
public void SendCachedTextureResponse(ISceneEntity avatar, int serial, List<CachedTextureResponseArg> cachedTextures)
{
}
public virtual void Kick(string message)
{
}
public virtual void SendStartPingCheck(byte seq)
{
}
public virtual void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
{
}
public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
{
}
public virtual void SendKillObject(List<uint> localID)
{
ReceivedKills.AddRange(localID);
}
public void SendPartFullUpdate(ISceneEntity ent, uint? parentID)
{
}
public virtual void SetChildAgentThrottle(byte[] throttle)
{
}
public virtual void SetChildAgentThrottle(byte[] throttle, float factor)
{
}
public void SetAgentThrottleSilent(int throttle, int setting)
{
}
public int GetAgentThrottleSilent(int throttle)
{
return 0;
}
public byte[] GetThrottlesPacked(float multiplier)
{
return new byte[0];
}
public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs)
{
}
public virtual void SendChatMessage(
string message, byte type, Vector3 fromPos, string fromName,
UUID fromAgentID, UUID ownerID, byte source, byte audible)
{
// Console.WriteLine("mmm {0} {1} {2}", message, Name, AgentId);
if (OnReceivedChatMessage != null)
OnReceivedChatMessage(message, type, fromPos, fromName, fromAgentID, ownerID, source, audible);
}
public void SendInstantMessage(GridInstantMessage im)
{
if (OnReceivedInstantMessage != null)
OnReceivedInstantMessage(im);
}
public void SendGenericMessage(string method, UUID invoice, List<string> message)
{
}
public void SendGenericMessage(string method, UUID invoice, List<byte[]> message)
{
}
public virtual bool CanSendLayerData()
{
return false;
}
public virtual void SendLayerData(float[] map)
{
}
public virtual void SendLayerData(int px, int py, float[] map)
{
}
public virtual void SendLayerData(int px, int py, float[] map, bool track)
{
}
public virtual void SendWindData(int version, Vector2[] windSpeeds) { }
public virtual void SendCloudData(int version, float[] cloudCover) { }
public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look)
{
if (OnReceivedMoveAgentIntoRegion != null)
OnReceivedMoveAgentIntoRegion(regInfo, pos, look);
}
public virtual AgentCircuitData RequestClientInfo()
{
AgentCircuitData agentData = new AgentCircuitData();
agentData.AgentID = AgentId;
agentData.SessionID = SessionId;
agentData.SecureSessionID = UUID.Zero;
agentData.circuitcode = m_circuitCode;
agentData.child = false;
agentData.firstname = m_firstName;
agentData.lastname = m_lastName;
ICapabilitiesModule capsModule = m_scene.RequestModuleInterface<ICapabilitiesModule>();
if (capsModule != null)
{
agentData.CapsPath = capsModule.GetCapsPath(m_agentId);
agentData.ChildrenCapSeeds = new Dictionary<ulong, string>(capsModule.GetChildrenSeeds(m_agentId));
}
return agentData;
}
public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint)
{
if (OnTestClientInformClientOfNeighbour != null)
OnTestClientInformClientOfNeighbour(neighbourHandle, neighbourExternalEndPoint);
}
public virtual void SendRegionTeleport(
ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL)
{
m_log.DebugFormat(
"[TEST CLIENT]: Received SendRegionTeleport for {0} {1} on {2}", m_firstName, m_lastName, m_scene.Name);
CapsSeedUrl = capsURL;
if (OnTestClientSendRegionTeleport != null)
OnTestClientSendRegionTeleport(
regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL);
}
public virtual void SendTeleportFailed(string reason)
{
m_log.DebugFormat(
"[TEST CLIENT]: Teleport failed for {0} {1} on {2} with reason {3}",
m_firstName, m_lastName, m_scene.Name, reason);
}
public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt,
IPEndPoint newRegionExternalEndPoint, string capsURL)
{
// This is supposed to send a packet to the client telling it's ready to start region crossing.
// Instead I will just signal I'm ready, mimicking the communication behavior.
// It's ugly, but avoids needless communication setup. This is used in ScenePresenceTests.cs.
// Arthur V.
wh.Set();
}
public virtual void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
{
}
public virtual void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags)
{
}
public virtual void SendTeleportStart(uint flags)
{
}
public void SendTeleportProgress(uint flags, string message)
{
}
public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance, int transactionType, UUID sourceID, bool sourceIsGroup, UUID destID, bool destIsGroup, int amount, string item)
{
}
public virtual void SendPayPrice(UUID objectID, int[] payPrice)
{
}
public virtual void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations)
{
}
public virtual void SendDialog(string objectname, UUID objectID, UUID ownerID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels)
{
}
public void SendAvatarDataImmediate(ISceneEntity avatar)
{
}
public void SendEntityUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags)
{
if (OnReceivedEntityUpdate != null)
OnReceivedEntityUpdate(entity, updateFlags);
}
public void ReprioritizeUpdates()
{
}
public void FlushPrimUpdates()
{
}
public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID,
List<InventoryItemBase> items,
List<InventoryFolderBase> folders,
int version,
bool fetchFolders,
bool fetchItems)
{
}
public virtual void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item)
{
}
public virtual void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackID)
{
}
public void SendInventoryItemCreateUpdate(InventoryItemBase Item, UUID transactionID, uint callbackId)
{
}
public virtual void SendRemoveInventoryItem(UUID itemID)
{
}
public virtual void SendBulkUpdateInventory(InventoryNodeBase node)
{
}
public void SendTakeControls(int controls, bool passToAgent, bool TakeControls)
{
}
public virtual void SendTaskInventory(UUID taskID, short serial, byte[] fileName)
{
}
public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data, bool isTaskInventory)
{
}
public virtual void SendAbortXferPacket(ulong xferID)
{
}
public virtual void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit,
int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor,
int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay,
int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent)
{
}
public virtual void SendNameReply(UUID profileId, string firstname, string lastname)
{
}
public virtual void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID)
{
}
public virtual void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain,
byte flags)
{
}
public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain)
{
}
public void SendAttachedSoundGainChange(UUID objectID, float gain)
{
}
public void SendAlertMessage(string message)
{
}
public void SendAgentAlertMessage(string message, bool modal)
{
}
public void SendAlertMessage(string message, string info)
{
}
public void SendSystemAlertMessage(string message)
{
}
public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message,
string url)
{
}
public virtual void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
{
if (OnRegionHandShakeReply != null)
{
OnRegionHandShakeReply(this);
}
}
public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
{
}
public void SendConfirmXfer(ulong xferID, uint PacketID)
{
}
public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName)
{
}
public void SendInitiateDownload(string simFileName, string clientFileName)
{
}
public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
{
ImageDataPacket im = new ImageDataPacket();
im.Header.Reliable = false;
im.ImageID.Packets = numParts;
im.ImageID.ID = ImageUUID;
if (ImageSize > 0)
im.ImageID.Size = ImageSize;
im.ImageData.Data = ImageData;
im.ImageID.Codec = imageCodec;
im.Header.Zerocoded = true;
SentImageDataPackets.Add(im);
}
public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData)
{
ImagePacketPacket im = new ImagePacketPacket();
im.Header.Reliable = false;
im.ImageID.Packet = partNumber;
im.ImageID.ID = imageUuid;
im.ImageData.Data = imageData;
SentImagePacketPackets.Add(im);
}
public void SendImageNotFound(UUID imageid)
{
ImageNotInDatabasePacket p = new ImageNotInDatabasePacket();
p.ImageID.ID = imageid;
SentImageNotInDatabasePackets.Add(p);
}
public void SendShutdownConnectionNotice()
{
}
public void SendSimStats(SimStats stats)
{
}
public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags)
{
}
public void SendObjectPropertiesReply(ISceneEntity entity)
{
}
public void SendAgentOffline(UUID[] agentIDs)
{
ReceivedOfflineNotifications.AddRange(agentIDs);
}
public void SendAgentOnline(UUID[] agentIDs)
{
ReceivedOnlineNotifications.AddRange(agentIDs);
}
public void SendFindAgent(UUID HunterID, UUID PreyID, double GlobalX, double GlobalY)
{
}
public void SendSitResponse(UUID TargetID, Vector3 OffsetPos,
Quaternion SitOrientation, bool autopilot,
Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook)
{
}
public void SendAdminResponse(UUID Token, uint AdminLevel)
{
}
public void SendGroupMembership(GroupMembershipData[] GroupMembership)
{
}
public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase)
{
}
public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks)
{
}
public void SendViewerTime(int phase)
{
}
public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] membershipType,
string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL,
UUID partnerID)
{
}
public int DebugPacketLevel { get; set; }
public void InPacket(object NewPack)
{
}
public void ProcessInPacket(Packet NewPack)
{
}
/// <summary>
/// This is a TestClient only method to do shutdown tasks that are normally carried out by LLUDPServer.RemoveClient()
/// </summary>
public void Logout()
{
// We must set this here so that the presence is removed from the PresenceService by the PresenceDetector
IsLoggingOut = true;
Close();
}
public void Close()
{
Close(true, false);
}
public void Close(bool sendStop, bool force)
{
// Fire the callback for this connection closing
// This is necesary to get the presence detector to notice that a client has logged out.
if (OnConnectionClosed != null)
OnConnectionClosed(this);
m_scene.RemoveClient(AgentId, true);
}
public void Start()
{
throw new NotImplementedException();
}
public void Stop()
{
}
public void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message)
{
}
public void SendLogoutPacket()
{
}
public void Terminate()
{
}
public ClientInfo GetClientInfo()
{
return null;
}
public void SetClientInfo(ClientInfo info)
{
}
public void SendScriptQuestion(UUID objectID, string taskName, string ownerName, UUID itemID, int question)
{
}
public void SendHealth(float health)
{
}
public void SendTelehubInfo(UUID ObjectID, string ObjectName, Vector3 ObjectPos, Quaternion ObjectRot, List<Vector3> SpawnPoint)
{
}
public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID)
{
}
public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID)
{
}
public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
{
}
public void SendEstateCovenantInformation(UUID covenant)
{
}
public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, uint covenantChanged, string abuseEmail, UUID estateOwner)
{
}
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, ILandObject lo, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
{
}
public void SendLandAccessListData(List<LandAccessEntry> accessList, uint accessFlag, int localLandID)
{
}
public void SendForceClientSelectObjects(List<uint> objectIDs)
{
}
public void SendCameraConstraint(Vector4 ConstraintPlane)
{
}
public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount)
{
}
public void SendLandParcelOverlay(byte[] data, int sequence_id)
{
}
public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
{
}
public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType,
string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
{
}
public void SendGroupNameReply(UUID groupLLUID, string GroupName)
{
}
public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia)
{
}
public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running)
{
}
public void SendAsset(AssetRequestToClient req)
{
}
public void SendTexture(AssetBase TextureAsset)
{
}
public void SendSetFollowCamProperties (UUID objectID, SortedDictionary<int, float> parameters)
{
}
public void SendClearFollowCamProperties (UUID objectID)
{
}
public void SendRegionHandle (UUID regoinID, ulong handle)
{
}
public void SendParcelInfo (RegionInfo info, LandData land, UUID parcelID, uint x, uint y)
{
}
public void SetClientOption(string option, string value)
{
}
public string GetClientOption(string option)
{
return string.Empty;
}
public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt)
{
}
public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data)
{
}
public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data)
{
}
public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data)
{
}
public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data)
{
}
public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data)
{
}
public void SendDirLandReply(UUID queryID, DirLandReplyData[] data)
{
}
public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data)
{
}
public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
{
}
public void SendEventInfoReply (EventData info)
{
}
public void SendOfferCallingCard (UUID destID, UUID transactionID)
{
}
public void SendAcceptCallingCard (UUID transactionID)
{
}
public void SendDeclineCallingCard (UUID transactionID)
{
}
public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data)
{
}
public void SendAgentGroupDataUpdate(UUID avatarID, GroupMembershipData[] data)
{
}
public void SendJoinGroupReply(UUID groupID, bool success)
{
}
public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool succss)
{
}
public void SendLeaveGroupReply(UUID groupID, bool success)
{
}
public void SendTerminateFriend(UUID exFriendID)
{
ReceivedFriendshipTerminations.Add(exFriendID);
}
public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
{
//throw new NotImplementedException();
return false;
}
public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name)
{
}
public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price)
{
}
public void SendAgentDropGroup(UUID groupID)
{
}
public void SendAvatarNotesReply(UUID targetID, string text)
{
}
public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks)
{
}
public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds)
{
}
public void SendParcelDwellReply(int localID, UUID parcelID, float dwell)
{
}
public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
{
}
public void SendCreateGroupReply(UUID groupID, bool success, string message)
{
}
public void RefreshGroupMembership()
{
}
public void UpdateGroupMembership(GroupMembershipData[] data)
{
}
public void GroupMembershipRemove(UUID GroupID)
{
}
public void GroupMembershipAddReplace(UUID GroupID,ulong GroupPowers)
{
}
public void SendUseCachedMuteList()
{
}
public void SendMuteListUpdate(string filename)
{
}
public void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled)
{
}
public bool TryGet<T>(out T iface)
{
iface = default(T);
return false;
}
public T Get<T>()
{
return default(T);
}
public void Disconnect(string reason)
{
}
public void Disconnect()
{
}
public void SendRebakeAvatarTextures(UUID textureID)
{
if (OnReceivedSendRebakeAvatarTextures != null)
OnReceivedSendRebakeAvatarTextures(textureID);
}
public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages)
{
}
public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt)
{
}
public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier)
{
}
public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt)
{
}
public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes)
{
}
public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
{
}
public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
{
}
public void SendTextBoxRequest(string message, int chatChannel, string objectname, UUID ownerID, string ownerFirstName, string ownerLastName, UUID objectId)
{
}
public void SendAgentTerseUpdate(ISceneEntity presence)
{
}
public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data)
{
}
public void SendSelectedPartsProprieties(List<ISceneEntity> parts)
{
}
public void SendPartPhysicsProprieties(ISceneEntity entity)
{
}
}
}
| |
namespace Nancy.Tests.Unit.Routing
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FakeItEasy;
using Nancy.Helpers;
using Nancy.Responses.Negotiation;
using Nancy.Routing;
using Nancy.Tests.Fakes;
using Xunit;
public class DefaultRequestDispatcherFixture
{
private readonly DefaultRequestDispatcher requestDispatcher;
private readonly IRouteResolver routeResolver;
private readonly IRouteInvoker routeInvoker;
private readonly IList<IResponseProcessor> responseProcessors;
private IResponseNegotiator negotiator;
public DefaultRequestDispatcherFixture()
{
this.responseProcessors = new List<IResponseProcessor>();
this.routeResolver = A.Fake<IRouteResolver>();
this.routeInvoker = A.Fake<IRouteInvoker>();
this.negotiator = A.Fake<IResponseNegotiator>();
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg =>
{
var tcs = new TaskCompletionSource<Response>();
var actionResult =
((Route)arg.Arguments[0]).Action.Invoke(arg.Arguments[2], new CancellationToken());
if (actionResult.IsFaulted)
{
tcs.SetException(actionResult.Exception.InnerException);
}
else
{
tcs.SetResult(actionResult.Result);
}
return tcs.Task;
});
this.requestDispatcher =
new DefaultRequestDispatcher(this.routeResolver, this.responseProcessors, this.routeInvoker, this.negotiator);
var resolvedRoute = new ResolveResult
{
Route = new FakeRoute(),
Parameters = DynamicDictionary.Empty,
Before = null,
After = null,
OnError = null
};
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>._)).Returns(resolvedRoute);
}
[Fact]
public void Should_invoke_module_before_hook_followed_by_resolved_route_followed_by_module_after_hook()
{
// Given
var capturedExecutionOrder = new List<string>();
var expectedExecutionOrder = new[] { "Prehook", "RouteInvoke", "Posthook" };
var route = new FakeRoute
{
Action = (parameters, token) =>
{
capturedExecutionOrder.Add("RouteInvoke");
return CreateResponseTask(null);
}
};
var before = new BeforePipeline();
before += (ctx) =>
{
capturedExecutionOrder.Add("Prehook");
return null;
};
var after = new AfterPipeline();
after += (ctx) =>
{
capturedExecutionOrder.Add("Posthook");
};
var resolvedRoute = new ResolveResult
{
Route = route,
Parameters = DynamicDictionary.Empty,
Before = before,
After = after,
OnError = null
};
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
capturedExecutionOrder.Count().ShouldEqual(3);
capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
}
[Fact]
public void Should_not_invoke_resolved_route_if_module_before_hook_returns_response_but_should_invoke_module_after_hook()
{
// Given
var capturedExecutionOrder = new List<string>();
var expectedExecutionOrder = new[] { "Prehook", "Posthook" };
var route = new FakeRoute
{
Action = (parameters, token) =>
{
capturedExecutionOrder.Add("RouteInvoke");
return null;
}
};
var before = new BeforePipeline();
before += ctx =>
{
capturedExecutionOrder.Add("Prehook");
return new Response();
};
var after = new AfterPipeline();
after += ctx => capturedExecutionOrder.Add("Posthook");
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
null);
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
capturedExecutionOrder.Count().ShouldEqual(2);
capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
}
[Fact]
public void Should_return_response_from_module_before_hook_when_not_null()
{
// Given
var expectedResponse = new Response();
Func<NancyContext, Response> moduleBeforeHookResponse = ctx => expectedResponse;
var before = new BeforePipeline();
before += moduleBeforeHookResponse;
var after = new AfterPipeline();
after += ctx => { };
var route = new FakeRoute();
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
null);
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
context.Response.ShouldBeSameAs(expectedResponse);
}
[Fact]
public void Should_allow_module_after_hook_to_change_response()
{
// Given
var before = new BeforePipeline();
before += ctx => null;
var response = new Response();
Func<NancyContext, Response> moduleAfterHookResponse = ctx => response;
var after = new AfterPipeline();
after += ctx =>
{
ctx.Response = moduleAfterHookResponse(ctx);
};
var route = new FakeRoute();
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
null);
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
context.Response.ShouldBeSameAs(response);
}
[Fact]
public void HandleRequest_should_allow_module_after_hook_to_add_items_to_context()
{
// Given
var route = new FakeRoute();
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx => ctx.Items.Add("RoutePostReq", new object());
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
null);
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
context.Items.ContainsKey("RoutePostReq").ShouldBeTrue();
}
[Fact]
public void Should_set_the_route_parameters_from_resolved_route()
{
// Given
const string expectedPath = "/the/path";
var context =
new NancyContext
{
Request = new FakeRequest("GET", expectedPath)
};
var parameters = new DynamicDictionary();
var resolvedRoute = new ResolveResult(
new FakeRoute(),
parameters,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
((DynamicDictionary)context.Parameters).ShouldBeSameAs(parameters);
}
[Fact]
public void Should_set_the_context_resolved_route_from_resolve_result()
{
// Given
const string expectedPath = "/the/path";
var context =
new NancyContext
{
Request = new FakeRequest("GET", expectedPath)
};
var expectedRoute = new FakeRoute();
var resolveResult = new ResolveResult(
expectedRoute,
new DynamicDictionary(),
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolveResult);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
context.ResolvedRoute.ShouldBeSameAs(expectedRoute);
}
[Fact]
public void Should_invoke_route_resolver_with_context_for_current_request()
{
// Given
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/")
};
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
A.CallTo(() => this.routeResolver.Resolve(context)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_invoke_route_resolver_with_path_when_path_does_not_contain_file_extension()
{
// Given
const string expectedPath = "/the/path";
var requestedPath = string.Empty;
var context =
new NancyContext
{
Request = new FakeRequest("GET", expectedPath)
};
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)
.Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedPath.ShouldEqual(expectedPath);
}
[Fact]
public void Should_invoke_route_resolver_with_passed_in_accept_headers_when_path_does_not_contain_file_extensions()
{
// Given
var expectedAcceptHeaders = new List<Tuple<string, decimal>>
{
{ new Tuple<string, decimal>("application/json", 0.8m) },
{ new Tuple<string, decimal>("application/xml", 0.4m) }
};
var requestedAcceptHeaders =
new List<Tuple<string, decimal>>();
var request = new FakeRequest("GET", "/")
{
Headers = { Accept = expectedAcceptHeaders }
};
var context =
new NancyContext { Request = request };
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())
.Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedAcceptHeaders.ShouldHaveCount(2);
requestedAcceptHeaders[0].Item1.ShouldEqual("application/json");
requestedAcceptHeaders[0].Item2.ShouldEqual(0.8m);
requestedAcceptHeaders[1].Item1.ShouldEqual("application/xml");
requestedAcceptHeaders[1].Item2.ShouldEqual(0.4m);
}
[Fact]
public void Should_invoke_route_resolver_with_extension_stripped_from_path_when_path_does_contain_file_extension_and_mapped_response_processor_exists()
{
// Given
var requestedPath = string.Empty;
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var processor =
A.Fake<IResponseProcessor>();
this.responseProcessors.Add(processor);
var mappings = new List<Tuple<string, MediaRange>>
{
{ new Tuple<string, MediaRange>("json", "application/json") }
};
A.CallTo(() => processor.ExtensionMappings).Returns(mappings);
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)
.Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedPath.ShouldEqual("/user");
}
[Fact]
public void Should_invoke_route_resolver_with_extension_stripped_only_at_the_end_from_path_when_path_does_contain_file_extension_and_mapped_response_processor_exists()
{
// Given
var requestedPath = string.Empty;
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/directory.jsonfiles/user.json")
};
var processor =
A.Fake<IResponseProcessor>();
this.responseProcessors.Add(processor);
var mappings = new List<Tuple<string, MediaRange>>
{
{ new Tuple<string, MediaRange>("json", "application/json") }
};
A.CallTo(() => processor.ExtensionMappings).Returns(mappings);
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)
.Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedPath.ShouldEqual("/directory.jsonfiles/user");
}
[Fact]
public void Should_invoke_route_resolver_with_path_containing_when_path_does_contain_file_extension_and_no_mapped_response_processor_exists()
{
// Given
var requestedPath = string.Empty;
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)
.Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedPath.ShouldEqual("/user.json");
}
[Fact]
public void Should_invoke_route_resolver_with_distinct_mapped_media_ranged_when_path_contains_extension_and_mapped_response_processors_exists()
{
// Given
var requestedAcceptHeaders =
new List<Tuple<string, decimal>>();
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var jsonProcessor =
A.Fake<IResponseProcessor>();
var jsonProcessormappings =
new List<Tuple<string, MediaRange>> { { new Tuple<string, MediaRange>("json", "application/json") } };
A.CallTo(() => jsonProcessor.ExtensionMappings).Returns(jsonProcessormappings);
var otherProcessor =
A.Fake<IResponseProcessor>();
var otherProcessormappings =
new List<Tuple<string, MediaRange>>
{
{ new Tuple<string, MediaRange>("json", "application/json") },
{ new Tuple<string, MediaRange>("xml", "application/xml") }
};
A.CallTo(() => otherProcessor.ExtensionMappings).Returns(otherProcessormappings);
this.responseProcessors.Add(jsonProcessor);
this.responseProcessors.Add(otherProcessor);
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())
.Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedAcceptHeaders.ShouldHaveCount(1);
requestedAcceptHeaders[0].Item1.ShouldEqual("application/json");
}
[Fact]
public void Should_set_quality_to_high_for_mapped_media_ranges_before_invoking_route_resolver_when_path_contains_extension_and_mapped_response_processors_exists()
{
// Given
var requestedAcceptHeaders =
new List<Tuple<string, decimal>>();
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var jsonProcessor =
A.Fake<IResponseProcessor>();
var jsonProcessormappings =
new List<Tuple<string, MediaRange>> { { new Tuple<string, MediaRange>("json", "application/json") } };
A.CallTo(() => jsonProcessor.ExtensionMappings).Returns(jsonProcessormappings);
this.responseProcessors.Add(jsonProcessor);
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())
.Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
requestedAcceptHeaders.ShouldHaveCount(1);
Assert.True(requestedAcceptHeaders[0].Item2 > 1.0m);
}
[Fact]
public void Should_call_route_invoker_with_resolved_route()
{
// Given
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
A.CallTo(() => this.routeInvoker.Invoke(resolvedRoute.Route, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_invoke_route_resolver_with_path_containing_extension_when_mapped_response_processor_existed_but_no_route_match_was_found()
{
// Given
var requestedAcceptHeaders =
new List<Tuple<string, decimal>>();
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var jsonProcessor =
A.Fake<IResponseProcessor>();
var jsonProcessormappings =
new List<Tuple<string, MediaRange>> { { new Tuple<string, MediaRange>("json", "application/json") } };
A.CallTo(() => jsonProcessor.ExtensionMappings).Returns(jsonProcessormappings);
this.responseProcessors.Add(jsonProcessor);
var resolvedRoute = new ResolveResult(
new NotFoundRoute("GET", "/"),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context))
.Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())
.Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>._)).MustHaveHappened(Repeated.Exactly.Twice);
}
[Fact]
public void Should_call_route_invoker_with_captured_parameters()
{
// Given
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var parameters = new DynamicDictionary();
var resolvedRoute = new ResolveResult(
new FakeRoute(),
parameters,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, parameters, A<NancyContext>._)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_call_route_invoker_with_context()
{
// Given
var context =
new NancyContext
{
Request = new FakeRequest("GET", "/user.json")
};
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, context)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_invoke_module_onerror_hook_when_module_before_hook_throws_exception()
{
// Given
var capturedExecutionOrder = new List<string>();
var expectedExecutionOrder = new[] { "Prehook", "OnErrorHook" };
var before = new BeforePipeline();
before += ctx =>
{
capturedExecutionOrder.Add("Prehook");
throw new Exception("Prehook");
};
var after = new AfterPipeline();
after += ctx => capturedExecutionOrder.Add("Posthook");
var route = new FakeRoute((parameters, ct) =>
{
capturedExecutionOrder.Add("RouteInvoke");
return CreateResponseTask(null);
});
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => { capturedExecutionOrder.Add("OnErrorHook"); return new Response(); });
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
capturedExecutionOrder.Count().ShouldEqual(2);
capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
}
[Fact]
public void Should_invoke_module_onerror_hook_when_route_invoker_throws_exception()
{
// Given
var capturedExecutionOrder = new List<string>();
var expectedExecutionOrder = new[] { "RouteInvoke", "OnErrorHook" };
var route = new FakeRoute
{
Action = (parameters, ct) =>
{
capturedExecutionOrder.Add("RouteInvoke");
return TaskHelpers.GetFaultedTask<dynamic>(new Exception("RouteInvoke"));
}
};
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx => capturedExecutionOrder.Add("Posthook");
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => { capturedExecutionOrder.Add("OnErrorHook"); return new Response(); });
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
capturedExecutionOrder.Count().ShouldEqual(2);
capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
}
[Fact]
public void Should_invoke_module_onerror_hook_when_module_after_hook_throws_exception()
{
// Given
var capturedExecutionOrder = new List<string>();
var expectedExecutionOrder = new[] { "Posthook", "OnErrorHook" };
var route = new FakeRoute
{
Action = (parameters, ct) => CreateResponseTask(null)
};
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx =>
{
capturedExecutionOrder.Add("Posthook");
throw new Exception("Posthook");
};
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => { capturedExecutionOrder.Add("OnErrorHook"); return new Response(); });
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
// When
this.requestDispatcher.Dispatch(context, new CancellationToken());
// Then
capturedExecutionOrder.Count().ShouldEqual(2);
capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
}
[Fact]
public void Should_rethrow_exception_when_onerror_hook_does_return_response()
{
// Given
var route = new FakeRoute
{
Action = (parameters, ct) => { throw new Exception(); }
};
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx => { };
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => { return null; });
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
//When
// Then
Assert.Throws<Exception>(() => this.requestDispatcher.Dispatch(context, new CancellationToken()));
}
[Fact]
public void Should_not_rethrow_exception_when_onerror_hook_returns_response()
{
// Given
var route = new FakeRoute
{
Action = (parameters,ct) => TaskHelpers.GetFaultedTask<dynamic>(new Exception())
};
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx => { };
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => new Response());
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
//When
// Then
Assert.DoesNotThrow(() => this.requestDispatcher.Dispatch(context, new CancellationToken()));
}
#if !__MonoCS__
[Fact]
public void should_preserve_stacktrace_when_rethrowing_the_excption()
{
// Given
var route = new FakeRoute
{
Action = (o,ct) => BrokenMethod()
};
var before = new BeforePipeline();
before += ctx => null;
var after = new AfterPipeline();
after += ctx => { };
var resolvedRoute = new ResolveResult(
route,
DynamicDictionary.Empty,
before,
after,
(ctx, ex) => { return null; });
A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
var context =
new NancyContext { Request = new Request("GET", "/", "http") };
var exception = Assert.Throws<Exception>(() => this.requestDispatcher.Dispatch(context, new CancellationToken()));
exception.StackTrace.ShouldContain("BrokenMethod");
}
#endif
private static Task<dynamic> CreateResponseTask(dynamic response)
{
var tcs =
new TaskCompletionSource<dynamic>();
tcs.SetResult(response);
return tcs.Task;
}
private static Task<dynamic> BrokenMethod()
{
throw new Exception("You called the broken method!");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue
{
internal sealed class TopSyntaxComparer : SyntaxComparer
{
internal static readonly TopSyntaxComparer Instance = new TopSyntaxComparer();
private TopSyntaxComparer()
{
}
#region Tree Traversal
protected internal override bool TryGetParent(SyntaxNode node, out SyntaxNode parent)
{
var parentNode = node.Parent;
parent = parentNode;
return parentNode != null;
}
protected internal override IEnumerable<SyntaxNode> GetChildren(SyntaxNode node)
{
Debug.Assert(GetLabel(node) != IgnoredNode);
return HasChildren(node) ? EnumerateChildren(node) : null;
}
private IEnumerable<SyntaxNode> EnumerateChildren(SyntaxNode node)
{
foreach (var child in node.ChildNodesAndTokens())
{
var childNode = child.AsNode();
if (childNode != null && GetLabel(childNode) != IgnoredNode)
{
yield return childNode;
}
}
}
protected internal override IEnumerable<SyntaxNode> GetDescendants(SyntaxNode node)
{
foreach (var descendant in node.DescendantNodesAndTokens(
descendIntoChildren: HasChildren,
descendIntoTrivia: false))
{
var descendantNode = descendant.AsNode();
if (descendantNode != null && GetLabel(descendantNode) != IgnoredNode)
{
yield return descendantNode;
}
}
}
private static bool HasChildren(SyntaxNode node)
{
// Leaves are labeled statements that don't have a labeled child.
// We also return true for non-labeled statements.
bool isLeaf;
Label label = Classify(node.Kind(), out isLeaf, ignoreVariableDeclarations: false);
// ignored should always be reported as leaves
Debug.Assert(label != Label.Ignored || isLeaf);
return !isLeaf;
}
#endregion
#region Labels
// Assumptions:
// - Each listed label corresponds to one or more syntax kinds.
// - Nodes with same labels might produce Update edits, nodes with different labels don't.
// - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label.
// (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label).
// - All descendants of a node whose kind is listed here will be ignored regardless of their labels
internal enum Label
{
CompilationUnit,
NamespaceDeclaration,
ExternAliasDirective, // tied to parent
UsingDirective, // tied to parent
TypeDeclaration,
EnumDeclaration,
DelegateDeclaration,
FieldDeclaration, // tied to parent
FieldVariableDeclaration, // tied to parent
FieldVariableDeclarator, // tied to parent
MethodDeclaration, // tied to parent
OperatorDeclaration, // tied to parent
ConversionOperatorDeclaration, // tied to parent
ConstructorDeclaration, // tied to parent
DestructorDeclaration, // tied to parent
PropertyDeclaration, // tied to parent
IndexerDeclaration, // tied to parent
EventDeclaration, // tied to parent
EnumMemberDeclaration, // tied to parent
AccessorList, // tied to parent
AccessorDeclaration, // tied to parent
TypeParameterList, // tied to parent
TypeParameterConstraintClause, // tied to parent
TypeParameter, // tied to parent
ParameterList, // tied to parent
BracketedParameterList, // tied to parent
Parameter, // tied to parent
AttributeList, // tied to parent
Attribute, // tied to parent
// helpers:
Count,
Ignored = IgnoredNode
}
/// <summary>
/// Return 1 if it is desirable to report two edits (delete and insert) rather than a move edit
/// when the node changes its parent.
/// </summary>
private static int TiedToAncestor(Label label)
{
switch (label)
{
case Label.ExternAliasDirective:
case Label.UsingDirective:
case Label.FieldDeclaration:
case Label.FieldVariableDeclaration:
case Label.FieldVariableDeclarator:
case Label.MethodDeclaration:
case Label.OperatorDeclaration:
case Label.ConversionOperatorDeclaration:
case Label.ConstructorDeclaration:
case Label.DestructorDeclaration:
case Label.PropertyDeclaration:
case Label.IndexerDeclaration:
case Label.EventDeclaration:
case Label.EnumMemberDeclaration:
case Label.AccessorDeclaration:
case Label.AccessorList:
case Label.TypeParameterList:
case Label.TypeParameter:
case Label.TypeParameterConstraintClause:
case Label.ParameterList:
case Label.BracketedParameterList:
case Label.Parameter:
case Label.AttributeList:
case Label.Attribute:
return 1;
default:
return 0;
}
}
// internal for testing
internal static Label Classify(SyntaxKind kind, out bool isLeaf, bool ignoreVariableDeclarations)
{
switch (kind)
{
case SyntaxKind.CompilationUnit:
isLeaf = false;
return Label.CompilationUnit;
case SyntaxKind.GlobalStatement:
// TODO:
isLeaf = true;
return Label.Ignored;
case SyntaxKind.ExternAliasDirective:
isLeaf = true;
return Label.ExternAliasDirective;
case SyntaxKind.UsingDirective:
isLeaf = true;
return Label.UsingDirective;
case SyntaxKind.NamespaceDeclaration:
isLeaf = false;
return Label.NamespaceDeclaration;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
isLeaf = false;
return Label.TypeDeclaration;
case SyntaxKind.EnumDeclaration:
isLeaf = false;
return Label.EnumDeclaration;
case SyntaxKind.DelegateDeclaration:
isLeaf = false;
return Label.DelegateDeclaration;
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
isLeaf = false;
return Label.FieldDeclaration;
case SyntaxKind.VariableDeclaration:
isLeaf = ignoreVariableDeclarations;
return ignoreVariableDeclarations ? Label.Ignored : Label.FieldVariableDeclaration;
case SyntaxKind.VariableDeclarator:
isLeaf = true;
return ignoreVariableDeclarations ? Label.Ignored : Label.FieldVariableDeclarator;
case SyntaxKind.MethodDeclaration:
isLeaf = false;
return Label.MethodDeclaration;
case SyntaxKind.ConversionOperatorDeclaration:
isLeaf = false;
return Label.ConversionOperatorDeclaration;
case SyntaxKind.OperatorDeclaration:
isLeaf = false;
return Label.OperatorDeclaration;
case SyntaxKind.ConstructorDeclaration:
isLeaf = false;
return Label.ConstructorDeclaration;
case SyntaxKind.DestructorDeclaration:
isLeaf = true;
return Label.DestructorDeclaration;
case SyntaxKind.PropertyDeclaration:
isLeaf = false;
return Label.PropertyDeclaration;
case SyntaxKind.IndexerDeclaration:
isLeaf = false;
return Label.IndexerDeclaration;
case SyntaxKind.EventDeclaration:
isLeaf = false;
return Label.EventDeclaration;
case SyntaxKind.EnumMemberDeclaration:
isLeaf = false; // attribute may be applied
return Label.EnumMemberDeclaration;
case SyntaxKind.AccessorList:
isLeaf = false;
return Label.AccessorList;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
isLeaf = true;
return Label.AccessorDeclaration;
case SyntaxKind.TypeParameterList:
isLeaf = false;
return Label.TypeParameterList;
case SyntaxKind.TypeParameterConstraintClause:
isLeaf = false;
return Label.TypeParameterConstraintClause;
case SyntaxKind.TypeParameter:
isLeaf = false; // children: attributes
return Label.TypeParameter;
case SyntaxKind.ParameterList:
isLeaf = false;
return Label.ParameterList;
case SyntaxKind.BracketedParameterList:
isLeaf = false;
return Label.BracketedParameterList;
case SyntaxKind.Parameter:
// We ignore anonymous methods and lambdas,
// we only care about parameters of member declarations.
isLeaf = false; // children: attributes
return Label.Parameter;
case SyntaxKind.AttributeList:
isLeaf = false;
return Label.AttributeList;
case SyntaxKind.Attribute:
isLeaf = true;
return Label.Attribute;
default:
isLeaf = true;
return Label.Ignored;
}
}
protected internal override int GetLabel(SyntaxNode node)
{
return (int)GetLabel(node.Kind());
}
internal static Label GetLabel(SyntaxKind kind)
{
bool isLeaf;
return Classify(kind, out isLeaf, ignoreVariableDeclarations: false);
}
// internal for testing
internal static bool HasLabel(SyntaxKind kind, bool ignoreVariableDeclarations)
{
bool isLeaf;
return Classify(kind, out isLeaf, ignoreVariableDeclarations) != Label.Ignored;
}
protected internal override int LabelCount
{
get { return (int)Label.Count; }
}
protected internal override int TiedToAncestor(int label)
{
return TiedToAncestor((Label)label);
}
#endregion
#region Comparisons
public override bool ValuesEqual(SyntaxNode left, SyntaxNode right)
{
Func<SyntaxKind, bool> ignoreChildFunction;
switch (left.Kind())
{
// all syntax kinds with a method body child:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
// When comparing method bodies we need to NOT ignore VariableDeclaration and VariableDeclarator children,
// but when comparing field definitions we should ignore VariableDeclarations children.
ignoreChildFunction = childKind => HasLabel(childKind, ignoreVariableDeclarations: true);
break;
default:
if (HasChildren(left))
{
ignoreChildFunction = childKind => HasLabel(childKind, ignoreVariableDeclarations: false);
}
else
{
ignoreChildFunction = null;
}
break;
}
return SyntaxFactory.AreEquivalent(left, right, ignoreChildFunction);
}
protected override bool TryComputeWeightedDistance(SyntaxNode leftNode, SyntaxNode rightNode, out double distance)
{
SyntaxNodeOrToken? leftName = TryGetName(leftNode);
SyntaxNodeOrToken? rightName = TryGetName(rightNode);
Debug.Assert(rightName.HasValue == leftName.HasValue);
if (leftName.HasValue)
{
distance = ComputeDistance(leftName.Value, rightName.Value);
return true;
}
else
{
distance = 0;
return false;
}
}
private static SyntaxNodeOrToken? TryGetName(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ExternAliasDirective:
return ((ExternAliasDirectiveSyntax)node).Identifier;
case SyntaxKind.UsingDirective:
return ((UsingDirectiveSyntax)node).Name;
case SyntaxKind.NamespaceDeclaration:
return ((NamespaceDeclarationSyntax)node).Name;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
return ((TypeDeclarationSyntax)node).Identifier;
case SyntaxKind.EnumDeclaration:
return ((EnumDeclarationSyntax)node).Identifier;
case SyntaxKind.DelegateDeclaration:
return ((DelegateDeclarationSyntax)node).Identifier;
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.VariableDeclaration:
return null;
case SyntaxKind.VariableDeclarator:
return ((VariableDeclaratorSyntax)node).Identifier;
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)node).Identifier;
case SyntaxKind.ConversionOperatorDeclaration:
return ((ConversionOperatorDeclarationSyntax)node).Type;
case SyntaxKind.OperatorDeclaration:
return ((OperatorDeclarationSyntax)node).OperatorToken;
case SyntaxKind.ConstructorDeclaration:
return ((ConstructorDeclarationSyntax)node).Identifier;
case SyntaxKind.DestructorDeclaration:
return ((DestructorDeclarationSyntax)node).Identifier;
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)node).Identifier;
case SyntaxKind.IndexerDeclaration:
return null;
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)node).Identifier;
case SyntaxKind.EnumMemberDeclaration:
return ((EnumMemberDeclarationSyntax)node).Identifier;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
return null;
case SyntaxKind.TypeParameterConstraintClause:
return ((TypeParameterConstraintClauseSyntax)node).Name.Identifier;
case SyntaxKind.TypeParameter:
return ((TypeParameterSyntax)node).Identifier;
case SyntaxKind.TypeParameterList:
case SyntaxKind.ParameterList:
case SyntaxKind.BracketedParameterList:
return null;
case SyntaxKind.Parameter:
return ((ParameterSyntax)node).Identifier;
case SyntaxKind.AttributeList:
return ((AttributeListSyntax)node).Target;
case SyntaxKind.Attribute:
return ((AttributeSyntax)node).Name;
default:
return null;
}
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Parabox.CSG
{
internal class CSG_Node
{
public List<CSG_Polygon> polygons;
public CSG_Node front; /// Reference to front node.
public CSG_Node back; /// Reference to front node.
public CSG_Plane plane;
public CSG_Node()
{
this.front = null;
this.back = null;
}
public CSG_Node(List<CSG_Polygon> list)
{
Build(list);
// this.front = null;
// this.back = null;
}
public CSG_Node(List<CSG_Polygon> list, CSG_Plane plane, CSG_Node front, CSG_Node back)
{
this.polygons = list;
this.plane = plane;
this.front = front;
this.back = back;
}
public CSG_Node Clone()
{
CSG_Node clone = new CSG_Node(this.polygons, this.plane, this.front, this.back);
return clone;
}
// Remove all polygons in this BSP tree that are inside the other BSP tree
// `bsp`.
public void ClipTo(CSG_Node other)
{
this.polygons = other.ClipPolygons(this.polygons);
if (this.front != null)
{
this.front.ClipTo(other);
}
if (this.back != null)
{
this.back.ClipTo(other);
}
}
// Convert solid space to empty space and empty space to solid space.
public void Invert()
{
for (int i = 0; i < this.polygons.Count; i++)
this.polygons[i].Flip();
this.plane.Flip();
if (this.front != null)
{
this.front.Invert();
}
if (this.back != null)
{
this.back.Invert();
}
CSG_Node tmp = this.front;
this.front = this.back;
this.back = tmp;
}
// Build a BSP tree out of `polygons`. When called on an existing tree, the
// new polygons are filtered down to the bottom of the tree and become new
// nodes there. Each set of polygons is partitioned using the first polygon
// (no heuristic is used to pick a good split).
public void Build(List<CSG_Polygon> list)
{
if (list.Count < 1)
return;
if (this.plane == null || !this.plane.Valid())
{
this.plane = new CSG_Plane();
this.plane.normal = list[0].plane.normal;
this.plane.w = list[0].plane.w;
}
if(this.polygons == null)
this.polygons = new List<CSG_Polygon>();
List<CSG_Polygon> list_front = new List<CSG_Polygon>();
List<CSG_Polygon> list_back = new List<CSG_Polygon>();
for (int i = 0; i < list.Count; i++)
{
this.plane.SplitPolygon(list[i], this.polygons, this.polygons, list_front, list_back);
}
if (list_front.Count > 0)
{
if (this.front == null)
this.front = new CSG_Node();
this.front.Build(list_front);
}
if (list_back.Count > 0)
{
if (this.back == null)
this.back = new CSG_Node();
this.back.Build(list_back);
}
}
// Recursively remove all polygons in `polygons` that are inside this BSP
// tree.
public List<CSG_Polygon> ClipPolygons(List<CSG_Polygon> list)
{
if (!this.plane.Valid())
{
return list;
}
List<CSG_Polygon> list_front = new List<CSG_Polygon>();
List<CSG_Polygon> list_back = new List<CSG_Polygon>();
for (int i = 0; i < list.Count; i++)
{
this.plane.SplitPolygon(list[i], list_front, list_back, list_front, list_back);
}
if (this.front != null)
{
list_front = this.front.ClipPolygons(list_front);
}
if (this.back != null)
{
list_back = this.back.ClipPolygons(list_back);
}
else
{
list_back.Clear();
}
// Position [First, Last]
// list_front.insert(list_front.end(), list_back.begin(), list_back.end());
list_front.AddRange(list_back);
return list_front;
}
// Return a list of all polygons in this BSP tree.
public List<CSG_Polygon> AllPolygons()
{
List<CSG_Polygon> list = this.polygons;
List<CSG_Polygon> list_front = new List<CSG_Polygon>(), list_back = new List<CSG_Polygon>();
if (this.front != null)
{
list_front = this.front.AllPolygons();
}
if (this.back != null)
{
list_back = this.back.AllPolygons();
}
list.AddRange(list_front);
list.AddRange(list_back);
return list;
}
#region STATIC OPERATIONS
// Return a new CSG solid representing space in either this solid or in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
public static CSG_Node Union(CSG_Node a1, CSG_Node b1)
{
CSG_Node a = a1.Clone();
CSG_Node b = b1.Clone();
a.ClipTo(b);
b.ClipTo(a);
b.Invert();
b.ClipTo(a);
b.Invert();
a.Build(b.AllPolygons());
CSG_Node ret = new CSG_Node(a.AllPolygons());
return ret;
}
// Return a new CSG solid representing space in this solid but not in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
public static CSG_Node Subtract(CSG_Node a1, CSG_Node b1)
{
CSG_Node a = a1.Clone();
CSG_Node b = b1.Clone();
a.Invert();
a.ClipTo(b);
b.ClipTo(a);
b.Invert();
b.ClipTo(a);
b.Invert();
a.Build(b.AllPolygons());
a.Invert();
CSG_Node ret = new CSG_Node(a.AllPolygons());
return ret;
}
// Return a new CSG solid representing space both this solid and in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
public static CSG_Node Intersect(CSG_Node a1, CSG_Node b1)
{
CSG_Node a = a1.Clone();
CSG_Node b = b1.Clone();
a.Invert();
b.ClipTo(a);
b.Invert();
a.ClipTo(b);
b.ClipTo(a);
a.Build(b.AllPolygons());
a.Invert();
CSG_Node ret = new CSG_Node(a.AllPolygons());
return ret;
}
#endregion
}
}
| |
using Neo.Cryptography;
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace Neo.IO.Data.LevelDB
{
public struct Slice : IComparable<Slice>, IEquatable<Slice>
{
internal byte[] buffer;
internal Slice(IntPtr data, UIntPtr length)
{
buffer = new byte[(int)length];
Marshal.Copy(data, buffer, 0, (int)length);
}
public int CompareTo(Slice other)
{
for (int i = 0; i < buffer.Length && i < other.buffer.Length; i++)
{
int r = buffer[i].CompareTo(other.buffer[i]);
if (r != 0) return r;
}
return buffer.Length.CompareTo(other.buffer.Length);
}
public bool Equals(Slice other)
{
if (buffer.Length != other.buffer.Length) return false;
return buffer.SequenceEqual(other.buffer);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (!(obj is Slice)) return false;
return Equals((Slice)obj);
}
public override int GetHashCode()
{
return (int)buffer.Murmur32(0);
}
public byte[] ToArray()
{
return buffer ?? new byte[0];
}
unsafe public bool ToBoolean()
{
if (buffer.Length != sizeof(bool))
throw new InvalidCastException();
fixed (byte* pbyte = &buffer[0])
{
return *((bool*)pbyte);
}
}
public byte ToByte()
{
if (buffer.Length != sizeof(byte))
throw new InvalidCastException();
return buffer[0];
}
unsafe public double ToDouble()
{
if (buffer.Length != sizeof(double))
throw new InvalidCastException();
fixed (byte* pbyte = &buffer[0])
{
return *((double*)pbyte);
}
}
unsafe public short ToInt16()
{
if (buffer.Length != sizeof(short))
throw new InvalidCastException();
fixed (byte* pbyte = &buffer[0])
{
return *((short*)pbyte);
}
}
unsafe public int ToInt32()
{
if (buffer.Length != sizeof(int))
throw new InvalidCastException();
fixed (byte* pbyte = &buffer[0])
{
return *((int*)pbyte);
}
}
unsafe public long ToInt64()
{
if (buffer.Length != sizeof(long))
throw new InvalidCastException();
fixed (byte* pbyte = &buffer[0])
{
return *((long*)pbyte);
}
}
unsafe public float ToSingle()
{
if (buffer.Length != sizeof(float))
throw new InvalidCastException();
fixed (byte* pbyte = &buffer[0])
{
return *((float*)pbyte);
}
}
public override string ToString()
{
return Encoding.UTF8.GetString(buffer);
}
unsafe public ushort ToUInt16()
{
if (buffer.Length != sizeof(ushort))
throw new InvalidCastException();
fixed (byte* pbyte = &buffer[0])
{
return *((ushort*)pbyte);
}
}
unsafe public uint ToUInt32(int index = 0)
{
if (buffer.Length != sizeof(uint) + index)
throw new InvalidCastException();
fixed (byte* pbyte = &buffer[index])
{
return *((uint*)pbyte);
}
}
unsafe public ulong ToUInt64()
{
if (buffer.Length != sizeof(ulong))
throw new InvalidCastException();
fixed (byte* pbyte = &buffer[0])
{
return *((ulong*)pbyte);
}
}
public static implicit operator Slice(byte[] data)
{
return new Slice { buffer = data };
}
public static implicit operator Slice(bool data)
{
return new Slice { buffer = BitConverter.GetBytes(data) };
}
public static implicit operator Slice(byte data)
{
return new Slice { buffer = new[] { data } };
}
public static implicit operator Slice(double data)
{
return new Slice { buffer = BitConverter.GetBytes(data) };
}
public static implicit operator Slice(short data)
{
return new Slice { buffer = BitConverter.GetBytes(data) };
}
public static implicit operator Slice(int data)
{
return new Slice { buffer = BitConverter.GetBytes(data) };
}
public static implicit operator Slice(long data)
{
return new Slice { buffer = BitConverter.GetBytes(data) };
}
public static implicit operator Slice(float data)
{
return new Slice { buffer = BitConverter.GetBytes(data) };
}
public static implicit operator Slice(string data)
{
return new Slice { buffer = Encoding.UTF8.GetBytes(data) };
}
public static implicit operator Slice(ushort data)
{
return new Slice { buffer = BitConverter.GetBytes(data) };
}
public static implicit operator Slice(uint data)
{
return new Slice { buffer = BitConverter.GetBytes(data) };
}
public static implicit operator Slice(ulong data)
{
return new Slice { buffer = BitConverter.GetBytes(data) };
}
public static bool operator <(Slice x, Slice y)
{
return x.CompareTo(y) < 0;
}
public static bool operator <=(Slice x, Slice y)
{
return x.CompareTo(y) <= 0;
}
public static bool operator >(Slice x, Slice y)
{
return x.CompareTo(y) > 0;
}
public static bool operator >=(Slice x, Slice y)
{
return x.CompareTo(y) >= 0;
}
public static bool operator ==(Slice x, Slice y)
{
return x.Equals(y);
}
public static bool operator !=(Slice x, Slice y)
{
return !x.Equals(y);
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets.Wrappers
{
using NLog.Common;
using NLog.Conditions;
using NLog.Internal;
/// <summary>
/// Causes a flush on a wrapped target if LogEvent satisfies the <see cref="Condition"/>.
/// If condition isn't set, flushes on each write.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/AutoFlushWrapper-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/AutoFlushWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/AutoFlushWrapper/Simple/Example.cs" />
/// </example>
[Target("AutoFlushWrapper", IsWrapper = true)]
public class AutoFlushTargetWrapper : WrapperTargetBase
{
/// <summary>
/// Gets or sets the condition expression. Log events who meet this condition will cause
/// a flush on the wrapped target.
/// </summary>
/// <docgen category='General Options' order='10' />
public ConditionExpression Condition { get; set; }
/// <summary>
/// Delay the flush until the LogEvent has been confirmed as written
/// </summary>
/// <docgen category='General Options' order='10' />
public bool AsyncFlush
{
get => _asyncFlush ?? true;
set => _asyncFlush = value;
}
private bool? _asyncFlush;
/// <summary>
/// Only flush when LogEvent matches condition. Ignore explicit-flush, config-reload-flush and shutdown-flush
/// </summary>
/// <docgen category='General Options' order='10' />
public bool FlushOnConditionOnly { get; set; }
private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter();
/// <summary>
/// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public AutoFlushTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="name">Name of the target</param>
public AutoFlushTargetWrapper(string name, Target wrappedTarget)
: this(wrappedTarget)
{
Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AutoFlushTargetWrapper(Target wrappedTarget)
{
WrappedTarget = wrappedTarget;
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
if (!_asyncFlush.HasValue && !TargetSupportsAsyncFlush(WrappedTarget))
{
AsyncFlush = false; // Disable AsyncFlush, so the intended trigger works
}
}
private static bool TargetSupportsAsyncFlush(Target wrappedTarget)
{
if (wrappedTarget is BufferingTargetWrapper)
return false;
#if !NET3_5 && !SILVERLIGHT4
if (wrappedTarget is AsyncTaskTarget)
return false;
#endif
return true;
}
/// <summary>
/// Forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write()
/// and calls <see cref="Target.Flush(AsyncContinuation)"/> on it if LogEvent satisfies
/// the flush condition or condition is null.
/// </summary>
/// <param name="logEvent">Logging event to be written out.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
if (Condition == null || Condition.Evaluate(logEvent.LogEvent).Equals(true))
{
if (AsyncFlush)
{
AsyncContinuation currentContinuation = logEvent.Continuation;
AsyncContinuation wrappedContinuation = (ex) =>
{
if (ex == null)
FlushOnCondition();
_pendingManualFlushList.CompleteOperation(ex);
currentContinuation(ex);
};
_pendingManualFlushList.BeginOperation();
WrappedTarget.WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(wrappedContinuation));
}
else
{
WrappedTarget.WriteAsyncLogEvent(logEvent);
FlushOnCondition();
}
}
else
{
WrappedTarget.WriteAsyncLogEvent(logEvent);
}
}
/// <summary>
/// Schedules a flush operation, that triggers when all pending flush operations are completed (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
if (FlushOnConditionOnly)
asyncContinuation(null);
else
FlushWrappedTarget(asyncContinuation);
}
private void FlushOnCondition()
{
if (FlushOnConditionOnly)
FlushWrappedTarget((e) => { });
else
FlushAsync((e) => { });
}
private void FlushWrappedTarget(AsyncContinuation asyncContinuation)
{
var wrappedContinuation = _pendingManualFlushList.RegisterCompletionNotification(asyncContinuation);
WrappedTarget.Flush(wrappedContinuation);
}
/// <summary>
/// Closes the target.
/// </summary>
protected override void CloseTarget()
{
_pendingManualFlushList.Clear(); // Maybe consider to wait a short while if pending requests?
base.CloseTarget();
}
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using FunWithSqlite.Data;
namespace FunWithSqlite.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.2");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("FunWithSqlite.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("FunWithSqlite.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("FunWithSqlite.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("FunWithSqlite.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
//using Sem.Service;
//using EbInstanceModel;
//using IFC2X3;
//namespace Sem.Predefined
//{
// public class SemPaintFinishPatch : BbElementGeometry
// {
// public BbSurfaceGeometry _bbSurfaceGeometry;
// public BbSurfaceGeometry Patch
// {
// get { return _bbSurfaceGeometry; }
// set
// {
// _bbSurfaceGeometry = value;
// IfcCovering.Representation = _bbSurfaceGeometry.IfcProductDefinitionShape;
// }
// }
// public BbLocalPlacement3D _bbLocalPlacement3D;
// public BbLocalPlacement3D BbLocalPlacement3D
// {
// get { return _bbLocalPlacement3D; }
// set
// {
// _bbLocalPlacement3D = value;
// IfcCovering.ObjectPlacement = _bbLocalPlacement3D.IfcLocalPlacement;
// }
// }
// protected SemPaintFinishPatch(string name, string type, BbSurfaceGeometry semSurfaceGeometry)
// : base(name, type)
// {
// Patch = semSurfaceGeometry;
// }
// protected SemPaintFinishPatch()
// { }
// protected SemPaintFinishPatch(IfcCovering paint, IfcRelCoversBldgElements agg)
// {
// IfcCovering = paint;
// IfcRelCoversBldgElements = agg;
// }
// public static SemPaintFinishPatch Create(string name, string type, BbSurfaceGeometry semSurfaceGeometry)
// {
// var pat = new SemPaintFinishPatch(name, type, semSurfaceGeometry);
// BbInstanceDB.AddToExport(pat);
// return pat;
// }
// public void AddToElement(BbElement element, BbLocalPlacement3D semLocalPlacement3D)
// {
// AddToElement(element);
// BbLocalPlacement3D = semLocalPlacement3D;
// }
// }
//}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using BlackBox.Service;
using IFC2X3;
using EbInstanceModel;
namespace BlackBox.Predefined
{
/// <summary>
/// Paint finish.
/// </summary>
public partial class BbPaintFinishApplied : BbPaintFinish
{
[EarlyBindingInstanceCollection]
public IList<IfcCovering> IfcCoveringList
{
get
{
var a = (from x in _hostElements
select x.IfcObject).OfType<IfcCovering>().ToList();
return a.Any() ? a.ToList() : null;
}
}
[EarlyBindingInstanceCollection]
public IList<IfcRelCoversBldgElements> IfcRelCoversBldgElementsList
{
get { return _ifcRelCoversBldgElementsList; }
}
readonly List<IfcCovering> _ifcCoveringList = new List<IfcCovering>();
readonly List<IfcRelCoversBldgElements> _ifcRelCoversBldgElementsList = new List<IfcRelCoversBldgElements>();
readonly List<BbPaintFinish> _paintFinishes = new List<BbPaintFinish>();
readonly List<BbElement> _hostElements = new List<BbElement>();
public BbElement TheElement
{
get
{
return _hostElements.Count == 1 ? _hostElements[0] : null;
}
}
// BLASTED, GALVANIZED, PAINTED, PRIMED and ETC
//protected BbPaintFinishApplied(BbElement hostElement, BbPaintFinish paintFinish, BbSurfaceGeometry shape, BbPosition3D localPlacement3D)
//{
// if (hostElement == null) { throw new ArgumentNullException(); }
// if (hostElement.IfcObject == null) { throw new NullReferenceException(); }
// _hostElements.Add(hostElement);
// _paintFinishes.Add(paintFinish);
// //var ploc = BbLocalPlacement3D.Create(TheElement.ObjectBbLocalPlacement, localPlacement3D);
// //paintFinish.BbLocalPlacement3D = ploc;
// var bElement = hostElement.IfcObject as IfcElement;
// if (bElement == null){throw new InvalidCastException();}
// var relCovers = new IfcRelCoversBldgElements
// {
// GlobalId = IfcGloballyUniqueId.NewGuid(),
// OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory,
// RelatingBuildingElement = bElement,
// RelatedCoverings = new List<IfcCovering>{paintFinish.IfcCovering},
// };
// IfcRelCoversBldgElementsList.Add(relCovers);
//}
///// <summary>
/////
///// </summary>
///// <param name="type">one of SemSurfaceTreatmentProperties</param>
//protected BbPaintFinish()
// : this(@"FINISH", @"PAINTED")
//{
// //IfcCovering = new IfcCovering
// //{
// // GlobalId = IfcGloballyUniqueId.NewGuid(),
// // OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory,
// // //Name = name,
// // ObjectType = "FINISH",
// // //Tag = id,
// // PredefinedType = IfcCoveringTypeEnum.USERDEFINED,
// // /// set propertySet value with type parameter value
// //};n
//}
//protected BbPaintFinishApplied(IfcCovering paint, IfcRelCoversBldgElements agg)
//{
// _ifcCoveringList.Add(paint);
// _ifcRelCoversBldgElementsList.Add(agg);
//}
//public static BbPaintFinishApplied Create(BbElement hostElement, BbPaintFinish paintFinish, BbPosition3D localPlacement3D)
//{
// var paintFinishes = new BbPaintFinishApplied(hostElement, paintFinish, localPlacement3D);
// BbInstanceDB.AddToExport(paintFinishes);
// return paintFinishes;
//}
//public static BbPaintFinish Create()
//{
// var paintFinish = new BbPaintFinish();
// BbInstanceDB.AddToExport(paintFinish);
// return paintFinish;
//}
public void AddToOtherElement(BbElement element)
{
if (element == null)
{
throw new ArgumentNullException();
}
if (element.IfcObject == null)
{
throw new NullReferenceException();
}
var bElement = element.IfcObject as IfcElement;
if (bElement == null)
{
throw new InvalidCastException();
}
var relCovers = new IfcRelCoversBldgElements
{
RelatingBuildingElement = bElement,
};
IfcRelCoversBldgElementsList.Add(relCovers);
//PaintFinishes.Add(paintFinish);
}
public void AddNextLayer(string name, string type)
{
var ifcCovering = new IfcCovering
{
GlobalId = IfcGloballyUniqueId.NewGuid(),
OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory,
Name = name,
ObjectType = type,
//Tag = id,
PredefinedType = IfcCoveringTypeEnum.USERDEFINED,
};
_ifcCoveringList.Add(ifcCovering);
foreach (var coversBldgElement in _ifcRelCoversBldgElementsList)
{
coversBldgElement.RelatedCoverings.Add(ifcCovering);
}
}
//public void AddGeometryToAll(BbSurfaceGeometry geometryDefinition)
//{
// foreach (var ifcCovering in _ifcCoveringList)
// {
// ifcCovering.Representation = geometryDefinition.IfcProductDefinitionShape;
// ifcCovering.ObjectPlacement = _bbLocalPlacement3D.IfcLocalPlacement;
// }
//}
//public void AddToElement(BbElement element, BbLocalPlacement3D semLocalPlacement3D)
//{
// AddToElement(element);
// BbLocalPlacement3D = semLocalPlacement3D;
//}
//public void AddToElement(SemPaintFinishPatch semPaintFinish, BbLocalPlacement3D semLocalPlacement3D)
//{
// AddToElement(semPaintFinish);
// semPaintFinish.BbLocalPlacement3D = semLocalPlacement3D;
//}
//public List<BbPaintFinish> PaintFinishes { get; protected set; }
//public void AddPaintFinish(BbPaintFinish paintFinish)
//{
// if (PaintFinishes == null)
// {
// PaintFinishes = new List<BbPaintFinish>();
// }
// if (IfcRelCoversBldgElements == null)
// {
// IfcRelCoversBldgElements = new IfcRelCoversBldgElements
// {
// GlobalId = IfcGloballyUniqueId.NewGuid(),
// OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory,
// RelatingBuildingElement = IfcObject as IfcElement,
// RelatedCoverings = new List<IfcCovering>(),
// };
// }
// IfcRelCoversBldgElements.RelatedCoverings.Add(paintFinish.IfcCovering);
// PaintFinishes.Add(paintFinish);
//}
//public void AddPaintFinish(SemPaintFinishPatch semPaintFinish, BbLocalPlacement3D semLocalPlacement3D)
//{
// AddPaintFinish(semPaintFinish);
// semPaintFinish.BbLocalPlacement3D = semLocalPlacement3D;
//}
//public static BbLocalPlacement3D RetrieveLocalPlacement(BbPaintFinish pFinishPatch)
//{
// var localPlacement = new BbLocalPlacement3D();
// //if (!EarlyBindingInstanceModel.TheModel.DataByType.ContainsKey("IfcLocalPlacement")) return null;
// var collection = EarlyBindingInstanceModel.GetDataByType("IfcLocalPlacement").Values;
// foreach (var item in collection)
// {
// if (item.EIN == pFinishPatch.IfcCovering.ObjectPlacement.EIN)
// {
// var placement = item as IfcLocalPlacement;
// if (placement == null) continue;
// var Instance = new BbLocalPlacement3D { IfcLocalPlacement = placement };
// BbInstanceDB.AddToExport(Instance);
// localPlacement = Instance;
// }
// }
// return localPlacement;
//}
//public static BbSurfaceGeometry RetrieveSurfaceGeometry(BbPaintFinish pFinishPatch)
//{
// //if (!EarlyBindingInstanceModel.TheModel.DataByType.ContainsKey("IfcCurveBoundedPlane")) return null;
// var collection = EarlyBindingInstanceModel.GetDataByType("IfcCurveBoundedPlane").Values;
// var ret = new BbSurfaceGeometry();
// foreach (var item in collection)
// {
// var shapeRepresentations = pFinishPatch.IfcCovering.Representation.Representations;
// foreach (var shapeRepresentation in shapeRepresentations)
// {
// var RepItems = shapeRepresentation.Items;
// foreach (var RepItem in RepItems)
// {
// if (item.EIN == RepItem.EIN)
// {
// var curvePlane = item as IfcCurveBoundedPlane;
// if (curvePlane == null) continue;
// var surfaceGeometry = new BbSurfaceGeometry { ifcCurveBoundedPlane = curvePlane };
// BbInstanceDB.AddToExport(surfaceGeometry);
// ret = surfaceGeometry;
// }
// }
// }
// }
// return ret;
//}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Threading;
namespace SteamTrade
{
/// <summary>
/// This class represents the TF2 Item schema as deserialized from its
/// JSON representation.
/// </summary>
public class Schema
{
private const string SchemaMutexName = "steam_bot_cache_file_mutex";
private const string SchemaApiUrlBase = "https://api.steampowered.com/IEconItems_440/GetSchemaItems/v1/?key=";
private const string SchemaApiItemOriginNamesUrlBase = "https://api.steampowered.com/IEconItems_440/GetSchemaOverview/v1/?key=";
/// <summary>
/// Full file name for schema cache file. This value is only used when calling <see cref="FetchSchema"/>. If the time modified of the local copy is later than that of the server, local copy is used without downloading. Default value is %TEMP%\tf_schema.cache.
/// </summary>
public static string CacheFileFullName = Path.GetTempPath() + "\\tf_schema.cache";
/// <summary>
/// Fetches the Tf2 Item schema.
/// </summary>
/// <param name="apiKey">The API key.</param>
/// <returns>A deserialized instance of the Item Schema.</returns>
/// <remarks>
/// The schema will be cached for future use if it is updated.
/// </remarks>
public static Schema FetchSchema(string apiKey, string schemaLang = null)
{
var url = SchemaApiUrlBase + apiKey;
if (schemaLang != null)
url += "&format=json&language=" + schemaLang;
// just let one thread/proc do the initial check/possible update.
bool wasCreated;
var mre = new EventWaitHandle(false,
EventResetMode.ManualReset, SchemaMutexName, out wasCreated);
// the thread that create the wait handle will be the one to
// write the cache file. The others will wait patiently.
if (!wasCreated)
{
bool signaled = mre.WaitOne(10000);
if (!signaled)
{
return null;
}
}
bool keepUpdating = true;
SchemaResult schemaResult = new SchemaResult();
string tmpUrl = url;
do
{
if(schemaResult.result != null)
tmpUrl = url + "&start=" + schemaResult.result.Next;
string result = new SteamWeb().Fetch(tmpUrl, "GET");
if (schemaResult.result == null || schemaResult.result.Items == null)
{
schemaResult = JsonConvert.DeserializeObject<SchemaResult>(result);
}
else
{
SchemaResult tempResult = JsonConvert.DeserializeObject<SchemaResult>(result);
var items = schemaResult.result.Items.Concat(tempResult.result.Items);
schemaResult.result.Items = items.ToArray();
schemaResult.result.Next = tempResult.result.Next;
}
if (schemaResult.result.Next <= schemaResult.result.Items.Count())
keepUpdating = false;
} while (keepUpdating);
//Get origin names
string itemOriginUrl = SchemaApiItemOriginNamesUrlBase + apiKey;
if (schemaLang != null)
itemOriginUrl += "&format=json&language=" + schemaLang;
string resp = new SteamWeb().Fetch(itemOriginUrl, "GET");
var itemOriginResult = JsonConvert.DeserializeObject<SchemaResult>(resp);
schemaResult.result.OriginNames = itemOriginResult.result.OriginNames;
// were done here. let others read.
mre.Set();
DateTime schemaLastModified = DateTime.Now;
return schemaResult.result ?? null;
}
// Gets the schema from the web or from the cached file.
private static string GetSchemaString(HttpWebResponse response, DateTime schemaLastModified)
{
string result;
bool mustUpdateCache = !File.Exists(CacheFileFullName) || schemaLastModified > File.GetCreationTime(CacheFileFullName);
if (mustUpdateCache)
{
using(var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
File.WriteAllText(CacheFileFullName, result);
File.SetCreationTime(CacheFileFullName, schemaLastModified);
}
}
else
{
// read previously cached file.
using(TextReader reader = new StreamReader(CacheFileFullName))
{
result = reader.ReadToEnd();
}
}
return result;
}
[JsonProperty("status")]
public int Status { get; set; }
[JsonProperty("items_game_url")]
public string ItemsGameUrl { get; set; }
[JsonProperty("items")]
public Item[] Items { get; set; }
[JsonProperty("originNames")]
public ItemOrigin[] OriginNames { get; set; }
[JsonProperty("next")]
public int Next { get; set; }
/// <summary>
/// Find an SchemaItem by it's defindex.
/// </summary>
public Item GetItem (int defindex)
{
foreach (Item item in Items)
{
if (item.Defindex == defindex)
return item;
}
return null;
}
/// <summary>
/// Returns all Items of the given crafting material.
/// </summary>
/// <param name="material">Item's craft_material_type JSON property.</param>
/// <seealso cref="Item"/>
public List<Item> GetItemsByCraftingMaterial(string material)
{
return Items.Where(item => item.CraftMaterialType == material).ToList();
}
public List<Item> GetItems()
{
return Items.ToList();
}
public class ItemOrigin
{
[JsonProperty("origin")]
public int Origin { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class Item
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("defindex")]
public ushort Defindex { get; set; }
[JsonProperty("item_class")]
public string ItemClass { get; set; }
[JsonProperty("item_type_name")]
public string ItemTypeName { get; set; }
[JsonProperty("item_name")]
public string ItemName { get; set; }
[JsonProperty("proper_name")]
public bool ProperName { get; set; }
[JsonProperty("craft_material_type")]
public string CraftMaterialType { get; set; }
[JsonProperty("used_by_classes")]
public string[] UsableByClasses { get; set; }
[JsonProperty("item_slot")]
public string ItemSlot { get; set; }
[JsonProperty("craft_class")]
public string CraftClass { get; set; }
[JsonProperty("item_quality")]
public int ItemQuality { get; set; }
}
protected class SchemaResult
{
public Schema result { get; set; }
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ProvidersOperations operations.
/// </summary>
internal partial class ProvidersOperations : IServiceOperations<ResourceManagementClient>, IProvidersOperations
{
/// <summary>
/// Initializes a new instance of the ProvidersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ProvidersOperations(ResourceManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the ResourceManagementClient
/// </summary>
public ResourceManagementClient Client { get; private set; }
/// <summary>
/// Unregisters provider from a subscription.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Provider>> UnregisterWithHttpMessagesAsync(string resourceProviderNamespace, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceProviderNamespace == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceProviderNamespace");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Unregister", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/unregister").ToString();
_url = _url.Replace("{resourceProviderNamespace}", Uri.EscapeDataString(resourceProviderNamespace));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Provider>();
_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 = SafeJsonConvert.DeserializeObject<Provider>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Registers provider to be used with a subscription.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Provider>> RegisterWithHttpMessagesAsync(string resourceProviderNamespace, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceProviderNamespace == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceProviderNamespace");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Register", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register").ToString();
_url = _url.Replace("{resourceProviderNamespace}", Uri.EscapeDataString(resourceProviderNamespace));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Provider>();
_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 = SafeJsonConvert.DeserializeObject<Provider>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of resource providers.
/// </summary>
/// <param name='top'>
/// Query parameters. If null is passed returns all deployments.
/// </param>
/// <param name='expand'>
/// The $expand query parameter. e.g. To include property aliases in response,
/// use $expand=resourceTypes/aliases.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<IPage<Provider>>> ListWithHttpMessagesAsync(int? top = default(int?), string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("top", top);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(top, this.Client.SerializationSettings).Trim('"'))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Provider>>();
_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 = SafeJsonConvert.DeserializeObject<Page<Provider>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a resource provider.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='expand'>
/// The $expand query parameter. e.g. To include property aliases in response,
/// use $expand=resourceTypes/aliases.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Provider>> GetWithHttpMessagesAsync(string resourceProviderNamespace, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceProviderNamespace == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceProviderNamespace");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("expand", expand);
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}").ToString();
_url = _url.Replace("{resourceProviderNamespace}", Uri.EscapeDataString(resourceProviderNamespace));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Provider>();
_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 = SafeJsonConvert.DeserializeObject<Provider>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of resource providers.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<IPage<Provider>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Provider>>();
_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 = SafeJsonConvert.DeserializeObject<Page<Provider>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace PeregrineDb.Tests.Utils
{
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using Npgsql;
using PeregrineDb;
using PeregrineDb.Databases;
using PeregrineDb.Dialects;
using PeregrineDb.Testing;
using PeregrineDb.Tests.Utils.Pooling;
internal class BlankDatabaseFactory
{
private const string DatabasePrefix = "peregrinetests_";
private static readonly ObjectPool<string> SqlServer2012Pool = new ObjectPool<string>(CreateSqlServer2012Database);
private static readonly ObjectPool<string> PostgresPool = new ObjectPool<string>(CreatePostgreSqlDatabase);
private static readonly object Sync = new object();
private static bool cleanedUp;
public static IDatabase MakeDatabase(IDialect dialect)
{
CleanUp();
switch (dialect)
{
case PostgreSqlDialect _:
return OpenBlankDatabase(PostgresPool, cs => new NpgsqlConnection(cs), PeregrineConfig.Postgres);
case SqlServer2012Dialect _:
return OpenBlankDatabase(SqlServer2012Pool, cs => new SqlConnection(cs), PeregrineConfig.SqlServer2012);
default:
throw new NotSupportedException("Unknown dialect: " + dialect.GetType().Name);
}
IDatabase OpenBlankDatabase(
ObjectPool<string> pool,
Func<string, IDbConnection> makeConnection,
PeregrineConfig config)
{
var pooledConnectionString = pool.Acquire();
try
{
IDbConnection dbConnection = null;
try
{
dbConnection = makeConnection(pooledConnectionString.Item);
dbConnection.Open();
IDbConnection pooledConnection = new PooledConnection<IDbConnection>(pooledConnectionString, dbConnection);
var database = new DefaultDatabase(pooledConnection, config);
DataWiper.ClearAllData(database);
return database;
}
catch
{
dbConnection?.Dispose();
throw;
}
}
catch
{
pooledConnectionString?.Dispose();
throw;
}
}
}
private static void CleanUp()
{
lock (Sync)
{
if (cleanedUp)
{
return;
}
using (var con = new SqlConnection(TestSettings.SqlServerConnectionString))
{
con.Open();
using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.SqlServer2012))
{
var databases = database.Query<string>("SELECT name FROM sys.databases")
.Where(s => s.StartsWith(DatabasePrefix));
foreach (var databaseName in databases)
{
if (!ProcessHelpers.IsRunning(GetProcessIdFromDatabaseName(databaseName)))
{
try
{
database.Execute($@"USE master; DROP DATABASE {databaseName};");
}
catch (SqlException)
{
// Ignore errors since multiple processes can try to clean up the same database - only one can win
// Ideally we'd use a mutex but doesnt seem necessary - if we fail to cleanup we'll try again next time (or the other process did for us!)
}
}
}
}
}
using (var con = new NpgsqlConnection(TestSettings.PostgresServerConnectionString))
{
con.Open();
using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.Postgres))
{
var databases = database.Query<string>("SELECT datname FROM pg_database")
.Where(s => s.StartsWith(DatabasePrefix));
foreach (var databaseName in databases)
{
if (!ProcessHelpers.IsRunning(GetProcessIdFromDatabaseName(databaseName)))
{
try
{
database.Execute($@"DROP DATABASE {databaseName};");
}
catch (NpgsqlException)
{
// Ignore errors since multiple processes can try to clean up the same database - only one can win
// Ideally we'd use a mutex but doesnt seem necessary - if we fail to cleanup we'll try again next time (or the other process did for us!)
}
}
}
}
}
cleanedUp = true;
}
}
private static string CreateSqlServer2012Database()
{
var databaseName = MakeRandomDatabaseName();
using (var con = new SqlConnection(TestSettings.SqlServerConnectionString))
{
con.Open();
using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.SqlServer2012))
{
database.Execute("CREATE DATABASE " + databaseName);
}
}
var connectionString = new SqlConnectionStringBuilder(TestSettings.SqlServerConnectionString)
{
InitialCatalog = databaseName,
MultipleActiveResultSets = false
};
var sql = GetSql("CreateSqlServer2012.sql");
using (var con = new SqlConnection(connectionString.ToString()))
{
con.Open();
using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.SqlServer2012))
{
database.Execute("CREATE SCHEMA Other;");
database.Execute(sql);
}
}
return connectionString.ToString();
}
private static string CreatePostgreSqlDatabase()
{
var databaseName = MakeRandomDatabaseName();
using (var con = new NpgsqlConnection(TestSettings.PostgresServerConnectionString))
{
con.Open();
using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.Postgres))
{
database.Execute("CREATE DATABASE " + databaseName);
}
}
var connectionStringBuilder = new NpgsqlConnectionStringBuilder(TestSettings.PostgresServerConnectionString)
{
Database = databaseName
};
var connectionString = connectionStringBuilder.ToString();
using (var con = new NpgsqlConnection(connectionString))
{
con.Open();
using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.Postgres))
{
database.Execute(GetSql("CreatePostgreSql.sql"));
con.ReloadTypes();
}
}
return connectionString;
}
private static string GetSql(string name)
{
string sql;
using (var stream = typeof(BlankDatabaseFactory).GetTypeInfo().Assembly.GetManifestResourceStream("PeregrineDb.Tests.Scripts." + name))
{
using (var reader = new StreamReader(stream))
{
sql = reader.ReadToEnd();
}
}
return sql;
}
private static string MakeRandomDatabaseName()
{
return DatabasePrefix + Guid.NewGuid().ToString("N") + "_" + ProcessHelpers.CurrentProcessId;
}
private static int GetProcessIdFromDatabaseName(string databaseName)
{
return int.Parse(databaseName.Substring(databaseName.LastIndexOf("_", StringComparison.Ordinal) + 1));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using Autofac;
using LibGit2Sharp;
using PassWinmenu.Actions;
using PassWinmenu.Configuration;
using PassWinmenu.ExternalPrograms;
using PassWinmenu.ExternalPrograms.Gpg;
using PassWinmenu.Hotkeys;
using PassWinmenu.PasswordManagement;
using PassWinmenu.UpdateChecking;
using PassWinmenu.WinApi;
using PassWinmenu.Windows;
using YamlDotNet.Core;
using IContainer = Autofac.IContainer;
namespace PassWinmenu
{
internal sealed class Program : IDisposable
{
public static string Version => EmbeddedResources.Version;
public const string LastConfigVersion = "1.7";
public const string EncryptedFileExtension = ".gpg";
public const string PlaintextFileExtension = ".txt";
public const string ConfigFileName = @".\pass-winmenu.yaml";
private ActionDispatcher actionDispatcher;
private HotkeyManager hotkeys;
private UpdateChecker updateChecker;
private Notifications notificationService;
private IContainer container;
public Program()
{
try
{
Initialise();
RunInitialCheck();
}
catch (Exception e)
{
Log.EnableFileLogging();
Log.Send("Could not start pass-winmenu: An exception occurred.", LogLevel.Error);
Log.ReportException(e);
string errorMessage = $"pass-winmenu failed to start ({e.GetType().Name}: {e.Message})";
if (notificationService == null)
{
// We have no notification service yet. Instantiating one is risky,
// so we'll make do with a call to MessageBox.Show() instead.
MessageBox.Show(errorMessage, "An error occurred.", MessageBoxButton.OK, MessageBoxImage.Error);
}
else
{
notificationService.ShowErrorWindow(errorMessage);
}
Exit();
}
}
/// <summary>
/// Loads all required resources.
/// </summary>
private void Initialise()
{
// Load compiled-in resources.
EmbeddedResources.Load();
Log.Send("------------------------------");
Log.Send($"Starting pass-winmenu {Version}");
Log.Send("------------------------------");
// Set the security protocol to TLS 1.2 only.
// We only use this for update checking (Git push over HTTPS is not handled by .NET).
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Create the notification service first, so it's available if initialisation fails.
notificationService = Notifications.Create();
// Initialise the DI Container builder.
var builder = new ContainerBuilder();
builder.Register(_ => notificationService)
.AsImplementedInterfaces()
.SingleInstance();
// Now load the configuration options that we'll need
// to continue initialising the rest of the applications.
LoadConfigFile();
builder.Register(_ => ConfigManager.Config).AsSelf();
builder.Register(_ => ConfigManager.Config.Gpg).AsSelf();
builder.Register(_ => ConfigManager.Config.Git).AsSelf();
builder.Register(_ => ConfigManager.Config.PasswordStore).AsSelf();
builder.Register(_ => ConfigManager.Config.Application.UpdateChecking).AsSelf();
#if DEBUG
Log.EnableFileLogging();
#else
if (ConfigManager.Config.CreateLogFile)
{
Log.EnableFileLogging();
}
#endif
// Register actions
builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(ActionDispatcher)))
.InNamespaceOf<ActionDispatcher>()
.Except<ActionDispatcher>()
.AsImplementedInterfaces();
builder.RegisterType<ActionDispatcher>()
.WithParameter(
(p, ctx) => p.ParameterType == typeof(Dictionary<HotkeyAction, IAction>),
(info, context) => context.Resolve<IEnumerable<IAction>>().ToDictionary(a => a.ActionType));
// Register environment wrappers
builder.RegisterTypes(
typeof(FileSystem),
typeof(SystemEnvironment),
typeof(Processes),
typeof(ExecutablePathResolver)
).AsImplementedInterfaces();
// Register GPG types
builder.RegisterTypes(
typeof(GpgInstallationFinder),
typeof(GpgHomedirResolver),
typeof(GpgAgentConfigReader),
typeof(GpgAgentConfigUpdater),
typeof(GpgTransport),
typeof(GpgAgent),
typeof(GpgResultVerifier)
).AsImplementedInterfaces()
.AsSelf();
// Register GPG installation
builder.Register(context => context.Resolve<GpgInstallationFinder>().FindGpgInstallation(ConfigManager.Config.Gpg.GpgPath));
// Register GPG
builder.Register(context => new GPG(
context.Resolve<IGpgTransport>(),
context.Resolve<IGpgAgent>(),
context.Resolve<IGpgResultVerifier>(),
context.Resolve<GpgConfig>().PinentryFix))
.AsImplementedInterfaces()
.AsSelf();
builder.RegisterType<DialogCreator>()
.AsSelf();
// Register the internal password manager
builder.Register(context => context.Resolve<IFileSystem>().DirectoryInfo.FromDirectoryName(context.Resolve<PasswordStoreConfig>().Location))
.Named("PasswordStore", typeof(IDirectoryInfo));
builder.RegisterType<GpgRecipientFinder>().WithParameter(
(parameter, context) => true,
(parameter, context) => context.ResolveNamed<IDirectoryInfo>("PasswordStore"))
.AsImplementedInterfaces();
builder.RegisterType<PasswordManager>().WithParameter(
(parameter, context) => parameter.ParameterType == typeof(IDirectoryInfo),
(parameter, context) => context.ResolveNamed<IDirectoryInfo>("PasswordStore"))
.AsImplementedInterfaces()
.AsSelf();
// Create the Git wrapper, if enabled.
builder.Register(RegisterSyncService)
.AsImplementedInterfaces();
builder.Register(context => UpdateCheckerFactory.CreateUpdateChecker(context.Resolve<UpdateCheckingConfig>(), context.Resolve<INotificationService>()));
// Build the container
container = builder.Build();
var gpgConfig = container.Resolve<GpgConfig>();
if (gpgConfig.GpgAgent.Config.AllowConfigManagement)
{
container.Resolve<GpgAgentConfigUpdater>().UpdateAgentConfig(gpgConfig.GpgAgent.Config.Keys);
}
actionDispatcher = container.Resolve<ActionDispatcher>();
notificationService.AddMenuActions(actionDispatcher);
// Assign our hotkeys.
hotkeys = new HotkeyManager();
AssignHotkeys(hotkeys);
}
private static ISyncService RegisterSyncService (IComponentContext context)
{
var config = context.Resolve<GitConfig>();
var passwordStore = context.ResolveNamed<IDirectoryInfo>("PasswordStore");
var notificationService = context.Resolve<INotificationService>();
if (config.UseGit)
{
try
{
return new SyncServiceFactory().BuildSyncService(config, passwordStore.FullName);
}
catch (RepositoryNotFoundException)
{
// Password store doesn't appear to be a Git repository.
// Git support will be disabled.
}
catch (TypeInitializationException e) when (e.InnerException is DllNotFoundException)
{
notificationService.ShowErrorWindow("The git2 DLL could not be found. Git support will be disabled.");
}
catch (Exception e)
{
notificationService.ShowErrorWindow($"Failed to open the password store Git repository ({e.GetType().Name}: {e.Message}). Git support will be disabled.");
}
}
return null;
}
/// <summary>
/// Checks if all components are configured correctly.
/// </summary>
private void RunInitialCheck()
{
var gpg = container.Resolve<GPG>();
if (!Directory.Exists(ConfigManager.Config.PasswordStore.Location))
{
notificationService.ShowErrorWindow($"Could not find the password store at {Path.GetFullPath(ConfigManager.Config.PasswordStore.Location)}. Please make sure it exists.");
Exit();
return;
}
try
{
Log.Send("Using GPG version " + gpg.GetVersion());
}
catch (System.ComponentModel.Win32Exception)
{
notificationService.ShowErrorWindow("Could not find GPG. Make sure your gpg-path is set correctly.");
Exit();
return;
}
catch (Exception e)
{
notificationService.ShowErrorWindow($"Failed to initialise GPG. {e.GetType().Name}: {e.Message}");
Exit();
return;
}
if (ConfigManager.Config.Gpg.GpgAgent.Preload)
{
Task.Run(() =>
{
try
{
gpg.StartAgent();
}
catch (GpgError err)
{
notificationService.ShowErrorWindow(err.Message);
}
// Ignore other exceptions. If it turns out GPG is misconfigured,
// these errors will surface upon decryption/encryption.
// The reason we catch GpgErrors here is so we can notify the user
// if we don't detect any decryption keys.
});
}
}
private void LoadConfigFile()
{
LoadResult result;
try
{
result = ConfigManager.Load(ConfigFileName);
}
catch (Exception e) when (e.InnerException != null)
{
if (e is YamlException)
{
notificationService.ShowErrorWindow(
$"The configuration file could not be loaded: {e.Message}\n\n{e.InnerException.GetType().Name}: {e.InnerException.Message}",
"Unable to load configuration file.");
}
else
{
notificationService.ShowErrorWindow(
$"The configuration file could not be loaded. An unhandled exception occurred.\n{e.InnerException.GetType().Name}: {e.InnerException.Message}",
"Unable to load configuration file.");
}
Exit();
return;
}
catch (SemanticErrorException e)
{
notificationService.ShowErrorWindow(
$"The configuration file could not be loaded. An unhandled exception occurred.\n{e.GetType().Name}: {e.Message}",
"Unable to load configuration file.");
Exit();
return;
}
catch (YamlException e)
{
notificationService.ShowErrorWindow(
$"The configuration file could not be loaded. An unhandled exception occurred.\n{e.GetType().Name}: {e.Message}",
"Unable to load configuration file.");
Exit();
return;
}
switch (result)
{
case LoadResult.FileCreationFailure:
notificationService.Raise("A default configuration file was generated, but could not be saved.\nPass-winmenu will fall back to its default settings.", Severity.Error);
break;
case LoadResult.NewFileCreated:
var open = MessageBox.Show("A new configuration file has been generated. Please modify it according to your preferences and restart the application.\n\n" +
"Would you like to open it now?", "New configuration file created", MessageBoxButton.YesNo);
if (open == MessageBoxResult.Yes) Process.Start(ConfigFileName);
Exit();
return;
case LoadResult.NeedsUpgrade:
var backedUpFile = ConfigManager.Backup(ConfigFileName);
var openBoth = MessageBox.Show("The current configuration file is out of date. A new configuration file has been created, and the old file has been backed up.\n" +
"Please edit the new configuration file according to your preferences and restart the application.\n\n" +
"Would you like to open both files now?", "Configuration file out of date", MessageBoxButton.YesNo);
if (openBoth == MessageBoxResult.Yes)
{
Process.Start(ConfigFileName);
Process.Start(backedUpFile);
}
Exit();
return;
}
if (ConfigManager.Config.Application.ReloadConfig)
{
ConfigManager.EnableAutoReloading(ConfigFileName);
Log.Send("Config reloading enabled");
}
}
/// <summary>
/// Loads keybindings from the configuration file and registers them with Windows.
/// </summary>
private void AssignHotkeys(HotkeyManager hotkeyManager)
{
try
{
hotkeyManager.AssignHotkeys(
ConfigManager.Config.Hotkeys ?? new HotkeyConfig[0],
actionDispatcher,
notificationService);
}
catch (Exception e) when (e is ArgumentException || e is HotkeyException)
{
Log.Send("Failed to register hotkeys", LogLevel.Error);
Log.ReportException(e);
notificationService.ShowErrorWindow(e.Message, "Could not register hotkeys");
Exit();
}
}
public static void Exit()
{
Log.Send("Shutting down.");
Environment.Exit(0);
}
public void Dispose()
{
notificationService?.Dispose();
hotkeys?.Dispose();
updateChecker?.Dispose();
}
}
}
| |
using Microsoft.Build.Framework;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Threading;
namespace Microsoft.DotNet.Build.Tasks
{
public class CleanupVSTSAgent : Microsoft.Build.Utilities.Task
{
public bool Clean { get; set; }
public bool Report { get; set; }
[Required]
public string AgentDirectory { get; set; }
[Required]
public double RetentionDays { get; set; }
public int? Retries { get; set; }
public int MaximumWorkspacesToClean { get; set; } = 8;
public bool EnableLongPathRemoval { get; set; } = true;
public int? SleepTimeInMilliseconds { get; set; }
public ITaskItem[] ProcessNamesToKill { get; set; }
public string [] AdditionalCleanupDirectories { get; set; }
private static readonly int s_DefaultRetries = 3;
private static readonly int s_DefaultSleepTime = 2000;
private DateTime _timerStarted;
private HashSet<string> _protectedDirectories = new HashSet<string>();
private HashSet<string> _additionalCleanupDirectories = new HashSet<string>();
private Dictionary<string, bool> _availableUnixCommands = new Dictionary<string, bool>();
public override bool Execute()
{
string entryLocation = System.Reflection.Assembly.GetEntryAssembly().Location;
if(!string.IsNullOrEmpty(entryLocation))
{
_protectedDirectories.Add(entryLocation);
}
string currentDirectory = Directory.GetCurrentDirectory();
if (!string.IsNullOrEmpty(currentDirectory))
{
_protectedDirectories.Add(currentDirectory);
}
KillStaleProcesses();
if (!Directory.Exists(AgentDirectory))
{
Log.LogMessage($"Agent directory specified: '{AgentDirectory}' does not exist.");
return false;
}
if (!Retries.HasValue)
{
Retries = s_DefaultRetries;
}
if (!SleepTimeInMilliseconds.HasValue)
{
SleepTimeInMilliseconds = s_DefaultSleepTime;
}
bool returnValue = true;
_timerStarted = DateTime.Now;
GenerateAdditionalCleanupDirectories();
if (Report)
{
ReportDiskUsage();
}
if (Clean)
{
returnValue = CleanupDirsAsync().Result;
// If report and clean are both 'true', then report disk usage both before and after cleanup.
if (Report)
{
Log.LogMessage("Disk usage after 'Clean'.");
ReportDiskUsage();
}
}
return returnValue;
}
private void GenerateAdditionalCleanupDirectories()
{
if (AdditionalCleanupDirectories != null)
{
_additionalCleanupDirectories = new HashSet<string>(AdditionalCleanupDirectories);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_additionalCleanupDirectories.Add(Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), "NuGet"));
_additionalCleanupDirectories.Add(Path.Combine(Environment.GetEnvironmentVariable("UserProfile"), ".nuget\\packages"));
_additionalCleanupDirectories.Add(Environment.GetEnvironmentVariable("TEMP"));
_additionalCleanupDirectories.Add(Environment.GetEnvironmentVariable("TMP"));
}
else
{
_additionalCleanupDirectories.Add(Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".local/share/NuGet"));
_additionalCleanupDirectories.Add(Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".nuget"));
_additionalCleanupDirectories.Add(Environment.GetEnvironmentVariable("TMPDIR"));
_additionalCleanupDirectories.Add(Environment.GetEnvironmentVariable("TMP"));
_additionalCleanupDirectories.Add(Path.Combine(Environment.GetEnvironmentVariable("HOME"), "myagent/_work/_temp"));
}
_additionalCleanupDirectories.RemoveWhere(f => string.IsNullOrWhiteSpace(f));
_additionalCleanupDirectories.RemoveWhere(f => !Directory.Exists(f));
foreach(string additionalCleanupDirectory in _additionalCleanupDirectories)
{
Log.LogMessage($"Found additional cleanup directory {additionalCleanupDirectory}");
}
}
private void KillStaleProcesses()
{
foreach (string imageName in ProcessNamesToKill.Select(t => t.ItemSpec))
{
Process[] allInstances = Process.GetProcessesByName(imageName);
foreach (Process proc in allInstances)
{
try
{
if (!proc.HasExited)
{
proc.Kill();
Log.LogMessage($"Killed process {imageName} ({proc.Id})");
}
}
catch (Exception e)
{
Log.LogMessage($"Hit {e.GetType().ToString()} trying to kill process {imageName} ({proc.Id})");
}
}
}
}
private void ReportDiskUsage()
{
string lastDirectoryChecked = AgentDirectory;
try
{
// Report disk usage for agent directory
ReportCommonDiskUsage("Agent", AgentDirectory);
foreach (string additionalCleanupDirectory in _additionalCleanupDirectories)
{
ReportCommonDiskUsage("Cleanup", additionalCleanupDirectory);
}
}
catch (PathTooLongException)
{
Log.LogWarning("Hit PathTooLongException attempting to list info about agent directory. Ensure you are running the framework version of this task and 'EnableLongPathRemoval' is 'true'..");
if (!string.IsNullOrEmpty(lastDirectoryChecked))
{
Log.LogWarning($"Last directory checked : {lastDirectoryChecked} (likely the first inaccessible directory, alphabetically) ");
}
}
catch (UnauthorizedAccessException)
{
Log.LogWarning("Hit UnauthorizedAccessException attempting to list info about agent directory. There are likely files which cannot be cleaned up on the agent.");
if (!string.IsNullOrEmpty(lastDirectoryChecked))
{
Log.LogWarning($"Last directory checked : {lastDirectoryChecked} (likely the first inaccessible directory, alphabetically) ");
}
}
}
private DriveInfo ReportCommonDiskUsage(string dirType, string directory)
{
try
{
if (String.IsNullOrEmpty(directory))
{
Log.LogMessage($"Disk usage report for {dirType} directory is not available, because the directory does NOT exist.");
return null;
}
if (!Directory.Exists(directory))
{
Log.LogMessage($"Disk usage report for {dirType} directory is not available, because the directory {directory} does NOT exist.");
return null;
}
string drive = Path.GetPathRoot(directory);
if (String.IsNullOrEmpty(drive))
{
Log.LogMessage($"Can't parse the drive correctly from directory {directory} because it's null or empty.");
return null;
}
DriveInfo driveInfo = new DriveInfo(drive);
Log.LogMessage($"Disk usage report for {dirType} directory");
Log.LogMessage($" {dirType} directory: {directory}");
Log.LogMessage($" Drive letter: {drive}");
Log.LogMessage($" Total disk size: {string.Format("{0:N0}", driveInfo.TotalSize)} bytes");
Log.LogMessage($" Total disk free space: {string.Format("{0:N0}", driveInfo.TotalFreeSpace)} bytes");
Log.LogMessage($" {dirType} directory info");
Log.LogMessage($" Total size of {dirType} directory: {string.Format("{0:N0}", GetDirectoryAttributes(directory).Item1)} bytes");
return driveInfo;
}
catch (PathTooLongException)
{
Log.LogWarning($"Hit PathTooLongException attempting to list info about directory {directory}. Ensure you are running the framework version of this task and 'EnableLongPathRemoval' is 'true'.");
return null;
}
catch (UnauthorizedAccessException)
{
Log.LogWarning($"Hit UnauthorizedAccessException attempting to list info about directory {directory}. There are likely files which cannot be cleaned up on the agent.");
return null;
}
}
private Tuple<long, DateTime> GetDirectoryAttributes(string directory)
{
DirectoryInfo directoryInfo = new DirectoryInfo(directory);
FileInfo[] fileInfos = directoryInfo.GetFiles();
long totalSize = 0;
DateTime lastModifiedDateTime = directoryInfo.LastWriteTime;
foreach (FileInfo fileInfo in fileInfos)
{
totalSize += fileInfo.Length;
lastModifiedDateTime = fileInfo.LastWriteTime > lastModifiedDateTime ? fileInfo.LastWriteTime : lastModifiedDateTime;
}
string[] directories = Directory.GetDirectories(directory);
foreach (string dir in directories)
{
Tuple<long, DateTime> directoryAttributes = GetDirectoryAttributes(dir);
totalSize += directoryAttributes.Item1;
lastModifiedDateTime = directoryAttributes.Item2 > lastModifiedDateTime ? directoryAttributes.Item2 : lastModifiedDateTime;
}
return Tuple.Create(totalSize, lastModifiedDateTime);
}
private async System.Threading.Tasks.Task<bool> CleanupDirsAsync()
{
bool returnStatus = true;
DateTime now = DateTime.Now;
int cleanupTaskCount = 0;
List<System.Threading.Tasks.Task<bool>> cleanupTasks = new List<System.Threading.Tasks.Task<bool>>();
// Cleanup the agents that the VSTS agent is tracking
if (Directory.Exists(AgentDirectory))
{
GiveFullPermissionsIfUnixFolder(AgentDirectory);
string[] sourceFolderJsons = Directory.GetFiles(AgentDirectory, "SourceFolder.json", SearchOption.AllDirectories);
HashSet<string> knownDirectories = new HashSet<string>();
Log.LogMessage($"Found {sourceFolderJsons.Length} known agent working directories. (Will clean up to {MaximumWorkspacesToClean} of them)");
string workDirectoryRoot = Directory.GetDirectories(AgentDirectory, "_work", SearchOption.AllDirectories).FirstOrDefault();
foreach (var sourceFolderJson in sourceFolderJsons)
{
Log.LogMessage($"Examining {sourceFolderJson} ...");
Tuple<string, string, DateTime> agentInfo = await GetAgentInfoAsync(sourceFolderJson);
string workDirectory = Path.Combine(workDirectoryRoot, agentInfo.Item2);
knownDirectories.Add(workDirectory);
TimeSpan span = new TimeSpan(now.Ticks - agentInfo.Item3.Ticks);
if (cleanupTaskCount < MaximumWorkspacesToClean)
{
if (span.TotalDays > RetentionDays)
{
cleanupTasks.Add(CleanupAgentAsync(workDirectory, Path.GetDirectoryName(agentInfo.Item1)));
cleanupTaskCount++;
}
else
{
Log.LogMessage($"Skipping cleanup for {sourceFolderJson}, it is newer than {RetentionDays} days old, last run date is '{agentInfo.Item3.ToString()}'");
}
}
else
{
// We've taken enough cleanup tasks per the value of MaximumWorkspaces
break;
}
}
System.Threading.Tasks.Task.WaitAll(cleanupTasks.ToArray());
foreach (var cleanupTask in cleanupTasks)
{
returnStatus &= cleanupTask.Result;
}
// Attempt to cleanup any working folders which the VSTS agent doesn't know about.
Log.LogMessage("Looking for additional '_work' directories which are unknown to the agent.");
cleanupTasks.Clear();
if (cleanupTaskCount < MaximumWorkspacesToClean)
{
Regex workingDirectoryRegex = new Regex(@"[/\\]\d+$");
var workingDirectories = Directory.GetDirectories(workDirectoryRoot, "*", SearchOption.TopDirectoryOnly).Where(w => workingDirectoryRegex.IsMatch(w));
foreach (var workingDirectory in workingDirectories)
{
if (cleanupTaskCount >= MaximumWorkspacesToClean)
{
break;
}
if (!knownDirectories.Contains(workingDirectory))
{
cleanupTasks.Add(CleanupDirectoryAsync(workingDirectory));
cleanupTaskCount++;
}
}
}
System.Threading.Tasks.Task.WaitAll(cleanupTasks.ToArray());
foreach (var cleanupTask in cleanupTasks)
{
returnStatus &= cleanupTask.Result;
}
}
else
{
Log.LogMessage($"Agent directory not found at '{AgentDirectory}', skipping agent cleanup.");
}
cleanupTasks.Clear();
foreach (string additionalCleanupDirectory in _additionalCleanupDirectories)
{
cleanupTasks.Add(CleanupDirectoryAsync(additionalCleanupDirectory, 0, true));
}
System.Threading.Tasks.Task.WaitAll(cleanupTasks.ToArray());
return returnStatus;
}
private async System.Threading.Tasks.Task<bool> CleanupAgentAsync(string workDirectory, string sourceFolderJson)
{
bool returnStatus = await CleanupDirectoryAsync(workDirectory);
returnStatus &= await CleanupDirectoryAsync(sourceFolderJson).ConfigureAwait(false);
return returnStatus;
}
private async System.Threading.Tasks.Task<bool> CleanupDirectoryAsync(string directory, int attempts = 0, bool ignoreExceptions = false)
{
try
{
if (string.IsNullOrWhiteSpace(directory))
{
return true;
}
// A protected directory is, for instance, the directory which is currently running the cleanup task.
// The cleanup task should never try to clean itself up
foreach (string protectedDirectory in _protectedDirectories)
{
if (protectedDirectory.Contains(directory) || directory.Contains(protectedDirectory))
{
Console.WriteLine($"Specified cleanup directory ('{directory}') is a protected directory ('{protectedDirectory}'), skipping.");
return true;
}
}
if (!Directory.Exists(directory))
{
Log.LogMessage($"Specified directory, {directory}, does not exist");
}
else
{
GiveFullPermissionsIfUnixFolder(directory);
Log.LogMessage($"Attempting to cleanup {directory} ... ");
#if net45
// Unlike OSX and Linux, Windows has a hard limit of 260 chars on paths.
// Some build definitions leave paths this long behind. It's unusual,
// but robocopy has been on Windows by default since XP and understands
// how to stomp on long paths, so we'll use it to clean directories on Windows first.
if (EnableLongPathRemoval && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
RemoveDirectoryRecursiveLongPath(directory);
}
else
{
#endif
Directory.Delete(directory, true);
#if net45
}
#endif
Log.LogMessage("Success");
}
return true;
}
catch (Exception e)
{
if (ignoreExceptions)
{
Log.LogMessage($"Failed in cleanup attempt of '{directory}', but directory is non-blocking, ignoring failure.");
Log.LogMessage($"{e.GetType().ToString()} - {e.Message}");
return true;
}
else
{
attempts++;
Log.LogMessage($"Failed in cleanup attempt... {Retries - attempts} retries left.");
Log.LogMessage($"{e.GetType().ToString()} - {e.Message}");
Log.LogMessage(e.StackTrace);
if (attempts < Retries)
{
Log.LogMessage($"Will retry again in {SleepTimeInMilliseconds} ms");
await System.Threading.Tasks.Task.Delay(SleepTimeInMilliseconds.Value);
return await CleanupDirectoryAsync(directory, attempts).ConfigureAwait(false);
}
}
}
Log.LogMessage("Failed to cleanup.");
return false;
}
private void GiveFullPermissionsIfUnixFolder(string directory)
{
// Change file permissions on directory we're attempting to delete so we don't hit "Permission denied"
if (IsUnixCommandAvailable("sudo") &&
IsUnixCommandAvailable("chmod"))
{
string chmodPermissions = "777";
Log.LogMessage($"Changing file permissions to '{chmodPermissions}' for directory '{directory}'");
int maximumChmodTimeInMinutes = 3;
int maxTimeMilliseconds = (int)((TimeSpan.FromMinutes(maximumChmodTimeInMinutes) - (DateTime.Now - _timerStarted)).TotalMilliseconds - 1000);
Process chmodProcess = Process.Start(new ProcessStartInfo("sudo", $"chmod {chmodPermissions} -R {directory}"));
chmodProcess.WaitForExit(maxTimeMilliseconds);
chmodProcess.Refresh();
if (!chmodProcess.HasExited)
{
Log.LogWarning($"Chmod process (PID: {chmodProcess.Id} did not exit in maximum allotted time ({maximumChmodTimeInMinutes} mins), will try to kill");
chmodProcess.Kill();
}
}
}
// Keep a dictionary of Unix commands which we check for availability so that we have quick access to
// determine if the command has already been checked and if it is available.
private bool IsUnixCommandAvailable(string command)
{
if(_availableUnixCommands.ContainsKey(command))
{
return _availableUnixCommands[command];
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_availableUnixCommands.Add(command, false);
}
else
{
Process commandProcess = Process.Start(new ProcessStartInfo("which", command));
commandProcess.WaitForExit();
_availableUnixCommands.Add(command, commandProcess.ExitCode == 0);
}
return _availableUnixCommands[command];
}
private async System.Threading.Tasks.Task<Tuple<string, string, DateTime>> GetAgentInfoAsync(string sourceFolderJson)
{
Regex getValueRegex = new Regex(".*\": \"(?<value>[^\"]+)\"");
DateTime lastRunOn = DateTime.Now;
string agentBuildDirectory = null;
using (Stream stream = File.OpenRead(sourceFolderJson))
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
string line = await reader.ReadLineAsync();
if (line.Contains("lastRunOn"))
{
lastRunOn = DateTime.Parse(getValueRegex.Match(line).Groups["value"].Value.ToString());
}
else if (line.Contains("agent_builddirectory"))
{
agentBuildDirectory = getValueRegex.Match(line).Groups["value"].Value.ToString();
}
}
}
return new Tuple<string, string, DateTime>(sourceFolderJson, agentBuildDirectory, lastRunOn);
}
#if net45
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DeleteFileW([MarshalAs(UnmanagedType.LPWStr)]string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool RemoveDirectory(string lpFileName);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern bool FindClose(IntPtr hFindFile);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool SetFileAttributesW(string lpFileName, FileAttributes dwFileAttributes);
// The CharSet must match the CharSet of the corresponding PInvoke signature
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WIN32_FIND_DATA
{
public uint dwFileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
// Many Windows API's will use the unicode syntax when the path is prepended with '\\?\', this
// is instead of the ANSI paths which have a 260 character max path limit
private string MakeLongPath(string path)
{
if (path == null ||
path.Length == 0)
{
return path;
}
if (!path.StartsWith(@"\\?\"))
{
path = @"\\?\" + path;
}
return path;
}
private bool RemoveDirectoryRecursiveLongPath(string directory)
{
string[] directories = GetDirectoriesLongPath(directory);
// Windows DeleteFile API will only delete a directory if it is empty,
// so recurse down to the leaf directory
foreach (string dir in directories)
{
RemoveDirectoryRecursiveLongPath(dir);
}
string[] files = GetFilesLongPath(directory);
foreach (string file in files)
{
// Clear read-only attribute
SetFileAttributesW(file, FileAttributes.Normal);
bool deleted = DeleteFileW(MakeLongPath(file));
if (!deleted)
{
ThrowIfWindowsErrorCode($"Failed to delete file '{file}'");
}
}
directories = GetDirectoriesLongPath(directory);
foreach (string dir in directories)
{
RemoveDirectoryLongPath(MakeLongPath(dir));
}
RemoveDirectoryLongPath(directory);
return true;
}
private string[] GetDirectoriesLongPath(string directory)
{
return GetFilesByAttributes(directory, FileAttributes.Directory);
}
private string[] GetFilesLongPath(string directory)
{
return GetFilesByAttributes(directory, FileAttributes.Normal | FileAttributes.Archive | FileAttributes.NotContentIndexed);
}
// Given a directory, return an array of files in that directory with the specified attributes. Supports long paths.
private string[] GetFilesByAttributes(string directory, FileAttributes attributes)
{
directory = MakeLongPath(directory);
List<string> files = new List<string>();
WIN32_FIND_DATA findData;
IntPtr hFile = FindFirstFile(directory + "\\*", out findData);
int error = Marshal.GetLastWin32Error();
if (hFile.ToInt32() != -1)
{
do
{
string file = findData.cFileName;
if ((findData.dwFileAttributes & (int)attributes) != 0)
{
if (file != "." && file != "..")
{
files.Add(Path.Combine(directory, file));
}
}
}
while (FindNextFile(hFile, out findData));
FindClose(hFile);
}
return files.ToArray();
}
private void RemoveDirectoryLongPath(string directory)
{
bool deleted = RemoveDirectory(MakeLongPath(directory));
if (!deleted)
{
ThrowIfWindowsErrorCode($"Failed to remove directory '{directory}'");
}
}
private void ThrowIfWindowsErrorCode(string message)
{
int lastError = Marshal.GetLastWin32Error();
if(lastError != 0)
{
// Not trying to translate all of the error codes possibilities into readable text, just report the code
throw new Exception($"{message}: error={lastError}, error code values are described at https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx");
}
}
#endif
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Reactive;
using System.Reactive.Linq;
using Avalonia.Data;
using Avalonia.Interactivity;
namespace Avalonia.Controls.Primitives
{
/// <summary>
/// A scrollbar control.
/// </summary>
public class ScrollBar : RangeBase
{
/// <summary>
/// Defines the <see cref="ViewportSize"/> property.
/// </summary>
public static readonly StyledProperty<double> ViewportSizeProperty =
AvaloniaProperty.Register<ScrollBar, double>(nameof(ViewportSize), defaultValue: double.NaN);
/// <summary>
/// Defines the <see cref="Visibility"/> property.
/// </summary>
public static readonly StyledProperty<ScrollBarVisibility> VisibilityProperty =
AvaloniaProperty.Register<ScrollBar, ScrollBarVisibility>(nameof(Visibility));
/// <summary>
/// Defines the <see cref="Orientation"/> property.
/// </summary>
public static readonly StyledProperty<Orientation> OrientationProperty =
AvaloniaProperty.Register<ScrollBar, Orientation>(nameof(Orientation), Orientation.Vertical);
private Button _lineUpButton;
private Button _lineDownButton;
private Button _pageUpButton;
private Button _pageDownButton;
/// <summary>
/// Initializes static members of the <see cref="ScrollBar"/> class.
/// </summary>
static ScrollBar()
{
PseudoClass(OrientationProperty, o => o == Orientation.Vertical, ":vertical");
PseudoClass(OrientationProperty, o => o == Orientation.Horizontal, ":horizontal");
}
/// <summary>
/// Initializes a new instance of the <see cref="ScrollBar"/> class.
/// </summary>
public ScrollBar()
{
var isVisible = Observable.Merge(
this.GetObservable(MinimumProperty).Select(_ => Unit.Default),
this.GetObservable(MaximumProperty).Select(_ => Unit.Default),
this.GetObservable(ViewportSizeProperty).Select(_ => Unit.Default),
this.GetObservable(VisibilityProperty).Select(_ => Unit.Default))
.Select(_ => CalculateIsVisible());
Bind(IsVisibleProperty, isVisible, BindingPriority.Style);
}
/// <summary>
/// Gets or sets the amount of the scrollable content that is currently visible.
/// </summary>
public double ViewportSize
{
get { return GetValue(ViewportSizeProperty); }
set { SetValue(ViewportSizeProperty, value); }
}
/// <summary>
/// Gets or sets a value that indicates whether the scrollbar should hide itself when it
/// is not needed.
/// </summary>
public ScrollBarVisibility Visibility
{
get { return GetValue(VisibilityProperty); }
set { SetValue(VisibilityProperty, value); }
}
/// <summary>
/// Gets or sets the orientation of the scrollbar.
/// </summary>
public Orientation Orientation
{
get { return GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
/// <summary>
/// Calculates whether the scrollbar should be visible.
/// </summary>
/// <returns>The scrollbar's visibility.</returns>
private bool CalculateIsVisible()
{
switch (Visibility)
{
case ScrollBarVisibility.Visible:
return true;
case ScrollBarVisibility.Disabled:
case ScrollBarVisibility.Hidden:
return false;
case ScrollBarVisibility.Auto:
return double.IsNaN(ViewportSize) || Maximum > 0;
default:
throw new InvalidOperationException("Invalid value for ScrollBar.Visibility.");
}
}
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
base.OnTemplateApplied(e);
if (_lineUpButton != null)
{
_lineUpButton.Click -= LineUpClick;
}
if (_lineDownButton != null)
{
_lineDownButton.Click -= LineDownClick;
}
if (_pageUpButton != null)
{
_pageUpButton.Click -= PageUpClick;
}
if (_pageDownButton != null)
{
_pageDownButton.Click -= PageDownClick;
}
_lineUpButton = e.NameScope.Find<Button>("PART_LineUpButton");
_lineDownButton = e.NameScope.Find<Button>("PART_LineDownButton");
_pageUpButton = e.NameScope.Find<Button>("PART_PageUpButton");
_pageDownButton = e.NameScope.Find<Button>("PART_PageDownButton");
if (_lineUpButton != null)
{
_lineUpButton.Click += LineUpClick;
}
if (_lineDownButton != null)
{
_lineDownButton.Click += LineDownClick;
}
if (_pageUpButton != null)
{
_pageUpButton.Click += PageUpClick;
}
if (_pageDownButton != null)
{
_pageDownButton.Click += PageDownClick;
}
}
private void LineUpClick(object sender, RoutedEventArgs e)
{
SmallDecrement();
}
private void LineDownClick(object sender, RoutedEventArgs e)
{
SmallIncrement();
}
private void PageUpClick(object sender, RoutedEventArgs e)
{
LargeDecrement();
}
private void PageDownClick(object sender, RoutedEventArgs e)
{
LargeIncrement();
}
private void SmallDecrement()
{
Value = Math.Max(Value - SmallChange * ViewportSize, Minimum);
}
private void SmallIncrement()
{
Value = Math.Min(Value + SmallChange * ViewportSize, Maximum);
}
private void LargeDecrement()
{
Value = Math.Max(Value - LargeChange * ViewportSize, Minimum);
}
private void LargeIncrement()
{
Value = Math.Min(Value + LargeChange * ViewportSize, Maximum);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Profiling;
using Object = UnityEngine.Object;
namespace UnityEditor.VFX
{
public enum VFXDeviceTarget
{
CPU,
GPU,
}
class VFXExpressionGraph
{
private struct ExpressionData
{
public int depth;
public int index;
}
public VFXExpressionGraph()
{}
private void AddExpressionDataRecursively(Dictionary<VFXExpression, ExpressionData> dst, VFXExpression exp, int depth = 0)
{
ExpressionData data;
if (!dst.TryGetValue(exp, out data) || data.depth < depth)
{
data.index = -1; // Will be overridden later on
data.depth = depth;
dst[exp] = data;
foreach (var parent in exp.parents)
AddExpressionDataRecursively(dst, parent, depth + 1);
}
}
private void CompileExpressionContext(IEnumerable<VFXContext> contexts, VFXExpressionContextOption options, VFXDeviceTarget target)
{
HashSet<VFXExpression> expressions = new HashSet<VFXExpression>();
var expressionContext = new VFXExpression.Context(options);
var contextsToExpressions = target == VFXDeviceTarget.GPU ? m_ContextsToGPUExpressions : m_ContextsToCPUExpressions;
var expressionsToReduced = target == VFXDeviceTarget.GPU ? m_GPUExpressionsToReduced : m_CPUExpressionsToReduced;
contextsToExpressions.Clear();
expressionsToReduced.Clear();
foreach (var context in contexts)
{
var mapper = context.GetExpressionMapper(target);
if (mapper != null)
{
foreach (var exp in mapper.expressions)
expressionContext.RegisterExpression(exp);
expressions.UnionWith(mapper.expressions);
contextsToExpressions.Add(context, mapper);
}
}
expressionContext.Compile();
foreach (var exp in expressionContext.RegisteredExpressions)
expressionsToReduced.Add(exp, expressionContext.GetReduced(exp));
m_Expressions.UnionWith(expressionContext.BuildAllReduced());
foreach (var exp in expressionsToReduced.Values)
AddExpressionDataRecursively(m_ExpressionsData, exp);
}
public void CompileExpressions(VFXGraph graph, VFXExpressionContextOption options, bool filterOutInvalidContexts = false)
{
var models = new HashSet<ScriptableObject>();
graph.CollectDependencies(models);
var contexts = models.OfType<VFXContext>();
if (filterOutInvalidContexts)
contexts = contexts.Where(c => c.CanBeCompiled());
CompileExpressions(contexts, options);
}
public void CompileExpressions(IEnumerable<VFXContext> contexts, VFXExpressionContextOption options)
{
Profiler.BeginSample("VFXEditor.CompileExpressionGraph");
try
{
m_Expressions.Clear();
m_FlattenedExpressions.Clear();
m_ExpressionsData.Clear();
CompileExpressionContext(contexts, options, VFXDeviceTarget.CPU);
CompileExpressionContext(contexts, options | VFXExpressionContextOption.GPUDataTransformation, VFXDeviceTarget.GPU);
var sortedList = m_ExpressionsData.Where(kvp =>
{
var exp = kvp.Key;
return !exp.IsAny(VFXExpression.Flags.NotCompilableOnCPU);
}).ToList(); // remove per element expression from flattened data // TODO Remove uniform constants too
sortedList.Sort((kvpA, kvpB) => kvpB.Value.depth.CompareTo(kvpA.Value.depth));
m_FlattenedExpressions = sortedList.Select(kvp => kvp.Key).ToList();
// update index in expression data
for (int i = 0; i < m_FlattenedExpressions.Count; ++i)
{
var data = m_ExpressionsData[m_FlattenedExpressions[i]];
data.index = i;
m_ExpressionsData[m_FlattenedExpressions[i]] = data;
}
if (VFXViewPreference.advancedLogs)
Debug.Log(string.Format("RECOMPILE EXPRESSION GRAPH - NB EXPRESSIONS: {0} - NB CPU END EXPRESSIONS: {1} - NB GPU END EXPRESSIONS: {2}", m_Expressions.Count, m_CPUExpressionsToReduced.Count, m_GPUExpressionsToReduced.Count));
}
finally
{
Profiler.EndSample();
}
}
public int GetFlattenedIndex(VFXExpression exp)
{
if (m_ExpressionsData.ContainsKey(exp))
return m_ExpressionsData[exp].index;
return -1;
}
public VFXExpression GetReduced(VFXExpression exp, VFXDeviceTarget target)
{
VFXExpression reduced;
var expressionToReduced = target == VFXDeviceTarget.GPU ? m_GPUExpressionsToReduced : m_CPUExpressionsToReduced;
expressionToReduced.TryGetValue(exp, out reduced);
return reduced;
}
public VFXExpressionMapper BuildCPUMapper(VFXContext context)
{
return BuildMapper(context, m_ContextsToCPUExpressions, VFXDeviceTarget.CPU);
}
public VFXExpressionMapper BuildGPUMapper(VFXContext context)
{
return BuildMapper(context, m_ContextsToGPUExpressions, VFXDeviceTarget.GPU);
}
public List<string> GetAllNames(VFXExpression exp)
{
List<string> names = new List<string>();
foreach (var mapper in m_ContextsToCPUExpressions.Values.Concat(m_ContextsToGPUExpressions.Values))
{
names.AddRange(mapper.GetData(exp).Select(o => o.fullName));
}
return names;
}
private VFXExpressionMapper BuildMapper(VFXContext context, Dictionary<VFXContext, VFXExpressionMapper> dictionnary, VFXDeviceTarget target)
{
VFXExpression.Flags check = target == VFXDeviceTarget.GPU ? VFXExpression.Flags.InvalidOnGPU | VFXExpression.Flags.PerElement : VFXExpression.Flags.InvalidOnCPU;
VFXExpressionMapper outMapper = new VFXExpressionMapper();
VFXExpressionMapper inMapper;
dictionnary.TryGetValue(context, out inMapper);
if (inMapper != null)
{
foreach (var exp in inMapper.expressions)
{
var reduced = GetReduced(exp, target);
if (reduced.Is(check))
throw new InvalidOperationException(string.Format("The expression {0} is not valid as it have the invalid flag: {1}", reduced, check));
var mappedDataList = inMapper.GetData(exp);
foreach (var mappedData in mappedDataList)
outMapper.AddExpression(reduced, mappedData);
}
}
return outMapper;
}
public HashSet<VFXExpression> Expressions
{
get
{
return m_Expressions;
}
}
public List<VFXExpression> FlattenedExpressions
{
get
{
return m_FlattenedExpressions;
}
}
public Dictionary<VFXExpression, VFXExpression> GPUExpressionsToReduced
{
get
{
return m_GPUExpressionsToReduced;
}
}
public Dictionary<VFXExpression, VFXExpression> CPUExpressionsToReduced
{
get
{
return m_CPUExpressionsToReduced;
}
}
private HashSet<VFXExpression> m_Expressions = new HashSet<VFXExpression>();
private Dictionary<VFXExpression, VFXExpression> m_CPUExpressionsToReduced = new Dictionary<VFXExpression, VFXExpression>();
private Dictionary<VFXExpression, VFXExpression> m_GPUExpressionsToReduced = new Dictionary<VFXExpression, VFXExpression>();
private List<VFXExpression> m_FlattenedExpressions = new List<VFXExpression>();
private Dictionary<VFXExpression, ExpressionData> m_ExpressionsData = new Dictionary<VFXExpression, ExpressionData>();
private Dictionary<VFXContext, VFXExpressionMapper> m_ContextsToCPUExpressions = new Dictionary<VFXContext, VFXExpressionMapper>();
private Dictionary<VFXContext, VFXExpressionMapper> m_ContextsToGPUExpressions = new Dictionary<VFXContext, VFXExpressionMapper>();
}
}
| |
// InflaterInputStream.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// HISTORY
// 11-08-2009 GeoffHart T9121 Added Multi-member gzip support
using System;
using System.IO;
#if !NETCF_1_0
using System.Security.Cryptography;
#endif
namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// An input buffer customised for use by <see cref="InflaterInputStream"/>
/// </summary>
/// <remarks>
/// The buffer supports decryption of incoming data.
/// </remarks>
internal class InflaterInputBuffer
{
#region Constructors
/// <summary>
/// Initialise a new instance of <see cref="InflaterInputBuffer"/> with a default buffer size
/// </summary>
/// <param name="stream">The stream to buffer.</param>
public InflaterInputBuffer(Stream stream) : this(stream , 4096)
{
}
/// <summary>
/// Initialise a new instance of <see cref="InflaterInputBuffer"/>
/// </summary>
/// <param name="stream">The stream to buffer.</param>
/// <param name="bufferSize">The size to use for the buffer</param>
/// <remarks>A minimum buffer size of 1KB is permitted. Lower sizes are treated as 1KB.</remarks>
public InflaterInputBuffer(Stream stream, int bufferSize)
{
inputStream = stream;
if ( bufferSize < 1024 ) {
bufferSize = 1024;
}
rawData = new byte[bufferSize];
clearText = rawData;
}
#endregion
/// <summary>
/// Get the length of bytes bytes in the <see cref="RawData"/>
/// </summary>
public int RawLength
{
get {
return rawLength;
}
}
/// <summary>
/// Get the contents of the raw data buffer.
/// </summary>
/// <remarks>This may contain encrypted data.</remarks>
public byte[] RawData
{
get {
return rawData;
}
}
/// <summary>
/// Get the number of useable bytes in <see cref="ClearText"/>
/// </summary>
public int ClearTextLength
{
get {
return clearTextLength;
}
}
/// <summary>
/// Get the contents of the clear text buffer.
/// </summary>
public byte[] ClearText
{
get {
return clearText;
}
}
/// <summary>
/// Get/set the number of bytes available
/// </summary>
public int Available
{
get { return available; }
set { available = value; }
}
/// <summary>
/// Call <see cref="Inflater.SetInput(byte[], int, int)"/> passing the current clear text buffer contents.
/// </summary>
/// <param name="inflater">The inflater to set input for.</param>
public void SetInflaterInput(Inflater inflater)
{
if ( available > 0 ) {
inflater.SetInput(clearText, clearTextLength - available, available);
available = 0;
}
}
/// <summary>
/// Fill the buffer from the underlying input stream.
/// </summary>
public void Fill()
{
rawLength = 0;
int toRead = rawData.Length;
while (toRead > 0) {
int count = inputStream.Read(rawData, rawLength, toRead);
if ( count <= 0 ) {
break;
}
rawLength += count;
toRead -= count;
}
#if !NETCF_1_0
if ( cryptoTransform != null ) {
clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0);
}
else
#endif
{
clearTextLength = rawLength;
}
available = clearTextLength;
}
/// <summary>
/// Read a buffer directly from the input stream
/// </summary>
/// <param name="buffer">The buffer to fill</param>
/// <returns>Returns the number of bytes read.</returns>
public int ReadRawBuffer(byte[] buffer)
{
return ReadRawBuffer(buffer, 0, buffer.Length);
}
/// <summary>
/// Read a buffer directly from the input stream
/// </summary>
/// <param name="outBuffer">The buffer to read into</param>
/// <param name="offset">The offset to start reading data into.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>Returns the number of bytes read.</returns>
public int ReadRawBuffer(byte[] outBuffer, int offset, int length)
{
if ( length < 0 ) {
throw new ArgumentOutOfRangeException("length");
}
int currentOffset = offset;
int currentLength = length;
while ( currentLength > 0 ) {
if ( available <= 0 ) {
Fill();
if (available <= 0) {
return 0;
}
}
int toCopy = Math.Min(currentLength, available);
System.Array.Copy(rawData, rawLength - (int)available, outBuffer, currentOffset, toCopy);
currentOffset += toCopy;
currentLength -= toCopy;
available -= toCopy;
}
return length;
}
/// <summary>
/// Read clear text data from the input stream.
/// </summary>
/// <param name="outBuffer">The buffer to add data to.</param>
/// <param name="offset">The offset to start adding data at.</param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>Returns the number of bytes actually read.</returns>
public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length)
{
if ( length < 0 ) {
throw new ArgumentOutOfRangeException("length");
}
int currentOffset = offset;
int currentLength = length;
while ( currentLength > 0 ) {
if ( available <= 0 ) {
Fill();
if (available <= 0) {
return 0;
}
}
int toCopy = Math.Min(currentLength, available);
Array.Copy(clearText, clearTextLength - (int)available, outBuffer, currentOffset, toCopy);
currentOffset += toCopy;
currentLength -= toCopy;
available -= toCopy;
}
return length;
}
/// <summary>
/// Read a <see cref="byte"/> from the input stream.
/// </summary>
/// <returns>Returns the byte read.</returns>
public int ReadLeByte()
{
if (available <= 0) {
Fill();
if (available <= 0) {
throw new ZipException("EOF in header");
}
}
byte result = rawData[rawLength - available];
available -= 1;
return result;
}
/// <summary>
/// Read an <see cref="short"/> in little endian byte order.
/// </summary>
/// <returns>The short value read case to an int.</returns>
public int ReadLeShort()
{
return ReadLeByte() | (ReadLeByte() << 8);
}
/// <summary>
/// Read an <see cref="int"/> in little endian byte order.
/// </summary>
/// <returns>The int value read.</returns>
public int ReadLeInt()
{
return ReadLeShort() | (ReadLeShort() << 16);
}
/// <summary>
/// Read a <see cref="long"/> in little endian byte order.
/// </summary>
/// <returns>The long value read.</returns>
public long ReadLeLong()
{
return (uint)ReadLeInt() | ((long)ReadLeInt() << 32);
}
#if !NETCF_1_0
/// <summary>
/// Get/set the <see cref="ICryptoTransform"/> to apply to any data.
/// </summary>
/// <remarks>Set this value to null to have no transform applied.</remarks>
public ICryptoTransform CryptoTransform
{
set {
cryptoTransform = value;
if ( cryptoTransform != null ) {
if ( rawData == clearText ) {
if ( internalClearText == null ) {
internalClearText = new byte[rawData.Length];
}
clearText = internalClearText;
}
clearTextLength = rawLength;
if ( available > 0 ) {
cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available);
}
} else {
clearText = rawData;
clearTextLength = rawLength;
}
}
}
#endif
#region Instance Fields
int rawLength;
byte[] rawData;
int clearTextLength;
byte[] clearText;
#if !NETCF_1_0
byte[] internalClearText;
#endif
int available;
#if !NETCF_1_0
ICryptoTransform cryptoTransform;
#endif
Stream inputStream;
#endregion
}
/// <summary>
/// This filter stream is used to decompress data compressed using the "deflate"
/// format. The "deflate" format is described in RFC 1951.
///
/// This stream may form the basis for other decompression filters, such
/// as the <see cref="ICSharpCode.SharpZipLib.GZip.GZipInputStream">GZipInputStream</see>.
///
/// Author of the original java version : John Leuner.
/// </summary>
internal class InflaterInputStream : Stream
{
#region Constructors
/// <summary>
/// Create an InflaterInputStream with the default decompressor
/// and a default buffer size of 4KB.
/// </summary>
/// <param name = "baseInputStream">
/// The InputStream to read bytes from
/// </param>
public InflaterInputStream(Stream baseInputStream)
: this(baseInputStream, new Inflater(), 4096)
{
}
/// <summary>
/// Create an InflaterInputStream with the specified decompressor
/// and a default buffer size of 4KB.
/// </summary>
/// <param name = "baseInputStream">
/// The source of input data
/// </param>
/// <param name = "inf">
/// The decompressor used to decompress data read from baseInputStream
/// </param>
internal InflaterInputStream(Stream baseInputStream, Inflater inf)
: this(baseInputStream, inf, 4096)
{
}
/// <summary>
/// Create an InflaterInputStream with the specified decompressor
/// and the specified buffer size.
/// </summary>
/// <param name = "baseInputStream">
/// The InputStream to read bytes from
/// </param>
/// <param name = "inflater">
/// The decompressor to use
/// </param>
/// <param name = "bufferSize">
/// Size of the buffer to use
/// </param>
internal InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize)
{
if (baseInputStream == null) {
throw new ArgumentNullException("baseInputStream");
}
if (inflater == null) {
throw new ArgumentNullException("inflater");
}
if (bufferSize <= 0) {
throw new ArgumentOutOfRangeException("bufferSize");
}
this.baseInputStream = baseInputStream;
this.inf = inflater;
inputBuffer = new InflaterInputBuffer(baseInputStream, bufferSize);
}
#endregion
/// <summary>
/// Get/set flag indicating ownership of underlying stream.
/// When the flag is true <see cref="Close"/> will close the underlying stream also.
/// </summary>
/// <remarks>
/// The default value is true.
/// </remarks>
public bool IsStreamOwner
{
get { return isStreamOwner; }
set { isStreamOwner = value; }
}
/// <summary>
/// Skip specified number of bytes of uncompressed data
/// </summary>
/// <param name ="count">
/// Number of bytes to skip
/// </param>
/// <returns>
/// The number of bytes skipped, zero if the end of
/// stream has been reached
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="count">The number of bytes</paramref> to skip is less than or equal to zero.
/// </exception>
public long Skip(long count)
{
if (count <= 0) {
throw new ArgumentOutOfRangeException("count");
}
// v0.80 Skip by seeking if underlying stream supports it...
if (baseInputStream.CanSeek) {
baseInputStream.Seek(count, SeekOrigin.Current);
return count;
}
else {
int length = 2048;
if (count < length) {
length = (int) count;
}
byte[] tmp = new byte[length];
int readCount = 1;
long toSkip = count;
while ((toSkip > 0) && (readCount > 0) ) {
if (toSkip < length) {
length = (int)toSkip;
}
readCount = baseInputStream.Read(tmp, 0, length);
toSkip -= readCount;
}
return count - toSkip;
}
}
/// <summary>
/// Clear any cryptographic state.
/// </summary>
protected void StopDecrypting()
{
#if !NETCF_1_0
inputBuffer.CryptoTransform = null;
#endif
}
/// <summary>
/// Returns 0 once the end of the stream (EOF) has been reached.
/// Otherwise returns 1.
/// </summary>
public virtual int Available
{
get {
return inf.IsFinished ? 0 : 1;
}
}
/// <summary>
/// Fills the buffer with more data to decompress.
/// </summary>
/// <exception cref="SharpZipBaseException">
/// Stream ends early
/// </exception>
protected void Fill()
{
// Protect against redundant calls
if (inputBuffer.Available <= 0) {
inputBuffer.Fill();
if (inputBuffer.Available <= 0) {
throw new SharpZipBaseException("Unexpected EOF");
}
}
inputBuffer.SetInflaterInput(inf);
}
#region Stream Overrides
/// <summary>
/// Gets a value indicating whether the current stream supports reading
/// </summary>
public override bool CanRead
{
get {
return baseInputStream.CanRead;
}
}
/// <summary>
/// Gets a value of false indicating seeking is not supported for this stream.
/// </summary>
public override bool CanSeek {
get {
return false;
}
}
/// <summary>
/// Gets a value of false indicating that this stream is not writeable.
/// </summary>
public override bool CanWrite {
get {
return false;
}
}
/// <summary>
/// A value representing the length of the stream in bytes.
/// </summary>
public override long Length {
get {
return inputBuffer.RawLength;
}
}
/// <summary>
/// The current position within the stream.
/// Throws a NotSupportedException when attempting to set the position
/// </summary>
/// <exception cref="NotSupportedException">Attempting to set the position</exception>
public override long Position {
get {
return baseInputStream.Position;
}
set {
throw new NotSupportedException("InflaterInputStream Position not supported");
}
}
/// <summary>
/// Flushes the baseInputStream
/// </summary>
public override void Flush()
{
baseInputStream.Flush();
}
/// <summary>
/// Sets the position within the current stream
/// Always throws a NotSupportedException
/// </summary>
/// <param name="offset">The relative offset to seek to.</param>
/// <param name="origin">The <see cref="SeekOrigin"/> defining where to seek from.</param>
/// <returns>The new position in the stream.</returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("Seek not supported");
}
/// <summary>
/// Set the length of the current stream
/// Always throws a NotSupportedException
/// </summary>
/// <param name="value">The new length value for the stream.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void SetLength(long value)
{
throw new NotSupportedException("InflaterInputStream SetLength not supported");
}
/// <summary>
/// Writes a sequence of bytes to stream and advances the current position
/// This method always throws a NotSupportedException
/// </summary>
/// <param name="buffer">Thew buffer containing data to write.</param>
/// <param name="offset">The offset of the first byte to write.</param>
/// <param name="count">The number of bytes to write.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException("InflaterInputStream Write not supported");
}
/// <summary>
/// Writes one byte to the current stream and advances the current position
/// Always throws a NotSupportedException
/// </summary>
/// <param name="value">The byte to write.</param>
/// <exception cref="NotSupportedException">Any access</exception>
public override void WriteByte(byte value)
{
throw new NotSupportedException("InflaterInputStream WriteByte not supported");
}
/// <summary>
/// Entry point to begin an asynchronous write. Always throws a NotSupportedException.
/// </summary>
/// <param name="buffer">The buffer to write data from</param>
/// <param name="offset">Offset of first byte to write</param>
/// <param name="count">The maximum number of bytes to write</param>
/// <param name="callback">The method to be called when the asynchronous write operation is completed</param>
/// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests</param>
/// <returns>An <see cref="System.IAsyncResult">IAsyncResult</see> that references the asynchronous write</returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException("InflaterInputStream BeginWrite not supported");
}
/// <summary>
/// Closes the input stream. When <see cref="IsStreamOwner"></see>
/// is true the underlying stream is also closed.
/// </summary>
public override void Close()
{
if ( !isClosed ) {
isClosed = true;
if ( isStreamOwner ) {
baseInputStream.Close();
}
}
}
/// <summary>
/// Reads decompressed data into the provided buffer byte array
/// </summary>
/// <param name ="buffer">
/// The array to read and decompress data into
/// </param>
/// <param name ="offset">
/// The offset indicating where the data should be placed
/// </param>
/// <param name ="count">
/// The number of bytes to decompress
/// </param>
/// <returns>The number of bytes read. Zero signals the end of stream</returns>
/// <exception cref="SharpZipBaseException">
/// Inflater needs a dictionary
/// </exception>
public override int Read(byte[] buffer, int offset, int count)
{
if (inf.IsNeedingDictionary)
{
throw new SharpZipBaseException("Need a dictionary");
}
int remainingBytes = count;
while (true) {
int bytesRead = inf.Inflate(buffer, offset, remainingBytes);
offset += bytesRead;
remainingBytes -= bytesRead;
if (remainingBytes == 0 || inf.IsFinished) {
break;
}
if ( inf.IsNeedingInput ) {
Fill();
}
else if ( bytesRead == 0 ) {
throw new ZipException("Dont know what to do");
}
}
return count - remainingBytes;
}
#endregion
#region Instance Fields
/// <summary>
/// Decompressor for this stream
/// </summary>
internal Inflater inf;
/// <summary>
/// <see cref="InflaterInputBuffer">Input buffer</see> for this stream.
/// </summary>
internal InflaterInputBuffer inputBuffer;
/// <summary>
/// Base stream the inflater reads from.
/// </summary>
private Stream baseInputStream;
/// <summary>
/// The compressed size
/// </summary>
protected long csize;
/// <summary>
/// Flag indicating wether this instance has been closed or not.
/// </summary>
bool isClosed;
/// <summary>
/// Flag indicating wether this instance is designated the stream owner.
/// When closing if this flag is true the underlying stream is closed.
/// </summary>
bool isStreamOwner = true;
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// ConstraintBuilder maintains the stacks that are used in
/// processing a ConstraintExpression. An OperatorStack
/// is used to hold operators that are waiting for their
/// operands to be reorganized. a ConstraintStack holds
/// input constraints as well as the results of each
/// operator applied.
/// </summary>
public sealed class ConstraintBuilder : IResolveConstraint
{
#region Nested Operator Stack Class
/// <summary>
/// OperatorStack is a type-safe stack for holding ConstraintOperators
/// </summary>
private sealed class OperatorStack
{
private readonly Stack<ConstraintOperator> stack = new Stack<ConstraintOperator>();
/// <summary>
/// Initializes a new instance of the <see cref="OperatorStack"/> class.
/// </summary>
/// <param name="builder">The ConstraintBuilder using this stack.</param>
public OperatorStack(ConstraintBuilder builder)
{
}
/// <summary>
/// Gets a value indicating whether this <see cref="OperatorStack"/> is empty.
/// </summary>
/// <value><c>true</c> if empty; otherwise, <c>false</c>.</value>
public bool Empty
{
get { return stack.Count == 0; }
}
/// <summary>
/// Gets the topmost operator without modifying the stack.
/// </summary>
public ConstraintOperator Top
{
get { return stack.Peek(); }
}
/// <summary>
/// Pushes the specified operator onto the stack.
/// </summary>
/// <param name="op">The operator to put onto the stack.</param>
public void Push(ConstraintOperator op)
{
stack.Push(op);
}
/// <summary>
/// Pops the topmost operator from the stack.
/// </summary>
/// <returns>The topmost operator on the stack</returns>
public ConstraintOperator Pop()
{
return stack.Pop();
}
}
#endregion
#region Nested Constraint Stack Class
/// <summary>
/// ConstraintStack is a type-safe stack for holding Constraints
/// </summary>
public sealed class ConstraintStack
{
private readonly Stack<IConstraint> stack = new Stack<IConstraint>();
private readonly ConstraintBuilder builder;
/// <summary>
/// Initializes a new instance of the <see cref="ConstraintStack"/> class.
/// </summary>
/// <param name="builder">The ConstraintBuilder using this stack.</param>
public ConstraintStack(ConstraintBuilder builder)
{
this.builder = builder;
}
/// <summary>
/// Gets a value indicating whether this <see cref="ConstraintStack"/> is empty.
/// </summary>
/// <value><c>true</c> if empty; otherwise, <c>false</c>.</value>
public bool Empty
{
get { return stack.Count == 0; }
}
/// <summary>
/// Pushes the specified constraint. As a side effect,
/// the constraint's Builder field is set to the
/// ConstraintBuilder owning this stack.
/// </summary>
/// <param name="constraint">The constraint to put onto the stack</param>
public void Push(IConstraint constraint)
{
stack.Push(constraint);
constraint.Builder = this.builder;
}
/// <summary>
/// Pops this topmost constraint from the stack.
/// As a side effect, the constraint's Builder
/// field is set to null.
/// </summary>
/// <returns>The topmost constraint on the stack</returns>
public IConstraint Pop()
{
IConstraint constraint = stack.Pop();
constraint.Builder = null;
return constraint;
}
}
#endregion
#region Instance Fields
private readonly OperatorStack ops;
private readonly ConstraintStack constraints;
private object lastPushed;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ConstraintBuilder"/> class.
/// </summary>
public ConstraintBuilder()
{
this.ops = new OperatorStack(this);
this.constraints = new ConstraintStack(this);
}
#endregion
#region Public Methods
/// <summary>
/// Appends the specified operator to the expression by first
/// reducing the operator stack and then pushing the new
/// operator on the stack.
/// </summary>
/// <param name="op">The operator to push.</param>
public void Append(ConstraintOperator op)
{
op.LeftContext = lastPushed;
if (lastPushed is ConstraintOperator)
SetTopOperatorRightContext(op);
// Reduce any lower precedence operators
ReduceOperatorStack(op.LeftPrecedence);
ops.Push(op);
lastPushed = op;
}
/// <summary>
/// Appends the specified constraint to the expression by pushing
/// it on the constraint stack.
/// </summary>
/// <param name="constraint">The constraint to push.</param>
public void Append(Constraint constraint)
{
if (lastPushed is ConstraintOperator)
SetTopOperatorRightContext(constraint);
constraints.Push(constraint);
lastPushed = constraint;
constraint.Builder = this;
}
/// <summary>
/// Sets the top operator right context.
/// </summary>
/// <param name="rightContext">The right context.</param>
private void SetTopOperatorRightContext(object rightContext)
{
// Some operators change their precedence based on
// the right context - save current precedence.
int oldPrecedence = ops.Top.LeftPrecedence;
ops.Top.RightContext = rightContext;
// If the precedence increased, we may be able to
// reduce the region of the stack below the operator
if (ops.Top.LeftPrecedence > oldPrecedence)
{
ConstraintOperator changedOp = ops.Pop();
ReduceOperatorStack(changedOp.LeftPrecedence);
ops.Push(changedOp);
}
}
/// <summary>
/// Reduces the operator stack until the topmost item
/// precedence is greater than or equal to the target precedence.
/// </summary>
/// <param name="targetPrecedence">The target precedence.</param>
private void ReduceOperatorStack(int targetPrecedence)
{
while (!ops.Empty && ops.Top.RightPrecedence < targetPrecedence)
ops.Pop().Reduce(constraints);
}
#endregion
#region IResolveConstraint Implementation
/// <summary>
/// Resolves this instance, returning a Constraint. If the Builder
/// is not currently in a resolvable state, an exception is thrown.
/// </summary>
/// <returns>The resolved constraint</returns>
public IConstraint Resolve()
{
if (!IsResolvable)
throw new InvalidOperationException("A partial expression may not be resolved");
while (!ops.Empty)
{
ConstraintOperator op = ops.Pop();
op.Reduce(constraints);
}
return constraints.Pop();
}
#endregion
#region Helper Methods
/// <summary>
/// Gets a value indicating whether this instance is resolvable.
/// </summary>
/// <value>
/// <c>true</c> if this instance is resolvable; otherwise, <c>false</c>.
/// </value>
private bool IsResolvable
{
get { return lastPushed is Constraint || lastPushed is SelfResolvingOperator; }
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ASP.NET_WebAPI.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
public enum NodeFlags
{
None = 0,
EmptyElement = 1,
HasValue = 2,
SingleQuote = 4,
DefaultAttribute = 8,
UnparsedEntities = 16,
IsWhitespace = 32,
DocumentRoot = 64,
AttributeTextNode = 128,
MixedContent = 256,
Indent = 512
}
abstract public class CXmlBase
{
protected XmlNodeType _nType;
protected string _strName;
protected string _strLocalName;
protected string _strPrefix;
protected string _strNamespace;
internal int _nDepth;
internal NodeFlags _eFlags = NodeFlags.None;
internal CXmlBase _rNextNode = null;
internal CXmlBase _rParentNode = null;
internal CXmlBase _rFirstChildNode = null;
internal CXmlBase _rLastChildNode = null;
internal int _nChildNodes = 0;
//
// Constructors
//
public CXmlBase(string strPrefix, string strName, string strLocalName, XmlNodeType NodeType, string strNamespace)
{
_strPrefix = strPrefix;
_strName = strName;
_strLocalName = strLocalName;
_nType = NodeType;
_strNamespace = strNamespace;
}
public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType, string strNamespace)
: this(strPrefix, strName, strName, NodeType, strNamespace)
{ }
public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType)
: this(strPrefix, strName, strName, NodeType, "")
{ }
public CXmlBase(string strName, XmlNodeType NodeType)
: this("", strName, strName, NodeType, "")
{ }
//
// Virtual Methods and Properties
//
abstract public void Write(XmlWriter rXmlWriter);
abstract public string Xml
{ get; }
abstract public void WriteXml(TextWriter rTW);
abstract public string Value
{ get; }
//
// Public Methods and Properties
//
public string Name
{
get { return _strName; }
}
public string LocalName
{
get { return _strLocalName; }
}
public string Prefix
{
get { return _strPrefix; }
}
public string Namespace
{
get { return _strNamespace; }
}
public int Depth
{
get { return _nDepth; }
}
public XmlNodeType NodeType
{
get { return _nType; }
}
public NodeFlags Flags
{
get { return _eFlags; }
}
public int ChildNodeCount
{
get { return _nChildNodes; }
}
public void InsertNode(CXmlBase rNode)
{
if (_rFirstChildNode == null)
{
_rFirstChildNode = _rLastChildNode = rNode;
}
else
{
_rLastChildNode._rNextNode = rNode;
_rLastChildNode = rNode;
}
if ((this._eFlags & NodeFlags.IsWhitespace) == 0)
_nChildNodes++;
rNode._rParentNode = this;
}
//
// Internal Methods and Properties
//
internal CXmlBase _Child(int n)
{
int i;
int j;
CXmlBase rChild = _rFirstChildNode;
for (i = 0, j = 0; rChild != null; i++, rChild = rChild._rNextNode)
{
if ((rChild._eFlags & NodeFlags.IsWhitespace) == 0)
{
if (j++ == n) break;
}
}
return rChild;
}
internal CXmlBase _Child(string str)
{
CXmlBase rChild;
for (rChild = _rFirstChildNode; rChild != null; rChild = rChild._rNextNode)
if (rChild.Name == str) break;
return rChild;
}
//
// Private Methods and Properties
//
}
public class CXmlAttribute : CXmlBase
{
//
// Constructor
//
public CXmlAttribute(XmlReader rXmlReader)
: base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI)
{
if (rXmlReader.IsDefault)
_eFlags |= NodeFlags.DefaultAttribute;
if (rXmlReader.QuoteChar == '\'')
_eFlags |= NodeFlags.SingleQuote;
}
//
// Public Methods and Properties (Override)
//
override public void Write(XmlWriter rXmlWriter)
{
CXmlBase rNode;
if ((this._eFlags & NodeFlags.DefaultAttribute) == 0)
{
if (rXmlWriter is XmlTextWriter)
((XmlTextWriter)rXmlWriter).QuoteChar = this.Quote;
rXmlWriter.WriteStartAttribute(this.Prefix, this.LocalName, this.Namespace);
for (rNode = this._rFirstChildNode; rNode != null; rNode = rNode._rNextNode)
{
rNode.Write(rXmlWriter);
}
rXmlWriter.WriteEndAttribute();
}
}
override public string Xml
{
get
{
CXmlCache._rBufferWriter.Dispose();
WriteXml(CXmlCache._rBufferWriter);
return CXmlCache._rBufferWriter.ToString();
}
}
override public void WriteXml(TextWriter rTW)
{
if ((this._eFlags & NodeFlags.DefaultAttribute) == 0)
{
CXmlBase rNode;
rTW.Write(' ' + this.Name + '=' + this.Quote);
for (rNode = this._rFirstChildNode; rNode != null; rNode = rNode._rNextNode)
{
rNode.WriteXml(rTW);
}
rTW.Write(this.Quote);
}
}
//
// Public Methods and Properties
//
override public string Value
{
get
{
CXmlNode rNode;
string strValue = string.Empty;
for (rNode = (CXmlNode)this._rFirstChildNode; rNode != null; rNode = rNode.NextNode)
strValue += rNode.Value;
return strValue;
}
}
public CXmlAttribute NextAttribute
{
get { return (CXmlAttribute)this._rNextNode; }
}
public char Quote
{
get { return ((base._eFlags & NodeFlags.SingleQuote) != 0 ? '\'' : '"'); }
set { if (value == '\'') base._eFlags |= NodeFlags.SingleQuote; else base._eFlags &= ~NodeFlags.SingleQuote; }
}
public CXmlNode FirstChild
{
get { return (CXmlNode)base._rFirstChildNode; }
}
public CXmlNode Child(int n)
{
return (CXmlNode)base._Child(n);
}
public CXmlNode Child(string str)
{
return (CXmlNode)base._Child(str);
}
}
public class CXmlNode : CXmlBase
{
internal string _strValue = null;
private CXmlAttribute _rFirstAttribute = null;
private CXmlAttribute _rLastAttribute = null;
private int _nAttributeCount = 0;
//
// Constructors
//
public CXmlNode(string strPrefix, string strName, XmlNodeType NodeType)
: base(strPrefix, strName, NodeType)
{ }
public CXmlNode(XmlReader rXmlReader)
: base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI)
{
_eFlags |= CXmlCache._eDefaultFlags;
if (NodeType == XmlNodeType.Whitespace ||
NodeType == XmlNodeType.SignificantWhitespace)
{
_eFlags |= NodeFlags.IsWhitespace;
}
if (rXmlReader.IsEmptyElement)
{
_eFlags |= NodeFlags.EmptyElement;
}
if (rXmlReader.HasValue)
{
_eFlags |= NodeFlags.HasValue;
_strValue = rXmlReader.Value;
}
}
//
// Public Methods and Properties (Override)
//
override public void Write(XmlWriter rXmlWriter)
{
CXmlBase rNode;
CXmlAttribute rAttribute;
string DocTypePublic = null;
string DocTypeSystem = null;
/*
// Display of Indent information
if (this.LocalName == string.Empty)
_output.WriteLine("Node={0}, Indent={1}, Mixed={2}",this.NodeType, this.Flags & NodeFlags.Indent, this.Flags & NodeFlags.MixedContent);
else
_output.WriteLine("Node={0}, Indent={1}, Mixed={2}",this.LocalName, this.Flags & NodeFlags.Indent, this.Flags & NodeFlags.MixedContent);
*/
switch (this.NodeType)
{
case XmlNodeType.CDATA:
rXmlWriter.WriteCData(this._strValue);
break;
case XmlNodeType.Comment:
rXmlWriter.WriteComment(this._strValue);
break;
case XmlNodeType.DocumentType:
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
if (rAttribute.Name == "PUBLIC")
{ DocTypePublic = rAttribute.Value; }
if (rAttribute.Name == "SYSTEM")
{ DocTypeSystem = rAttribute.Value; }
}
rXmlWriter.WriteDocType(this.Name, DocTypePublic, DocTypeSystem, this._strValue);
break;
case XmlNodeType.EntityReference:
rXmlWriter.WriteEntityRef(this.Name);
break;
case XmlNodeType.ProcessingInstruction:
rXmlWriter.WriteProcessingInstruction(this.Name, this._strValue);
break;
case XmlNodeType.Text:
if (this.Name == string.Empty)
{
if ((this.Flags & NodeFlags.UnparsedEntities) == 0)
{
rXmlWriter.WriteString(this._strValue);
}
else
{
rXmlWriter.WriteRaw(this._strValue.ToCharArray(), 0, this._strValue.Length);
}
}
else
{
if (this._strName[0] == '#')
rXmlWriter.WriteCharEntity(this._strValue[0]);
else
rXmlWriter.WriteEntityRef(this.Name);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if ((this._rParentNode._eFlags & NodeFlags.DocumentRoot) != 0)
rXmlWriter.WriteRaw(this._strValue.ToCharArray(), 0, this._strValue.Length);
else
rXmlWriter.WriteString(this._strValue);
break;
case XmlNodeType.Element:
rXmlWriter.WriteStartElement(this.Prefix, this.LocalName, null);
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
rAttribute.Write(rXmlWriter);
}
if ((this.Flags & NodeFlags.EmptyElement) == 0)
rXmlWriter.WriteString(string.Empty);
for (rNode = base._rFirstChildNode; rNode != null; rNode = rNode._rNextNode)
{
rNode.Write(rXmlWriter);
}
// Should only produce empty tag if the original document used empty tag
if ((this.Flags & NodeFlags.EmptyElement) == 0)
rXmlWriter.WriteFullEndElement();
else
rXmlWriter.WriteEndElement();
break;
case XmlNodeType.XmlDeclaration:
rXmlWriter.WriteRaw("<?xml " + this._strValue + "?>");
break;
default:
throw (new Exception("Node.Write: Unhandled node type " + this.NodeType.ToString()));
}
}
override public string Xml
{
get
{
CXmlCache._rBufferWriter.Dispose();
WriteXml(CXmlCache._rBufferWriter);
return CXmlCache._rBufferWriter.ToString();
}
}
override public void WriteXml(TextWriter rTW)
{
String strXml;
CXmlAttribute rAttribute;
CXmlBase rNode;
switch (this._nType)
{
case XmlNodeType.Text:
if (this._strName == "")
{
rTW.Write(this._strValue);
}
else
{
if (this._strName.StartsWith("#"))
{
rTW.Write("&" + Convert.ToString(Convert.ToInt32(this._strValue[0])) + ";");
}
else
{
rTW.Write("&" + this.Name + ";");
}
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.DocumentType:
rTW.Write(this._strValue);
break;
case XmlNodeType.Element:
strXml = this.Name;
rTW.Write('<' + strXml);
//Put in all the Attributes
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
rAttribute.WriteXml(rTW);
}
//If there is children, put those in, otherwise close the tag.
if ((base._eFlags & NodeFlags.EmptyElement) == 0)
{
rTW.Write('>');
for (rNode = base._rFirstChildNode; rNode != null; rNode = rNode._rNextNode)
{
rNode.WriteXml(rTW);
}
rTW.Write("</" + strXml + ">");
}
else
{
rTW.Write(" />");
}
break;
case XmlNodeType.EntityReference:
rTW.Write("&" + this._strName + ";");
break;
case XmlNodeType.Notation:
rTW.Write("<!NOTATION " + this._strValue + ">");
break;
case XmlNodeType.CDATA:
rTW.Write("<![CDATA[" + this._strValue + "]]>");
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
rTW.Write("<?" + this._strName + " " + this._strValue + "?>");
break;
case XmlNodeType.Comment:
rTW.Write("<!--" + this._strValue + "-->");
break;
default:
throw (new Exception("Unhandled NodeType " + this._nType.ToString()));
}
}
//
// Public Methods and Properties
//
public string NodeValue
{
get { return _strValue; }
}
override public string Value
{
get
{
string strValue = "";
CXmlNode rChild;
if ((this._eFlags & NodeFlags.HasValue) != 0)
{
char chEnt;
int nIndexAmp = 0;
int nIndexSem = 0;
if ((this._eFlags & NodeFlags.UnparsedEntities) == 0)
return this._strValue;
strValue = this._strValue;
while ((nIndexAmp = strValue.IndexOf('&', nIndexAmp)) != -1)
{
nIndexSem = strValue.IndexOf(';', nIndexAmp);
chEnt = ResolveCharEntity(strValue.Substring(nIndexAmp + 1, nIndexSem - nIndexAmp - 1));
if (chEnt != char.MinValue)
{
strValue = strValue.Substring(0, nIndexAmp) + chEnt + strValue.Substring(nIndexSem + 1);
nIndexAmp++;
}
else
nIndexAmp = nIndexSem;
}
return strValue;
}
for (rChild = (CXmlNode)this._rFirstChildNode; rChild != null; rChild = (CXmlNode)rChild._rNextNode)
{
strValue = strValue + rChild.Value;
}
return strValue;
}
}
public CXmlNode NextNode
{
get
{
CXmlBase rNode = this._rNextNode;
while (rNode != null &&
(rNode.Flags & NodeFlags.IsWhitespace) != 0)
rNode = rNode._rNextNode;
return (CXmlNode)rNode;
}
}
public CXmlNode FirstChild
{
get
{
CXmlBase rNode = this._rFirstChildNode;
while (rNode != null &&
(rNode.Flags & NodeFlags.IsWhitespace) != 0)
rNode = rNode._rNextNode;
return (CXmlNode)rNode;
}
}
public CXmlNode Child(int n)
{
int i;
CXmlNode rChild;
i = 0;
for (rChild = FirstChild; rChild != null; rChild = rChild.NextNode)
if (i++ == n) break;
return rChild;
}
public CXmlNode Child(string str)
{
return (CXmlNode)base._Child(str);
}
public int Type
{
get { return Convert.ToInt32(base._nType); }
}
public CXmlAttribute FirstAttribute
{
get { return _rFirstAttribute; }
}
public int AttributeCount
{
get { return _nAttributeCount; }
}
public CXmlAttribute Attribute(int n)
{
int i;
CXmlAttribute rAttribute;
i = 0;
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
if (i++ == n) break;
return rAttribute;
}
public CXmlAttribute Attribute(string str)
{
CXmlAttribute rAttribute;
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
if (rAttribute.Name == str) break;
}
return rAttribute;
}
public void AddAttribute(CXmlAttribute rAttribute)
{
if (_rFirstAttribute == null)
{
_rFirstAttribute = rAttribute;
}
else
{
_rLastAttribute._rNextNode = rAttribute;
}
_rLastAttribute = rAttribute;
_nAttributeCount++;
}
private char ResolveCharEntity(string strName)
{
if (strName[0] == '#')
if (strName[1] == 'x')
return Convert.ToChar(Convert.ToInt32(strName.Substring(2), 16));
else
return Convert.ToChar(Convert.ToInt32(strName.Substring(1)));
if (strName == "lt")
return '<';
if (strName == "gt")
return '>';
if (strName == "amp")
return '&';
if (strName == "apos")
return '\'';
if (strName == "quot")
return '"';
return char.MinValue;
}
}
public class CXmlCache
{
//CXmlCache Properties
private bool _fTrace = false;
private bool _fThrow = true;
private bool _fReadNode = true;
private int _hr = 0;
private Encoding _eEncoding = System.Text.Encoding.UTF8;
private string _strParseError = "";
//XmlReader Properties
#pragma warning disable 0618
private ValidationType _eValidationMode = ValidationType.Auto;
#pragma warning restore 0618
private WhitespaceHandling _eWhitespaceMode = WhitespaceHandling.None;
private EntityHandling _eEntityMode = EntityHandling.ExpandEntities;
private bool _fNamespaces = true;
private bool _fValidationCallback = false;
private bool _fExpandAttributeValues = false;
//Internal stuff
protected XmlReader _rXmlReader = null;
protected CXmlNode _rDocumentRootNode;
protected CXmlNode _rRootNode = null;
internal static NodeFlags _eDefaultFlags = NodeFlags.None;
static internal BufferWriter _rBufferWriter = new BufferWriter();
private ITestOutputHelper _output;
public CXmlCache(ITestOutputHelper output)
{
_output = output;
}
//
// Constructor
//
public CXmlCache()
{
}
//
// Public Methods and Properties
//
public virtual bool Load(XmlReader rXmlReader)
{
//Hook up your reader as my reader
_rXmlReader = rXmlReader;
if (rXmlReader is XmlTextReader)
{
_eWhitespaceMode = ((XmlTextReader)rXmlReader).WhitespaceHandling;
_fNamespaces = ((XmlTextReader)rXmlReader).Namespaces;
_eValidationMode = ValidationType.None;
// _eEntityMode = ((XmlValidatingReader)rXmlReader).EntityHandling;
}
#pragma warning disable 0618
if (rXmlReader is XmlValidatingReader)
{
if (((XmlValidatingReader)rXmlReader).Reader is XmlTextReader)
{
_eWhitespaceMode = ((XmlTextReader)((XmlValidatingReader)rXmlReader).Reader).WhitespaceHandling;
}
else
{
_eWhitespaceMode = WhitespaceHandling.None;
}
_fNamespaces = ((XmlValidatingReader)rXmlReader).Namespaces;
_eValidationMode = ((XmlValidatingReader)rXmlReader).ValidationType;
_eEntityMode = ((XmlValidatingReader)rXmlReader).EntityHandling;
}
#pragma warning restore 0618
DebugTrace("Setting ValidationMode=" + _eValidationMode.ToString());
DebugTrace("Setting EntityMode=" + _eEntityMode.ToString());
DebugTrace("Setting WhitespaceMode=" + _eWhitespaceMode.ToString());
//Process the Document
try
{
_rDocumentRootNode = new CXmlNode("", "", XmlNodeType.Element);
_rDocumentRootNode._eFlags = NodeFlags.DocumentRoot | NodeFlags.Indent;
Process(_rDocumentRootNode);
for (_rRootNode = _rDocumentRootNode.FirstChild; _rRootNode != null && _rRootNode.NodeType != XmlNodeType.Element; _rRootNode = _rRootNode.NextNode) ;
}
catch (Exception e)
{
//Unhook your reader
_rXmlReader = null;
_strParseError = e.ToString();
if (_fThrow)
{
throw (e);
}
if (_hr == 0)
_hr = -1;
return false;
}
//Unhook your reader
_rXmlReader = null;
return true;
}
public bool Load(string strFileName)
{
#pragma warning disable 0618
XmlTextReader rXmlTextReader;
XmlValidatingReader rXmlValidatingReader;
bool fRet;
rXmlTextReader = new XmlTextReader(strFileName);
rXmlTextReader.WhitespaceHandling = _eWhitespaceMode;
rXmlTextReader.Namespaces = _fNamespaces;
_eEncoding = rXmlTextReader.Encoding;
rXmlValidatingReader = new XmlValidatingReader(rXmlTextReader);
rXmlValidatingReader.ValidationType = _eValidationMode;
rXmlValidatingReader.EntityHandling = _eEntityMode;
#pragma warning restore 0618
if (_fValidationCallback)
rXmlValidatingReader.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallback);
try
{
fRet = Load((XmlReader)rXmlValidatingReader);
}
catch (Exception e)
{
fRet = false;
rXmlValidatingReader.Dispose();
rXmlTextReader.Dispose();
if (_strParseError == string.Empty)
_strParseError = e.ToString();
if (_fThrow)
throw (e);
}
rXmlValidatingReader.Dispose();
rXmlTextReader.Dispose();
return fRet;
}
public void Save(string strName)
{
Save(strName, false, _eEncoding);
}
public void Save(string strName, bool fOverWrite)
{
Save(strName, fOverWrite, _eEncoding);
}
public void Save(string strName, bool fOverWrite, System.Text.Encoding Encoding)
{
CXmlBase rNode;
XmlTextWriter rXmlTextWriter = null;
try
{
if (fOverWrite)
{
File.Delete(strName);
}
rXmlTextWriter = new XmlTextWriter(strName, Encoding);
rXmlTextWriter.Namespaces = _fNamespaces;
for (rNode = _rDocumentRootNode._rFirstChildNode; rNode != null; rNode = rNode._rNextNode)
{
rNode.Write(rXmlTextWriter);
}
rXmlTextWriter.Dispose();
}
catch (Exception e)
{
DebugTrace(e.ToString());
if (rXmlTextWriter != null)
rXmlTextWriter.Dispose();
throw (e);
}
}
virtual public string Xml
{
get
{
_rBufferWriter.Dispose();
WriteXml(_rBufferWriter);
return _rBufferWriter.ToString();
}
}
public void WriteXml(TextWriter rTW)
{
CXmlBase rNode;
//Spit out the document
for (rNode = _rDocumentRootNode._rFirstChildNode; rNode != null; rNode = rNode._rNextNode)
rNode.WriteXml(rTW);
}
public CXmlNode RootNode
{
get { return _rRootNode; }
}
public string ParseError
{
get { return _strParseError; }
}
public int ParseErrorCode
{
get { return _hr; }
}
//
// XmlReader Properties
//
public string EntityMode
{
set
{
if (value == "ExpandEntities")
_eEntityMode = EntityHandling.ExpandEntities;
else if (value == "ExpandCharEntities")
_eEntityMode = EntityHandling.ExpandCharEntities;
else
throw (new Exception("Invalid Entity mode."));
}
get { return _eEntityMode.ToString(); }
}
public string ValidationMode
{
set
{
#pragma warning disable 0618
if (value == "None")
_eValidationMode = ValidationType.None;
else if (value == "DTD")
_eValidationMode = ValidationType.DTD;
else if (value == "XDR")
_eValidationMode = ValidationType.XDR;
else if (value == "Schema")
_eValidationMode = ValidationType.Schema;
else if (value == "Auto")
_eValidationMode = ValidationType.Auto;
else
throw (new Exception("Invalid Validation mode."));
#pragma warning restore 0618
}
get { return _eValidationMode.ToString(); }
}
public string WhitespaceMode
{
set
{
if (value == "All")
_eWhitespaceMode = WhitespaceHandling.All;
else if (value == "Significant")
_eWhitespaceMode = WhitespaceHandling.Significant;
else if (value == "None")
_eWhitespaceMode = WhitespaceHandling.None;
else
throw (new Exception("Invalid Whitespace mode."));
}
get { return _eWhitespaceMode.ToString(); }
}
public bool Namespaces
{
set { _fNamespaces = value; }
get { return _fNamespaces; }
}
public bool UseValidationCallback
{
set { _fValidationCallback = value; }
get { return _fValidationCallback; }
}
public bool ExpandAttributeValues
{
set { _fExpandAttributeValues = value; }
get { return _fExpandAttributeValues; }
}
//
// Internal Properties
//
public bool Throw
{
get { return _fThrow; }
set { _fThrow = value; }
}
public bool Trace
{
set { _fTrace = value; }
get { return _fTrace; }
}
//
//Private Methods
//
private void DebugTrace(string str)
{
DebugTrace(str, 0);
}
private void DebugTrace(string str, int nDepth)
{
if (_fTrace)
{
int i;
for (i = 0; i < nDepth; i++)
_output.WriteLine(" ");
_output.WriteLine(str);
}
}
private void DebugTrace(XmlReader rXmlReader)
{
if (_fTrace)
{
string str;
str = rXmlReader.NodeType.ToString() + ", Depth=" + rXmlReader.Depth + " Name=";
if (rXmlReader.Prefix != "")
{
str += rXmlReader.Prefix + ":";
}
str += rXmlReader.LocalName;
if (rXmlReader.HasValue)
str += " Value=" + rXmlReader.Value;
if (rXmlReader.NodeType == XmlNodeType.Attribute)
str += " QuoteChar=" + rXmlReader.QuoteChar;
DebugTrace(str, rXmlReader.Depth);
}
}
protected void Process(CXmlBase rParentNode)
{
CXmlNode rNewNode;
while (true)
{
//We want to pop if Read() returns false, aka EOF
if (_fReadNode)
{
if (!_rXmlReader.Read())
{
DebugTrace("Read() == false");
return;
}
}
else
{
if (!_rXmlReader.ReadAttributeValue())
{
DebugTrace("ReadAttributeValue() == false");
return;
}
}
DebugTrace(_rXmlReader);
//We also want to pop if we get an EndElement or EndEntity
if (_rXmlReader.NodeType == XmlNodeType.EndElement ||
_rXmlReader.NodeType == XmlNodeType.EndEntity)
{
DebugTrace("NodeType == EndElement or EndEntity");
return;
}
rNewNode = GetNewNode(_rXmlReader);
rNewNode._nDepth = _rXmlReader.Depth;
// Test for MixedContent and set Indent if necessary
if ((rParentNode.Flags & NodeFlags.MixedContent) != 0)
{
rNewNode._eFlags |= NodeFlags.MixedContent;
// Indent is off for all new nodes
}
else
{
rNewNode._eFlags |= NodeFlags.Indent; // Turn on Indent for current Node
}
// Set all Depth 0 nodes to No Mixed Content and Indent True
if (_rXmlReader.Depth == 0)
{
rNewNode._eFlags |= NodeFlags.Indent; // Turn on Indent
rNewNode._eFlags &= ~NodeFlags.MixedContent; // Turn off MixedContent
}
rParentNode.InsertNode(rNewNode);
//Do some special stuff based on NodeType
switch (_rXmlReader.NodeType)
{
case XmlNodeType.EntityReference:
if (_eValidationMode == ValidationType.DTD)
{
// _rXmlReader.EntityHandling = EntityHandling.ExpandEntities;
_rXmlReader.ResolveEntity();
Process(rNewNode);
// _rXmlReader.EntityHandling = _eEntityMode;
}
break;
case XmlNodeType.Element:
if (_rXmlReader.MoveToFirstAttribute())
{
do
{
CXmlAttribute rNewAttribute = new CXmlAttribute(_rXmlReader);
rNewNode.AddAttribute(rNewAttribute);
if (_fExpandAttributeValues)
{
DebugTrace("Attribute: " + _rXmlReader.Name);
_fReadNode = false;
Process(rNewAttribute);
_fReadNode = true;
}
else
{
CXmlNode rValueNode = new CXmlNode("", "", XmlNodeType.Text);
rValueNode._eFlags = _eDefaultFlags | NodeFlags.HasValue;
rValueNode._strValue = _rXmlReader.Value;
DebugTrace(" Value=" + rValueNode.Value, _rXmlReader.Depth + 1);
rNewAttribute.InsertNode(rValueNode);
}
} while (_rXmlReader.MoveToNextAttribute());
}
if ((rNewNode.Flags & NodeFlags.EmptyElement) == 0)
Process(rNewNode);
break;
case XmlNodeType.XmlDeclaration:
if (_rXmlReader is XmlTextReader)
{
_eEncoding = ((XmlTextReader)_rXmlReader).Encoding;
}
#pragma warning disable 0618
else if (_rXmlReader is XmlValidatingReader)
{
_eEncoding = ((XmlValidatingReader)_rXmlReader).Encoding;
}
#pragma warning restore 0618
else
{
string strValue = rNewNode.NodeValue;
int nPos = strValue.IndexOf("encoding");
if (nPos != -1)
{
int nEnd;
nPos = strValue.IndexOf("=", nPos); //Find the = sign
nEnd = strValue.IndexOf("\"", nPos) + 1; //Find the next " character
nPos = strValue.IndexOf("'", nPos) + 1; //Find the next ' character
if (nEnd == 0 || (nPos < nEnd && nPos > 0)) //Pick the one that's closer to the = sign
{
nEnd = strValue.IndexOf("'", nPos);
}
else
{
nPos = nEnd;
nEnd = strValue.IndexOf("\"", nPos);
}
string sEncodeName = strValue.Substring(nPos, nEnd - nPos);
DebugTrace("XMLDecl contains encoding " + sEncodeName);
if (sEncodeName.ToUpper() == "UCS-2")
{
sEncodeName = "unicode";
}
_eEncoding = System.Text.Encoding.GetEncoding(sEncodeName);
}
}
break;
case XmlNodeType.ProcessingInstruction:
break;
case XmlNodeType.Text:
if (!_fReadNode)
{
rNewNode._eFlags = _eDefaultFlags | NodeFlags.AttributeTextNode;
}
rNewNode._eFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node
rNewNode._eFlags &= ~NodeFlags.Indent; // turn off Indent for current node
rParentNode._eFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
rNewNode._eFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node
rNewNode._eFlags &= ~NodeFlags.Indent; // turn off Indent for current node
rParentNode._eFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node
break;
case XmlNodeType.Comment:
case XmlNodeType.Notation:
break;
case XmlNodeType.DocumentType:
if (_rXmlReader.MoveToFirstAttribute())
{
do
{
CXmlAttribute rNewAttribute = new CXmlAttribute(_rXmlReader);
rNewNode.AddAttribute(rNewAttribute);
CXmlNode rValueNode = new CXmlNode(_rXmlReader);
rValueNode._strValue = _rXmlReader.Value;
rNewAttribute.InsertNode(rValueNode);
} while (_rXmlReader.MoveToNextAttribute());
}
break;
default:
_output.WriteLine("UNHANDLED TYPE, " + _rXmlReader.NodeType.ToString() + " IN Process()!");
break;
}
}
}
protected virtual CXmlNode GetNewNode(XmlReader rXmlReader)
{
return new CXmlNode(rXmlReader);
}
private void ValidationCallback(object sender, ValidationEventArgs args)
{
// commented by ROCHOA -- don't know where ValidationEventArgs comes from
// _hr = Convert.ToInt16(args.ErrorCode);
throw (new Exception("[" + Convert.ToString(_hr) + "] " + args.Message));
}
}
public class ChecksumWriter : TextWriter
{
private int _nPosition = 0;
private Decimal _dResult = 0;
private Encoding _encoding;
// --------------------------------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------------------------------
public ChecksumWriter()
{
_encoding = Encoding.UTF8;
}
// --------------------------------------------------------------------------------------------------
// Properties
// --------------------------------------------------------------------------------------------------
public Decimal CheckSum
{
get { return _dResult; }
}
public override Encoding Encoding
{
get { return _encoding; }
}
// --------------------------------------------------------------------------------------------------
// Public methods
// --------------------------------------------------------------------------------------------------
override public void Write(String str)
{
int i;
int m;
m = str.Length;
for (i = 0; i < m; i++)
{
Write(str[i]);
}
}
override public void Write(Char[] rgch)
{
int i;
int m;
m = rgch.Length;
for (i = 0; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char[] rgch, Int32 iOffset, Int32 iCount)
{
int i;
int m;
m = iOffset + iCount;
for (i = iOffset; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char ch)
{
_dResult += Math.Round((Decimal)(ch / (_nPosition + 1.0)), 10);
_nPosition++;
}
public void Close()
{
_nPosition = 0;
_dResult = 0;
}
}
public class BufferWriter : TextWriter
{
private int _nBufferSize = 0;
private int _nBufferUsed = 0;
private int _nBufferGrow = 1024;
private Char[] _rgchBuffer = null;
private Encoding _encoding;
// --------------------------------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------------------------------
public BufferWriter()
{
_encoding = Encoding.UTF8;
}
// --------------------------------------------------------------------------------------------------
// Properties
// --------------------------------------------------------------------------------------------------
override public string ToString()
{
return new String(_rgchBuffer, 0, _nBufferUsed);
}
public override Encoding Encoding
{
get { return _encoding; }
}
// --------------------------------------------------------------------------------------------------
// Public methods
// --------------------------------------------------------------------------------------------------
override public void Write(String str)
{
int i;
int m;
m = str.Length;
for (i = 0; i < m; i++)
{
Write(str[i]);
}
}
override public void Write(Char[] rgch)
{
int i;
int m;
m = rgch.Length;
for (i = 0; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char[] rgch, Int32 iOffset, Int32 iCount)
{
int i;
int m;
m = iOffset + iCount;
for (i = iOffset; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char ch)
{
if (_nBufferUsed == _nBufferSize)
{
Char[] rgchTemp = new Char[_nBufferSize + _nBufferGrow];
for (_nBufferUsed = 0; _nBufferUsed < _nBufferSize; _nBufferUsed++)
rgchTemp[_nBufferUsed] = _rgchBuffer[_nBufferUsed];
_rgchBuffer = rgchTemp;
_nBufferSize += _nBufferGrow;
if (_nBufferGrow < (1024 * 1024))
_nBufferGrow *= 2;
}
_rgchBuffer[_nBufferUsed++] = ch;
}
public void Close()
{
//Set nBufferUsed to 0, so we start writing from the beginning of the buffer.
_nBufferUsed = 0;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using WebApplication.Models;
using WebApplication.Models.ManageViewModels;
using WebApplication.Services;
namespace WebApplication.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Diagnostics;
using System.DirectoryServices.ActiveDirectory;
using System.IO;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Text;
using System.Xml;
using Microsoft.Deployment.WindowsInstaller;
using WebsitePanel.Setup;
using WebsitePanel.Setup.Internal;
using WebsitePanel.WIXInstaller.Common;
using WebsitePanel.WIXInstaller.Common.Util;
namespace WebsitePanel.WIXInstaller
{
public class CustomActions
{
public static List<string> SysDb = new List<string> { "tempdb", "master", "model", "msdb" };
public const string SQL_AUTH_WINDOWS = "Windows Authentication";
public const string SQL_AUTH_SERVER = "SQL Server Authentication";
#region CustomActions
[CustomAction]
public static ActionResult OnScpa(Session Ctx)
{
PopUpDebugger();
Func<Hashtable, string, string> GetParam = (s, x) => Utils.GetStringSetupParameter(s, x);
Ctx.AttachToSetupLog();
Log.WriteStart("OnScpa");
try
{
var Hash = Ctx.CustomActionData.ToNonGenericDictionary() as Hashtable;
var Scpa = new WebsitePanel.Setup.Actions.ConfigureStandaloneServerAction();
Scpa.ServerSetup = new SetupVariables { };
Scpa.EnterpriseServerSetup = new SetupVariables { };
Scpa.PortalSetup = new SetupVariables { };
Scpa.EnterpriseServerSetup.ServerAdminPassword = GetParam(Hash, "ServerAdminPassword");
Scpa.EnterpriseServerSetup.PeerAdminPassword = Scpa.EnterpriseServerSetup.ServerAdminPassword;
Scpa.PortalSetup.InstallerFolder = GetParam(Hash, "InstallerFolder");
Scpa.PortalSetup.ComponentId = WiXSetup.GetComponentID(Scpa.PortalSetup);
AppConfig.LoadConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = WiXSetup.GetFullConfigPath(Scpa.PortalSetup) });
Scpa.PortalSetup.EnterpriseServerURL = GetParam(Hash, "EnterpriseServerUrl");
Scpa.PortalSetup.WebSiteIP = GetParam(Hash, "PortalWebSiteIP");
Scpa.ServerSetup.WebSiteIP = GetParam(Hash, "ServerWebSiteIP");
Scpa.ServerSetup.WebSitePort = GetParam(Hash, "ServerWebSitePort");
Scpa.ServerSetup.ServerPassword = GetParam(Hash, "ServerPassword");
var Make = Scpa as WebsitePanel.Setup.Actions.IInstallAction;
Make.Run(null);
}
catch (Exception ex)
{
Log.WriteError(ex.ToString());
}
Log.WriteEnd("OnScpa");
return ActionResult.Success;
}
[CustomAction]
public static ActionResult OnServerPrepare(Session Ctx)
{
PopUpDebugger();
Ctx.AttachToSetupLog();
Log.WriteStart("OnServerPrepare");
GetPrepareScript(Ctx).Run();
Log.WriteEnd("OnServerPrepare");
return ActionResult.Success;
}
[CustomAction]
public static ActionResult OnEServerPrepare(Session Ctx)
{
PopUpDebugger();
Ctx.AttachToSetupLog();
Log.WriteStart("OnEServerPrepare");
GetPrepareScript(Ctx).Run();
Log.WriteEnd("OnEServerPrepare");
return ActionResult.Success;
}
[CustomAction]
public static ActionResult OnPortalPrepare(Session Ctx)
{
PopUpDebugger();
Ctx.AttachToSetupLog();
Log.WriteStart("OnPortalPrepare");
GetPrepareScript(Ctx).Run();
Log.WriteEnd("OnPortalPrepare");
return ActionResult.Success;
}
[CustomAction]
public static ActionResult OnSchedulerPrepare(Session Ctx)
{
PopUpDebugger();
Ctx.AttachToSetupLog();
Log.WriteStart("OnSchedulerPrepare");
try
{
var ServiceName = Global.Parameters.SchedulerServiceName;
var ServiceFile = string.Empty;
ManagementClass WmiService = new ManagementClass("Win32_Service");
foreach (var MObj in WmiService.GetInstances())
{
if (MObj.GetPropertyValue("Name").ToString().Equals(ServiceName, StringComparison.CurrentCultureIgnoreCase))
{
ServiceFile = MObj.GetPropertyValue("PathName").ToString();
break;
}
}
if (!string.IsNullOrWhiteSpace(ServiceName) && !string.IsNullOrWhiteSpace(ServiceFile))
{
var CtxVars = new SetupVariables() { ServiceName = ServiceName, ServiceFile = ServiceFile };
var Script = new BackupSchedulerScript(CtxVars);
Script.Actions.Add(new InstallAction(ActionTypes.UnregisterWindowsService)
{
Name = ServiceName,
Path = ServiceFile,
Description = "Removing Windows service...",
Log = string.Format("- Remove {0} Windows service", ServiceName)
});
Script.Context.ServiceName = Global.Parameters.SchedulerServiceName;
Script.Run();
}
}
catch (Exception ex)
{
Log.WriteError(ex.ToString());
}
Log.WriteEnd("OnSchedulerPrepare");
return ActionResult.Success;
}
[CustomAction]
public static ActionResult MaintenanceServer(Session session)
{
PopUpDebugger();
var Result = ActionResult.Success;
Log.WriteStart("MaintenanceServer");
Result = ProcessInstall(session, WiXInstallType.MaintenanceServer);
Log.WriteEnd("MaintenanceServer");
return Result;
}
[CustomAction]
public static ActionResult MaintenanceEServer(Session session)
{
PopUpDebugger();
var Result = ActionResult.Success;
Log.WriteStart("MaintenanceEServer");
Result = ProcessInstall(session, WiXInstallType.MaintenanceEnterpriseServer);
Log.WriteEnd("MaintenanceEServer");
return Result;
}
[CustomAction]
public static ActionResult MaintenancePortal(Session session)
{
PopUpDebugger();
var Result = ActionResult.Success;
Log.WriteStart("MaintenancePortal");
Result = ProcessInstall(session, WiXInstallType.MaintenancePortal);
Log.WriteEnd("MaintenancePortal");
return Result;
}
[CustomAction]
public static ActionResult PreFillSettings(Session session)
{
Func<string, bool> HaveInstalledComponents = (string CfgFullPath) =>
{
var ComponentsPath = "//components";
return File.Exists(CfgFullPath) ? BackupRestore.HaveChild(CfgFullPath, ComponentsPath) : false;
};
Func<IEnumerable<string>, string> FindMainConfig = (IEnumerable<string> Dirs) =>
{
// Looking into directories with next priority:
// Previous installation directory and her backup, "WebsitePanel" directories on fixed drives and their backups.
// The last chance is an update from an installation based on previous installer version that installed to "Program Files".
// Regular directories.
foreach (var Dir in Dirs)
{
var Result = Path.Combine(Dir, BackupRestore.MainConfig);
if (HaveInstalledComponents(Result))
{
return Result;
}
else
{
var ComponentNames = new string[] { Global.Server.ComponentName, Global.EntServer.ComponentName, Global.WebPortal.ComponentName };
foreach (var Name in ComponentNames)
{
var Backup = BackupRestore.Find(Dir, Global.DefaultProductName, Name);
if (Backup != null && HaveInstalledComponents(Backup.BackupMainConfigFile))
return Backup.BackupMainConfigFile;
}
}
}
// Looking into platform specific Program Files.
{
var InstallerMainCfg = "WebsitePanel.Installer.exe.config";
var InstallerName = "WebsitePanel Installer";
var PFolderType = Environment.Is64BitOperatingSystem ? Environment.SpecialFolder.ProgramFilesX86 : Environment.SpecialFolder.ProgramFiles;
var PFiles = Environment.GetFolderPath(PFolderType);
var Result = Path.Combine(PFiles, InstallerName, InstallerMainCfg);
if (HaveInstalledComponents(Result))
return Result;
}
return null;
};
Action<Session, SetupVariables> VersionGuard = (Session SesCtx, SetupVariables CtxVars) =>
{
var Current = SesCtx["ProductVersion"];
var Found = string.IsNullOrWhiteSpace(CtxVars.Version) ? "0.0.0" : CtxVars.Version;
if ((new Version(Found) > new Version(Current)) && !CtxVars.InstallerType.ToLowerInvariant().Equals("msi"))
throw new InvalidOperationException("New version must be greater than previous always.");
};
Func<string, string> NormalizeDir = (string Dir) =>
{
string nds = Path.DirectorySeparatorChar.ToString();
string ads = Path.AltDirectorySeparatorChar.ToString();
var Result = Dir.Trim();
if (!Result.EndsWith(nds) && !Result.EndsWith(ads))
{
if (Result.Contains(nds))
Result += nds;
else
Result += ads;
}
return Result;
};
try
{
var Ctx = session;
Ctx.AttachToSetupLog();
PopUpDebugger();
Log.WriteStart("PreFillSettings");
TryApllyNewPassword(Ctx, "PI_SERVER_PASSWORD");
TryApllyNewPassword(Ctx, "PI_ESERVER_PASSWORD");
TryApllyNewPassword(Ctx, "PI_PORTAL_PASSWORD");
var WSP = Ctx["WSP_INSTALL_DIR"];
var DirList = new List<string>();
DirList.Add(WSP);
DirList.AddRange(from Drive in DriveInfo.GetDrives()
where Drive.DriveType == DriveType.Fixed
select Path.Combine(Drive.RootDirectory.FullName, Global.DefaultProductName));
var CfgPath = FindMainConfig(DirList);
if (!string.IsNullOrWhiteSpace(CfgPath))
{
try
{
var EServerUrl = string.Empty;
AppConfig.LoadConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = CfgPath });
var CtxVars = new SetupVariables();
CtxVars.ComponentId = WiXSetup.GetComponentID(CfgPath, Global.Server.ComponentCode);
if (!string.IsNullOrWhiteSpace(CtxVars.ComponentId))
{
AppConfig.LoadComponentSettings(CtxVars);
VersionGuard(Ctx, CtxVars);
SetProperty(Ctx, "COMPFOUND_SERVER_ID", CtxVars.ComponentId);
SetProperty(Ctx, "COMPFOUND_SERVER_MAIN_CFG", CfgPath);
SetProperty(Ctx, "PI_SERVER_IP", CtxVars.WebSiteIP);
SetProperty(Ctx, "PI_SERVER_PORT", CtxVars.WebSitePort);
SetProperty(Ctx, "PI_SERVER_HOST", CtxVars.WebSiteDomain);
SetProperty(Ctx, "PI_SERVER_LOGIN", CtxVars.UserAccount);
SetProperty(Ctx, "PI_SERVER_DOMAIN", CtxVars.UserDomain);
SetProperty(Ctx, "PI_SERVER_INSTALL_DIR", CtxVars.InstallFolder);
SetProperty(Ctx, "WSP_INSTALL_DIR", NormalizeDir(new DirectoryInfo(CtxVars.InstallFolder).Parent.FullName));
Ctx["SERVER_ACCESS_PASSWORD"] = string.Empty;
Ctx["SERVER_ACCESS_PASSWORD_CONFIRM"] = string.Empty;
var HaveAccount = SecurityUtils.UserExists(CtxVars.UserDomain, CtxVars.UserAccount);
bool HavePool = Tool.AppPoolExists(CtxVars.ApplicationPool);
Ctx["COMPFOUND_SERVER"] = (HaveAccount && HavePool) ? YesNo.Yes : YesNo.No;
}
CtxVars.ComponentId = WiXSetup.GetComponentID(CfgPath, Global.EntServer.ComponentCode);
if (!string.IsNullOrWhiteSpace(CtxVars.ComponentId))
{
AppConfig.LoadComponentSettings(CtxVars);
VersionGuard(Ctx, CtxVars);
SetProperty(Ctx, "COMPFOUND_ESERVER_ID", CtxVars.ComponentId);
SetProperty(Ctx, "COMPFOUND_ESERVER_MAIN_CFG", CfgPath);
SetProperty(Ctx, "PI_ESERVER_IP", CtxVars.WebSiteIP);
SetProperty(Ctx, "PI_ESERVER_PORT", CtxVars.WebSitePort);
SetProperty(Ctx, "PI_ESERVER_HOST", CtxVars.WebSiteDomain);
SetProperty(Ctx, "PI_ESERVER_LOGIN", CtxVars.UserAccount);
SetProperty(Ctx, "PI_ESERVER_DOMAIN", CtxVars.UserDomain);
EServerUrl = string.Format("http://{0}:{1}", CtxVars.WebSiteIP, CtxVars.WebSitePort);
SetProperty(Ctx, "PI_ESERVER_INSTALL_DIR", CtxVars.InstallFolder);
SetProperty(Ctx, "WSP_INSTALL_DIR", NormalizeDir(new DirectoryInfo(CtxVars.InstallFolder).Parent.FullName));
var ConnStr = new SqlConnectionStringBuilder(CtxVars.DbInstallConnectionString);
SetProperty(Ctx, "DB_CONN", ConnStr.ToString());
SetProperty(Ctx, "DB_SERVER", ConnStr.DataSource);
SetProperty(Ctx, "DB_AUTH", ConnStr.IntegratedSecurity ? SQL_AUTH_WINDOWS : SQL_AUTH_SERVER);
if (!ConnStr.IntegratedSecurity)
{
SetProperty(Ctx, "DB_LOGIN", ConnStr.UserID);
SetProperty(Ctx, "DB_PASSWORD", ConnStr.Password);
}
ConnStr = new SqlConnectionStringBuilder(CtxVars.ConnectionString);
SetProperty(Ctx, "DB_DATABASE", ConnStr.InitialCatalog);
SetProperty(Ctx, "PI_ESERVER_CONN_STR", ConnStr.ToString());
SetProperty(Ctx, "PI_ESERVER_CRYPTO_KEY", CtxVars.CryptoKey);
try
{
var SqlQuery = string.Format("USE [{0}]; SELECT [dbo].[Users].[Password] FROM [dbo].[Users] WHERE [dbo].[Users].[UserID] = 1;", ConnStr.InitialCatalog);
using (var Reader = SqlUtils.ExecuteSql(CtxVars.DbInstallConnectionString, SqlQuery).CreateDataReader())
{
if (Reader.Read())
{
var Hash = Reader[0].ToString();
var Password = IsEnctyptionEnabled(string.Format(@"{0}\Web.config", CtxVars.InstallationFolder)) ? Utils.Decrypt(CtxVars.CryptoKey, Hash) : Hash;
Ctx["SERVERADMIN_PASSWORD"] = Password;
Ctx["SERVERADMIN_PASSWORD_CONFIRM"] = Password;
}
}
}
catch
{
// Nothing to do.
}
var HaveAccount = SecurityUtils.UserExists(CtxVars.UserDomain, CtxVars.UserAccount);
bool HavePool = Tool.AppPoolExists(CtxVars.ApplicationPool);
Ctx["COMPFOUND_ESERVER"] = (HaveAccount && HavePool) ? YesNo.Yes : YesNo.No;
}
CtxVars.ComponentId = WiXSetup.GetComponentID(CfgPath, Global.WebPortal.ComponentCode);
if (!string.IsNullOrWhiteSpace(CtxVars.ComponentId))
{
AppConfig.LoadComponentSettings(CtxVars);
VersionGuard(Ctx, CtxVars);
SetProperty(Ctx, "COMPFOUND_PORTAL_ID", CtxVars.ComponentId);
SetProperty(Ctx, "COMPFOUND_PORTAL_MAIN_CFG", CfgPath);
SetProperty(Ctx, "PI_PORTAL_IP", CtxVars.WebSiteIP);
SetProperty(Ctx, "PI_PORTAL_PORT", CtxVars.WebSitePort);
SetProperty(Ctx, "PI_PORTAL_HOST", CtxVars.WebSiteDomain);
SetProperty(Ctx, "PI_PORTAL_LOGIN", CtxVars.UserAccount);
SetProperty(Ctx, "PI_PORTAL_DOMAIN", CtxVars.UserDomain);
if (!SetProperty(Ctx, "PI_ESERVER_URL", CtxVars.EnterpriseServerURL))
if (!SetProperty(Ctx, "PI_ESERVER_URL", EServerUrl))
SetProperty(Ctx, "PI_ESERVER_URL", Global.WebPortal.DefaultEntServURL);
SetProperty(Ctx, "PI_PORTAL_INSTALL_DIR", CtxVars.InstallFolder);
SetProperty(Ctx, "WSP_INSTALL_DIR", NormalizeDir(new DirectoryInfo(CtxVars.InstallFolder).Parent.FullName));
var HaveAccount = SecurityUtils.UserExists(CtxVars.UserDomain, CtxVars.UserAccount);
bool HavePool = Tool.AppPoolExists(CtxVars.ApplicationPool);
Ctx["COMPFOUND_PORTAL"] = (HaveAccount && HavePool) ? YesNo.Yes : YesNo.No;
}
CtxVars.ComponentId = WiXSetup.GetComponentID(CfgPath, Global.Scheduler.ComponentCode);
var HaveComponentId = !string.IsNullOrWhiteSpace(CtxVars.ComponentId);
var HaveSchedulerService = ServiceController.GetServices().Any(x => x.DisplayName.Equals(Global.Parameters.SchedulerServiceName, StringComparison.CurrentCultureIgnoreCase));
var EServerConnStr = Ctx["PI_ESERVER_CONN_STR"];
var HaveConn = !string.IsNullOrWhiteSpace(EServerConnStr);
if (HaveComponentId || HaveSchedulerService || HaveConn)
{
Ctx["COMPFOUND_SCHEDULER"] = YesNo.No;
try
{
SqlConnectionStringBuilder ConnInfo = null;
if (HaveComponentId)
{
AppConfig.LoadComponentSettings(CtxVars);
VersionGuard(Ctx, CtxVars);
SetProperty(Ctx, "COMPFOUND_SCHEDULER_ID", CtxVars.ComponentId);
SetProperty(Ctx, "COMPFOUND_SCHEDULER_MAIN_CFG", CfgPath);
SetProperty(Ctx, "PI_SCHEDULER_CRYPTO_KEY", CtxVars.CryptoKey);
ConnInfo = new SqlConnectionStringBuilder(CtxVars.ConnectionString);
}
else if (HaveConn)
{
SetProperty(Ctx, "PI_SCHEDULER_CRYPTO_KEY", Ctx["PI_ESERVER_CRYPTO_KEY"]);
ConnInfo = new SqlConnectionStringBuilder(EServerConnStr);
}
if(ConnInfo != null)
{
SetProperty(Ctx, "PI_SCHEDULER_DB_SERVER", ConnInfo.DataSource);
SetProperty(Ctx, "PI_SCHEDULER_DB_DATABASE", ConnInfo.InitialCatalog);
SetProperty(Ctx, "PI_SCHEDULER_DB_LOGIN", ConnInfo.UserID);
SetProperty(Ctx, "PI_SCHEDULER_DB_PASSWORD", ConnInfo.Password);
}
Ctx["COMPFOUND_SCHEDULER"] = HaveSchedulerService? YesNo.Yes : YesNo.No;
}
catch (Exception ex)
{
Log.WriteError("Detection of existing Scheduler Service failed.", ex);
}
}
}
catch (InvalidOperationException ioex)
{
Log.WriteError(ioex.ToString());
var Text = new Record(1);
Text.SetString(0, ioex.Message);
Ctx.Message(InstallMessage.Error, Text);
return ActionResult.Failure;
}
}
}
catch (Exception ex)
{
Log.WriteError(ex.ToString());
return ActionResult.Failure;
}
Log.WriteEnd("PreFillSettings");
return ActionResult.Success;
}
[CustomAction]
public static ActionResult InstallWebFeatures(Session session)
{
PopUpDebugger();
var Ctx = session;
Ctx.AttachToSetupLog();
Log.WriteStart("InstallWebFeatures");
var Result = ActionResult.Success;
var Scheduled = Ctx.GetMode(InstallRunMode.Scheduled);
var Components = new List<string>();
var InstallIis = false;
var InstallAspNet = false;
var InstallNetFx3 = false;
if (Scheduled)
{
InstallIis = Ctx.CustomActionData["PI_PREREQ_IIS_INSTALL"] != YesNo.No;
InstallAspNet = Ctx.CustomActionData["PI_PREREQ_ASPNET_INSTALL"] != YesNo.No;
InstallNetFx3 = Ctx.CustomActionData["PI_PREREQ_NETFX_INSTALL"] != YesNo.No;
}
else
{
InstallIis = Ctx["PI_PREREQ_IIS_INSTALL"] != YesNo.No;
InstallAspNet = Ctx["PI_PREREQ_ASPNET_INSTALL"] != YesNo.No;
InstallNetFx3 = Ctx["PI_PREREQ_NETFX_INSTALL"] != YesNo.No;
}
if (InstallIis)
Components.AddRange(Tool.GetWebRoleComponents());
if (InstallAspNet)
Components.AddRange(Tool.GetWebDevComponents());
if (InstallNetFx3)
Components.AddRange(Tool.GetNetFxComponents());
if (Scheduled)
{
Action<int, int> ProgressReset = (int Total, int Mode) =>
{
using (var Tmp = new Record(4))
{
Tmp.SetInteger(1, 0);
Tmp.SetInteger(2, Total);
Tmp.SetInteger(3, 0);
Tmp.SetInteger(4, Mode);
Ctx.Message(InstallMessage.Progress, Tmp);
}
};
Action<int> ProgressIncrement = (int Value) =>
{
using (var Tmp = new Record(2))
{
Tmp.SetInteger(1, 2);
Tmp.SetInteger(2, Value);
Ctx.Message(InstallMessage.Progress, Tmp);
}
};
Action<string> ProgressText = (string Text) =>
{
using (var Tmp = new Record(2))
{
Tmp.SetString(1, "CA_InstallWebFeaturesDeferred");
Tmp.SetString(2, Text);
Ctx.Message(InstallMessage.ActionStart, Tmp);
}
};
var Frmt = "Installing web component the {0} a {1} of {2}";
Log.WriteStart("InstallWebFeatures: components");
ProgressReset(Components.Count + 1, 0);
ProgressText("Installing necessary web components ...");
var Msg = new StringBuilder();
try
{
InstallToolDelegate InstallTool = Tool.GetInstallTool();
if (InstallTool == null)
throw new ApplicationException("Install tool for copmonents is not found.");
for (int i = 0; i < Components.Count; i ++)
{
var Component = Components[i];
ProgressText(string.Format(Frmt, Component, i + 1, Components.Count));
ProgressIncrement(1);
Msg.AppendLine(InstallTool(Component));
}
if (InstallAspNet)
Tool.PrepareAspNet();
Log.WriteInfo("InstallWebFeatures: done.");
}
catch (Exception ex)
{
Log.WriteError(string.Format("InstallWebFeatures: fail - {0}.", ex.ToString()));
Result = ActionResult.Failure;
}
finally
{
ProgressReset(Components.Count * 3 + 1, 0);
if (Msg.Length > 0)
Log.WriteInfo(string.Format("InstallWebFeatures Tool Log: {0}.", Msg.ToString()));
Log.WriteEnd("InstallWebFeatures: components");
}
}
else
{
Log.WriteStart("InstallWebFeatures: prepare");
using (var ProgressRecord = new Record(2))
{
ProgressRecord.SetInteger(1, 3);
ProgressRecord.SetInteger(2, Components.Count);
Ctx.Message(InstallMessage.Progress, ProgressRecord);
}
Log.WriteEnd("InstallWebFeatures: prepare");
}
Log.WriteEnd("InstallWebFeatures");
return Result;
}
// Install.
[CustomAction]
public static ActionResult OnServerInstall(Session session)
{
PopUpDebugger();
return ProcessInstall(session, WiXInstallType.InstallServer);
}
[CustomAction]
public static ActionResult OnEServerInstall(Session session)
{
PopUpDebugger();
return ProcessInstall(session, WiXInstallType.InstallEnterpriseServer);
}
[CustomAction]
public static ActionResult OnPortalInstall(Session session)
{
PopUpDebugger();
return ProcessInstall(session, WiXInstallType.InstallPortal);
}
[CustomAction]
public static ActionResult OnSchedulerInstall(Session session)
{
PopUpDebugger();
return ProcessInstall(session, WiXInstallType.InstallScheduler);
}
// Remove.
[CustomAction]
public static ActionResult OnServerRemove(Session session)
{
PopUpDebugger();
return ProcessInstall(session, WiXInstallType.RemoveServer);
}
[CustomAction]
public static ActionResult OnEServerRemove(Session session)
{
PopUpDebugger();
return ProcessInstall(session, WiXInstallType.RemoveEnterpriseServer);
}
[CustomAction]
public static ActionResult OnPortalRemove(Session session)
{
PopUpDebugger();
return ProcessInstall(session, WiXInstallType.RemovePortal);
}
[CustomAction]
public static ActionResult OnSchedulerRemove(Session session)
{
PopUpDebugger();
return ProcessInstall(session, WiXInstallType.RemoveScheduler);
}
// Other.
[CustomAction]
public static ActionResult SetEServerUrlUI(Session session)
{
var Ctx = session;
Ctx["PI_ESERVER_URL"] = string.Format("http://{0}:{1}/", Ctx["PI_ESERVER_IP"], Ctx["PI_ESERVER_PORT"]);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult RecapListUI(Session session)
{
const string F_WSP = "WebsitePanel";
const string F_Server = "ServerFeature";
const string F_EServer = "EnterpriseServerFeature";
const string F_Portal = "PortalFeature";
const string F_Scheduler = "SchedulerServiceFeature";
const string F_WDPosrtal = "WDPortalFeature";
var S_Install = new List<string> { "Copy WebsitePanel Server files", "Add WebsitePanel Server website" };
var ES_Install = new List<string> { "Copy WebsitePanel Enterprise Server files", "Install WebsitePanel database and updates", "Add WebsitePanel Enterprise Server website" };
var P_Install = new List<string> { "Copy WebsitePanel Portal files", "Add WebsitePanel Enterprise Portal website" };
var SCH_Install = new List<string> { "Copy WebsitePanel Scheduler Service files", "Install Scheduler Service Windows Service" };
var WDP_Install = new List<string> { "Copy WebsitePanel WebDav Portal files" };
var S_Uninstall = new List<string> { "Delete WebsitePanel Server files", "Remove WebsitePanel Server website" };
var ES_Uninstall = new List<string> { "Delete WebsitePanel Enterprise Server files", "Keep WebsitePanel database and updates", "Remove WebsitePanel Enterprise Server website" };
var P_Uninstall = new List<string> { "Delete WebsitePanel Portal files", "Remove WebsitePanel Enterprise Portal website" };
var SCH_Uninstall = new List<string> { "Delete WebsitePanel Scheduler Service files", "Remove Scheduler Service Windows Service" };
var WDP_Uninstall = new List<string> { "Delete WebsitePanel WebDav Portal files" };
var RecapList = new List<string>();
var EmptyList = new List<string>();
var Ctx = session;
RecapListReset(Ctx);
foreach (var Feature in Ctx.Features)
{
switch (Feature.Name)
{
case F_WSP:
break;
case F_Server:
RecapList.AddRange(Feature.RequestState == InstallState.Local ? S_Install : /*S_Uninstall*/ EmptyList);
break;
case F_EServer:
RecapList.AddRange(Feature.RequestState == InstallState.Local ? ES_Install : /*ES_Uninstall*/ EmptyList);
break;
case F_Portal:
RecapList.AddRange(Feature.RequestState == InstallState.Local ? P_Install : /*P_Uninstall*/ EmptyList);
break;
case F_Scheduler:
RecapList.AddRange(Feature.RequestState == InstallState.Local ? SCH_Install : /*SCH_Uninstall*/ EmptyList);
break;
case F_WDPosrtal:
RecapList.AddRange(Feature.RequestState == InstallState.Local ? WDP_Install : /*WDP_Uninstall*/ EmptyList);
break;
default:
break;
}
}
RecapListAdd(Ctx, RecapList.ToArray());
return ActionResult.Success;
}
[CustomAction]
public static ActionResult DatabaseConnectionValidateUI(Session session)
{
var Ctx = session;
bool Valid = true;
string Msg;
ValidationReset(Ctx);
Valid = ValidateDbNameUI(Ctx, out Msg);
ValidationMsg(Ctx, Msg);
ValidationStatus(Ctx, Valid);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult SchedulerValidateUI(Session session)
{
var Ctx = session;
bool Valid = true;
string Msg;
ValidationReset(Ctx);
Valid = ValidateCryptoKeyUI(Ctx, out Msg);
ValidationMsg(Ctx, Msg);
ValidationStatus(Ctx, Valid);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult ServerAdminValidateUI(Session session)
{
var Ctx = session;
bool Valid = true;
string Msg;
ValidationReset(Ctx);
Valid = ValidatePasswordUI(Ctx, "SERVERADMIN", out Msg);
ValidationMsg(Ctx, Msg);
ValidationStatus(Ctx, Valid);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult ServerValidateADUI(Session session)
{
var Ctx = session;
bool Valid = true;
string Msg;
ValidationReset(Ctx);
Valid = ValidateADUI(Ctx, "PI_SERVER", out Msg);
ValidationMsg(Ctx, Msg);
ValidationStatus(Ctx, Valid);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult EServerValidateADUI(Session session)
{
var Ctx = session;
bool Valid = true;
string Msg;
ValidationReset(Ctx);
Valid = ValidateADUI(Ctx, "PI_ESERVER", out Msg);
ValidationMsg(Ctx, Msg);
ValidationStatus(Ctx, Valid);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult PortalValidateADUI(Session session)
{
var Ctx = session;
bool Valid = true;
string Msg;
ValidationReset(Ctx);
Valid = ValidateADUI(Ctx, "PI_PORTAL", out Msg);
ValidationMsg(Ctx, Msg);
ValidationStatus(Ctx, Valid);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult ServerAccessValidateUI(Session session)
{
var Ctx = session;
bool Valid = true;
string Msg;
ValidationReset(Ctx);
Valid = ValidatePasswordUI(Ctx, "SERVER_ACCESS", out Msg);
ValidationMsg(Ctx, Msg);
ValidationStatus(Ctx, Valid);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult ServerAccessValidateMtnUI(Session session)
{
var Ctx = session;
bool Valid = true;
string Msg;
ValidationReset(Ctx);
Valid = ValidateEqualPasswordUI(Ctx, "SERVER_ACCESS", out Msg);
ValidationMsg(Ctx, Msg);
ValidationStatus(Ctx, Valid);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult FillDomainListUI(Session Ctx)
{
try
{
var Ctrls = new[]{ new ComboBoxCtrl(Ctx, "PI_SERVER_DOMAIN"),
new ComboBoxCtrl(Ctx, "PI_ESERVER_DOMAIN"),
new ComboBoxCtrl(Ctx, "PI_PORTAL_DOMAIN") };
using (var f = Forest.GetCurrentForest())
{
foreach (Domain d in f.Domains)
foreach (var Ctrl in Ctrls)
Ctrl.AddItem(d.Name);
}
}
catch
{
// Nothing to do.
}
return ActionResult.Success;
}
[CustomAction]
public static ActionResult SqlServerListUI(Session session)
{
var Ctx = session;
var SrvList = new ComboBoxCtrl(Ctx, "DB_SERVER");
foreach (var Srv in GetSqlInstances())
SrvList.AddItem(Srv);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult DbListUI(Session session)
{
string tmp;
var Ctrl = new ComboBoxCtrl(session, "DB_SELECT");
if (Adapter.CheckConnectionInfo(session["DB_CONN"], out tmp))
foreach (var Db in GetDbList(ConnStr: session["DB_CONN"], ForbiddenNames: SysDb))
{
Ctrl.AddItem(Db);
session["DB_SELECT"] = Db; // Adds available DBs to installer log and selects latest.
}
else
session["DB_SELECT"] = "";
return ActionResult.Success;
}
[CustomAction]
public static ActionResult CheckConnectionSchedulerUI(Session Ctx)
{
PopUpDebugger();
Ctx.AttachToSetupLog();
Log.WriteStart("CheckConnectionSchedulerUI");
var Result = default(bool);
var Msg = default(string);
var DbServer = Ctx["PI_SCHEDULER_DB_SERVER"];
var DbUser = Ctx["PI_SCHEDULER_DB_LOGIN"];
var DbPass = Ctx["PI_SCHEDULER_DB_PASSWORD"];
var DbBase = Ctx["PI_SCHEDULER_DB_DATABASE"];
if (new string[] { DbServer, DbUser, DbPass, DbBase }.Any(x => string.IsNullOrWhiteSpace(x)))
Msg = "Please check all fields again.";
else
Result = Adapter.CheckSql(new SetupVariables { InstallConnectionString = GetConnectionString(DbServer, DbBase, DbUser, DbPass) }, out Msg) == CheckStatuses.Success;
Ctx["DB_CONN_CORRECT"] = Result ? YesNo.Yes : YesNo.No;
Ctx["DB_CONN_MSG"] = string.Format(Result ? "Success. {0}" : "Error. {0}", Msg);
Log.WriteEnd("CheckConnectionSchedulerUI");
return ActionResult.Success;
}
[CustomAction]
public static ActionResult CheckConnectionUI(Session session)
{
string Msg = default(string);
string ConnStr = session["DB_AUTH"].Equals(SQL_AUTH_WINDOWS) ? GetConnectionString(session["DB_SERVER"], "master") :
GetConnectionString(session["DB_SERVER"], "master", session["DB_LOGIN"], session["DB_PASSWORD"]);
var Result = Adapter.CheckSql(new SetupVariables { InstallConnectionString = ConnStr }, out Msg) == CheckStatuses.Success;
session["DB_CONN_CORRECT"] = Result ? YesNo.Yes : YesNo.No;
session["DB_CONN"] = Result ? ConnStr : "";
session["DB_CONN_MSG"] = string.Format(Result? "Success. {0}" : "Error. {0}", Msg);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult GetDbSkip(Session Ctx)
{
PopUpDebugger();
Ctx.AttachToSetupLog();
Log.WriteStart("GetDbSkip");
var ConnStr = Ctx["DB_CONN"];
var DbName = Ctx["DB_DATABASE"];
var Tmp = Adapter.SkipCreateDb(ConnStr, DbName) ? YesNo.Yes : YesNo.No;
Log.WriteInfo("DB_SKIP_CREATE is " + Tmp);
Ctx["DB_SKIP_CREATE"] = Tmp;
Log.WriteEnd("GetDbSkip");
return ActionResult.Success;
}
[CustomAction]
public static ActionResult PrereqCheck(Session session)
{
var SecMsg = "You do not have the appropriate permissions to perform this operation. Make sure you are running the application from the local disk and you have local system administrator privileges.";
var NetMsg = "Microsoft .NET {0} is {1}.";
Action<string> ShowMsg = (string Text) =>
{
using(var Rec = new Record(0))
{
Rec.SetString(0, Text);
session.Message(InstallMessage.Error, Rec);
}
};
Action<Session, string, string> FxLog = (Session SesCtx, string Ver, string StrVer) =>
{
if (YesNo.Get(session[Ver]) == YesNo.Yes)
AddLog(SesCtx, string.Format(NetMsg, StrVer, "available"));
else
AddLog(SesCtx, string.Format(NetMsg, StrVer, "not available"));
};
if (!Adapter.CheckSecurity() || !Adapter.IsAdministrator())
{
ShowMsg(SecMsg);
return ActionResult.Failure;
}
string Msg;
var Ctx = Tool.GetSetupVars(session);
var ros = Adapter.CheckOS(Ctx, out Msg);
AddLog(session, Msg);
var riis = Adapter.CheckIIS(Ctx, out Msg);
AddLog(session, Msg);
var raspnet = Adapter.CheckASPNET(Ctx, out Msg);
AddLog(session, Msg);
session[Prop.REQ_OS] = ros == CheckStatuses.Success ? YesNo.Yes : YesNo.No;
session[Prop.REQ_IIS] = riis == CheckStatuses.Success ? YesNo.Yes : YesNo.No; ;
session[Prop.REQ_ASPNET] = raspnet == CheckStatuses.Success ? YesNo.Yes : YesNo.No; ;
FxLog(session, Prop.REQ_NETFRAMEWORK20, "2.0");
FxLog(session, Prop.REQ_NETFRAMEWORK35, "3.5");
FxLog(session, Prop.REQ_NETFRAMEWORK40FULL, "4.0");
return ActionResult.Success;
}
[CustomAction]
public static ActionResult PrereqCheckUI(Session session)
{
var ListView = new ListViewCtrl(session, "REQCHECKLIST");
AddCheck(ListView, session, Prop.REQ_NETFRAMEWORK20);
AddCheck(ListView, session, Prop.REQ_NETFRAMEWORK35);
AddCheck(ListView, session, Prop.REQ_NETFRAMEWORK40FULL);
AddCheck(ListView, session, Prop.REQ_OS);
AddCheck(ListView, session, Prop.REQ_IIS);
AddCheck(ListView, session, Prop.REQ_ASPNET);
return ActionResult.Success;
}
[CustomAction]
public static ActionResult FillIpListUI(Session session)
{
PopUpDebugger();
var Ctrls = new[]{ new ComboBoxCtrl(session, "PI_SERVER_IP"),
new ComboBoxCtrl(session, "PI_ESERVER_IP"),
new ComboBoxCtrl(session, "PI_PORTAL_IP") };
foreach (var Ip in GetIpList())
foreach (var Ctrl in Ctrls)
Ctrl.AddItem(Ip);
return ActionResult.Success;
}
#endregion
private static string GetConnectionString(string serverName, string databaseName, string login = null, string password = null)
{
return SqlUtils.BuildDbServerConnectionString(serverName, databaseName, login, password);
}
private static void AddCheck(ListViewCtrl view, Session session, string PropertyID)
{
view.AddItem(YesNo.Get(session[PropertyID]) != YesNo.No, session[PropertyID + "_TITLE"]);
}
static IList<string> GetSqlInstances()
{
var Result = new List<string>();
using (var Src = SqlDataSourceEnumerator.Instance.GetDataSources())
{
foreach (DataRow Row in Src.Rows)
{
var Instance = Row["InstanceName"].ToString();
Result.Add((string.IsNullOrWhiteSpace(Instance) ? "" : (Instance + "\\")) + Row["ServerName"].ToString());
}
}
return Result;
}
static IEnumerable<string> GetDbList(string ConnStr, IList<string> ForbiddenNames = null)
{
using (var Conn = new SqlConnection(ConnStr))
{
Conn.Open();
var Cmd = Conn.CreateCommand();
Cmd.CommandText = "SELECT name FROM master..sysdatabases";
if (ForbiddenNames != null && ForbiddenNames.Count > 0)
Cmd.CommandText += string.Format(" WHERE name NOT IN ({0})", string.Join(", ", ForbiddenNames.Select(x => string.Format("'{0}'", x))));
var Result = Cmd.ExecuteReader();
while (Result.Read())
yield return Result["name"].ToString();
}
}
static IEnumerable<string> GetIpList()
{
foreach (var Ni in NetworkInterface.GetAllNetworkInterfaces())
if (Ni.OperationalStatus == OperationalStatus.Up && (Ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
Ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
Ni.NetworkInterfaceType == NetworkInterfaceType.Loopback))
foreach (var IpInfo in Ni.GetIPProperties().UnicastAddresses)
if (IpInfo.Address.AddressFamily == AddressFamily.InterNetwork)
yield return IpInfo.Address.ToString();
}
internal static void AddLog(Session Ctx, string Msg)
{
AddTo(Ctx, "PI_PREREQ_LOG", Msg);
}
internal static void AddTo(Session Ctx, string TextProp, string Msg)
{
if (!string.IsNullOrWhiteSpace(Msg))
{
string tmp = Ctx[TextProp];
if (string.IsNullOrWhiteSpace(tmp))
Ctx[TextProp] = Msg;
else
Ctx[TextProp] = tmp + Environment.NewLine + Msg;
}
}
internal static void ValidationReset(Session Ctx)
{
Ctx["VALIDATE_OK"] = "0";
Ctx["VALIDATE_MSG"] = "Error occurred.";
}
internal static void ValidationStatus(Session Ctx, bool Value)
{
Ctx["VALIDATE_OK"] = Value ? YesNo.Yes : YesNo.No;
}
internal static void ValidationMsg(Session Ctx, string Msg)
{
AddTo(Ctx, "VALIDATE_MSG", Msg);
}
internal static bool PasswordValidate(string Password, string Confirm, out string Msg)
{
Msg = string.Empty;
bool Result = false;
if (string.IsNullOrWhiteSpace(Password))
Msg = "Empty password.";
else if (Password != Confirm)
Msg = "Password does not match the confirm password. Type both passwords again.";
else
Result = true;
return Result;
}
internal static bool PasswordValidateEqual(string Password, string Confirm, out string Msg)
{
Msg = string.Empty;
bool Result = false;
if (Password != Confirm)
Msg = "Password does not match the confirm password. Type both passwords again.";
else
Result = true;
return Result;
}
internal static bool ValidatePasswordUI(Session Ctx, string Ns, out string Msg)
{
string p1 = Ctx[Ns + "_PASSWORD"];
string p2 = Ctx[Ns + "_PASSWORD_CONFIRM"];
return PasswordValidate(p1, p2, out Msg);
}
internal static bool ValidateEqualPasswordUI(Session Ctx, string Ns, out string Msg)
{
string p1 = Ctx[Ns + "_PASSWORD"];
string p2 = Ctx[Ns + "_PASSWORD_CONFIRM"];
return PasswordValidateEqual(p1, p2, out Msg);
}
internal static bool ValidateADDomainUI(Session Ctx, string Ns, out string Msg)
{
bool Result = default(bool);
bool check = Ctx[Ns + "_CREATE_AD"] == YesNo.Yes;
string name = Ctx[Ns + "_DOMAIN"];
if (check && string.IsNullOrWhiteSpace(name))
{
Result = false;
Msg = "The domain can't be empty.";
}
else
{
Result = true;
Msg = string.Empty;
}
return Result;
}
internal static bool ValidateADLoginUI(Session Ctx, string Ns, out string Msg)
{
bool Result = default(bool);
string name = Ctx[Ns + "_LOGIN"];
if (string.IsNullOrWhiteSpace(name))
{
Result = false;
Msg = "The login can't be empty.";
}
else
{
Result = true;
Msg = string.Empty;
}
return Result;
}
internal static bool ValidateADUI(Session Ctx, string Ns, out string Msg)
{
bool Result = true;
if (!ValidateADDomainUI(Ctx, Ns, out Msg))
Result = false;
else if (!ValidateADLoginUI(Ctx, Ns, out Msg))
Result = false;
else if (!ValidatePasswordUI(Ctx, Ns, out Msg))
Result = false;
return Result;
}
internal static bool ValidateDbNameUI(Session Ctx, out string Msg)
{
Msg = string.Empty;
var Result = true;
string DbName = Ctx["DB_DATABASE"];
if (string.IsNullOrWhiteSpace(DbName))
{
Result = false;
Msg = "The database name can't be empty.";
}
return Result;
}
internal static bool ValidateCryptoKeyUI(Session Ctx, out string Msg)
{
Msg = string.Empty;
var Result = true;
string DbName = Ctx["PI_SCHEDULER_CRYPTO_KEY"];
if (string.IsNullOrWhiteSpace(DbName))
{
Result = false;
Msg = "The crypto key can't be empty.";
}
return Result;
}
internal static void RecapListReset(Session Ctx)
{
Ctx["CUSTOM_INSTALL_TEXT"] = string.Empty;
}
internal static void RecapListAdd(Session Ctx, params string[] Msgs)
{
foreach (var Msg in Msgs)
AddTo(Ctx, "CUSTOM_INSTALL_TEXT", Msg); ;
}
private static ActionResult ProcessInstall(Session Ctx, WiXInstallType InstallType)
{
IWiXSetup Install = null;
try
{
Ctx.AttachToSetupLog();
switch (InstallType)
{
case WiXInstallType.InstallServer:
Install = ServerSetup.Create(Ctx.CustomActionData, SetupActions.Install);
break;
case WiXInstallType.RemoveServer:
Install = ServerSetup.Create(Ctx.CustomActionData, SetupActions.Uninstall);
break;
case WiXInstallType.MaintenanceServer:
Install = ServerSetup.Create(Ctx.CustomActionData, SetupActions.Setup);
break;
case WiXInstallType.InstallEnterpriseServer:
Install = EServerSetup.Create(Ctx.CustomActionData, SetupActions.Install);
break;
case WiXInstallType.RemoveEnterpriseServer:
Install = EServerSetup.Create(Ctx.CustomActionData, SetupActions.Uninstall);
break;
case WiXInstallType.MaintenanceEnterpriseServer:
Install = EServerSetup.Create(Ctx.CustomActionData, SetupActions.Setup);
break;
case WiXInstallType.InstallPortal:
Install = PortalSetup.Create(Ctx.CustomActionData, SetupActions.Install);
break;
case WiXInstallType.RemovePortal:
Install = PortalSetup.Create(Ctx.CustomActionData, SetupActions.Uninstall);
break;
case WiXInstallType.MaintenancePortal:
Install = PortalSetup.Create(Ctx.CustomActionData, SetupActions.Setup);
break;
case WiXInstallType.InstallScheduler:
Install = SchedulerSetup.Create(Ctx.CustomActionData, SetupActions.Install);
break;
case WiXInstallType.RemoveScheduler:
Install = SchedulerSetup.Create(Ctx.CustomActionData, SetupActions.Uninstall);
break;
default:
throw new NotImplementedException();
}
Install.Run();
}
catch (WiXSetupException we)
{
Ctx.Log("Expected exception: " + we.ToString());
return ActionResult.Failure;
}
catch (Exception ex)
{
Ctx.Log(ex.ToString());
return ActionResult.Failure;
}
return ActionResult.Success;
}
[Conditional("DEBUG")]
private static void PopUpDebugger()
{
Debugger.Launch();
}
private static void TryApllyNewPassword(Session Ctx, string Id)
{
var Pass = Ctx[Id];
if (string.IsNullOrWhiteSpace(Pass))
{
Pass = Guid.NewGuid().ToString();
Ctx[Id] = Pass;
Ctx[Id + "_CONFIRM"] = Pass;
Log.WriteInfo("New password was applied to " + Id);
}
}
private static string GetProperty(Session Ctx, string Property)
{
if (Ctx.CustomActionData.ContainsKey(Property))
return Ctx.CustomActionData[Property];
else
return string.Empty;
}
private static bool SetProperty(Session CtxSession, string Prop, string Value)
{
if (!string.IsNullOrWhiteSpace(Value))
{
CtxSession[Prop] = Value;
return true;
}
return false;
}
private static SetupScript GetPrepareScript(Session Ctx)
{
var CtxVars = new SetupVariables();
WiXSetup.FillFromSession(Ctx.CustomActionData, CtxVars);
AppConfig.LoadConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = GetProperty(Ctx, "MainConfig") });
CtxVars.IISVersion = Tool.GetWebServerVersion();
CtxVars.ComponentId = GetProperty(Ctx, "ComponentId");
CtxVars.Version = AppConfig.GetComponentSettingStringValue(CtxVars.ComponentId, Global.Parameters.Release);
CtxVars.SpecialBaseDirectory = Directory.GetParent(GetProperty(Ctx, "MainConfig")).FullName;
CtxVars.FileNameMap = new Dictionary<string, string>();
CtxVars.FileNameMap.Add(new FileInfo(GetProperty(Ctx, "MainConfig")).Name, BackupRestore.MainConfig);
SetupScript Result = new ExpressScript(CtxVars);
Result.Actions.Add(new InstallAction(ActionTypes.StopApplicationPool) { SetupVariables = CtxVars });
Result.Actions.Add(new InstallAction(ActionTypes.Backup) { SetupVariables = CtxVars });
Result.Actions.Add(new InstallAction(ActionTypes.DeleteDirectory) { SetupVariables = CtxVars, Path = CtxVars.InstallFolder });
return Result;
}
private static bool IsEnctyptionEnabled(string Cfg)
{
var doc = new XmlDocument();
doc.Load(Cfg);
string xPath = "configuration/appSettings/add[@key=\"WebsitePanel.EncryptionEnabled\"]";
XmlElement encryptionNode = doc.SelectSingleNode(xPath) as XmlElement;
bool encryptionEnabled = false;
if (encryptionNode != null)
bool.TryParse(encryptionNode.GetAttribute("value"), out encryptionEnabled);
return encryptionEnabled;
}
}
public static class SessionExtension
{
public static void AttachToSetupLog(this Session Ctx)
{
WiXSetup.InstallLogListener(new WiXLogListener(Ctx));
WiXSetup.InstallLogListener(new InMemoryStringLogListener("WIX CA IN MEMORY"));
WiXSetup.InstallLogListener(new WiXLogFileListener());
}
}
public static class StringExtension
{
public static string Repeat(this string Src, ulong Count)
{
var Result = new StringBuilder();
for (ulong i = 0; i < Count; i++)
Result.Append(Src);
return Result.ToString();
}
}
internal enum WiXInstallType: byte
{
InstallServer,
InstallEnterpriseServer,
InstallPortal,
InstallScheduler,
RemoveServer,
RemoveEnterpriseServer,
RemovePortal,
RemoveScheduler,
MaintenanceServer,
MaintenanceEnterpriseServer,
MaintenancePortal
}
}
| |
//
// CoreVideo.cs
//
// Authors: Mono Team
//
// Copyright 2011 Novell, Inc
// Copyright 2011, 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
namespace MonoMac.CoreVideo {
public enum CVAttachmentMode : uint {
ShouldNotPropagate = 0,
ShouldPropagate = 1,
}
[Flags]
public enum CVPixelBufferLock {
ReadOnly = 0x00000001,
}
public struct CVPlanarComponentInfo {
public int Offset;
public uint RowBytes;
}
public struct CVPlanarPixelBufferInfo {
public CVPlanarComponentInfo[] ComponentInfo;
}
public struct CVPlanarPixelBufferInfo_YCbCrPlanar {
public CVPlanarComponentInfo ComponentInfoY;
public CVPlanarComponentInfo ComponentInfoCb;
public CVPlanarComponentInfo ComponentInfoCr;
}
public enum CVReturn {
Success = 0,
First = -6660,
Error = First,
InvalidArgument = -6661,
AllocationFailed = -6662,
InvalidDisplay = -6670,
DisplayLinkAlreadyRunning = -6671,
DisplayLinkNotRunning = -6672,
DisplayLinkCallbacksNotSet = -6673,
InvalidPixelFormat = -6680,
InvalidSize = -6681,
InvalidPixelBufferAttributes = -6682,
PixelBufferNotOpenGLCompatible = -6683,
WouldExceedAllocationThreshold = -6689,
PoolAllocationFailed = -6690,
InvalidPoolAttributes = -6691,
Last = -6699,
}
public enum CVPixelFormatType : uint {
// FIXME: These all start with integers; what should we do here?
CV1Monochrome = 0x00000001,
CV2Indexed = 0x00000002,
CV4Indexed = 0x00000004,
CV8Indexed = 0x00000008,
CV1IndexedGray_WhiteIsZero = 0x00000021,
CV2IndexedGray_WhiteIsZero = 0x00000022,
CV4IndexedGray_WhiteIsZero = 0x00000024,
CV8IndexedGray_WhiteIsZero = 0x00000028,
CV16BE555 = 0x00000010,
CV24RGB = 0x00000018,
CV32ARGB = 0x00000020,
CV16LE555 = 0x4c353535,
CV16LE5551 = 0x35353531,
CV16BE565 = 0x42353635,
CV16LE565 = 0x4c353635,
CV24BGR = 0x32344247,
CV32BGRA = 0x42475241,
CV32ABGR = 0x41424752,
CV32RGBA = 0x52474241,
CV64ARGB = 0x62363461,
CV48RGB = 0x62343872,
CV32AlphaGray = 0x62333261,
CV16Gray = 0x62313667,
CV422YpCbCr8 = 0x32767579,
CV4444YpCbCrA8 = 0x76343038,
CV4444YpCbCrA8R = 0x72343038,
CV444YpCbCr8 = 0x76333038,
CV422YpCbCr16 = 0x76323136,
CV422YpCbCr10 = 0x76323130,
CV444YpCbCr10 = 0x76343130,
CV420YpCbCr8Planar = 0x79343230,
CV420YpCbCr8PlanarFullRange = 0x66343230,
CV422YpCbCr_4A_8BiPlanar = 0x61327679,
CV420YpCbCr8BiPlanarVideoRange = 0x34323076,
CV420YpCbCr8BiPlanarFullRange = 0x34323066,
CV422YpCbCr8_yuvs = 0x79757673,
CV422YpCbCr8FullRange = 0x79757666,
CV30RGB = 0x5231306b,
CV4444AYpCbCr8 = 0x79343038,
CV4444AYpCbCr16 = 0x79343136,
// Since 5.1
OneComponent8 = 0x4C303038,
TwoComponent8 = 0x32433038,
// Since 6.0
OneComponent16Half = 0x4C303068, // 'L00h'
OneComponent32Float = 0x4C303066, // 'L00f'
TwoComponent16Half = 0x32433068, // '2C0h'
TwoComponent32Float = 0x32433066, // '2C0f'
CV64RGBAHalf = 0x52476841, // 'RGhA'
CV128RGBAFloat = 0x52476641, // 'RGfA'
}
public enum CVOptionFlags : long {
None = 0,
}
public struct CVTimeStamp {
public UInt32 Version;
public Int32 VideoTimeScale;
public Int64 VideoTime;
public UInt64 HostTime;
public double RateScalar;
public Int64 VideoRefreshPeriod;
public CVSMPTETime SMPTETime;
public UInt64 Flags;
public UInt64 Reserved;
}
public struct CVSMPTETime {
public Int16 Subframes;
public Int16 SubframeDivisor;
public UInt32 Counter;
public UInt32 Type;
public UInt32 Flags;
public Int16 Hours;
public Int16 Minutes;
public Int16 Seconds;
public Int16 Frames;
}
[Flags]
public enum CVTimeFlags {
IsIndefinite = 1 << 0
}
[Flags]
public enum CVTimeStampFlags {
VideoTimeValid = (1 << 0),
HostTimeValid = (1 << 1),
SMPTETimeValid = (1 << 2),
VideoRefreshPeriodValid = (1 << 3),
RateScalarValid = (1 << 4),
TopField = (1 << 16),
BottomField = (1 << 17),
VideoHostTimeValid = (VideoTimeValid | HostTimeValid),
IsInterlaced = (TopField | BottomField)
}
[Flags]
public enum CVSMPTETimeFlags {
Valid = (1 << 0),
Running = (1 << 1)
}
public enum CVSMPTETimeType {
Type24 = 0,
Type25 = 1,
Type30Drop = 2,
Type30 = 3,
Type2997 = 4,
Type2997Drop = 5,
Type60 = 6,
Type5994 = 7
}
public struct CVFillExtendedPixelsCallBackData {
public int Version;
public CVFillExtendedPixelsCallBack FillCallBack;
public IntPtr UserInfo;
}
public delegate bool CVFillExtendedPixelsCallBack (IntPtr pixelBuffer, IntPtr refCon);
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Linq;
using AutoRest.Swagger.Validation;
using System.Collections.Generic;
using AutoRest.Core.Utilities;
using AutoRest.Swagger.Validation.Core;
namespace AutoRest.Swagger.Model
{
/// <summary>
/// Describes a single API operation on a path.
/// </summary>
[Rule(typeof(OperationDescriptionRequired))]
public class Operation : SwaggerBase
{
private string _description;
private string _summary;
public Operation()
{
Consumes = new List<string>();
Produces = new List<string>();
}
/// <summary>
/// A list of tags for API documentation control.
/// </summary>
public IList<string> Tags { get; set; }
/// <summary>
/// A friendly serviceTypeName for the operation. The id MUST be unique among all
/// operations described in the API. Tools and libraries MAY use the
/// operation id to uniquely identify an operation.
/// </summary>
[Rule(typeof(OneUnderscoreInOperationId))]
[Rule(typeof(OperationIdNounInVerb))]
[Rule(typeof(GetOperationNameValidation))]
[Rule(typeof(PutOperationNameValidation))]
[Rule(typeof(PatchOperationNameValidation))]
[Rule(typeof(DeleteOperationNameValidation))]
public string OperationId { get; set; }
public string Summary
{
get { return _summary; }
set { _summary = value.StripControlCharacters(); }
}
[Rule(typeof(AvoidMsdnReferences))]
public string Description
{
get { return _description; }
set { _description = value.StripControlCharacters(); }
}
/// <summary>
/// Additional external documentation for this operation.
/// </summary>
public ExternalDoc ExternalDocs { get; set; }
/// <summary>
/// A list of MIME types the operation can consume.
/// </summary>
[CollectionRule(typeof(NonAppJsonTypeWarning))]
public IList<string> Consumes { get; set; }
/// <summary>
/// A list of MIME types the operation can produce.
/// </summary>
[CollectionRule(typeof(NonAppJsonTypeWarning))]
public IList<string> Produces { get; set; }
/// <summary>
/// A list of parameters that are applicable for this operation.
/// If a parameter is already defined at the Path Item, the
/// new definition will override it, but can never remove it.
/// </summary>
[CollectionRule(typeof(OperationParametersValidation))]
[CollectionRule(typeof(AnonymousParameterTypes))]
public IList<SwaggerParameter> Parameters { get; set; }
/// <summary>
/// The list of possible responses as they are returned from executing this operation.
/// </summary>
public Dictionary<string, OperationResponse> Responses { get; set; }
/// <summary>
/// The transfer protocol for the operation.
/// </summary>
[CollectionRule(typeof(SupportedSchemesWarning))]
public IList<TransferProtocolScheme> Schemes { get; set; }
public bool Deprecated { get; set; }
/// <summary>
/// A declaration of which security schemes are applied for this operation.
/// The list of values describes alternative security schemes that can be used
/// (that is, there is a logical OR between the security requirements).
/// This definition overrides any declared top-level security. To remove a
/// top-level security declaration, an empty array can be used.
/// </summary>
public IList<Dictionary<string, List<string>>> Security { get; set; }
/// <summary>
/// Compare a modified document node (this) to a previous one and look for breaking as well as non-breaking changes.
/// </summary>
/// <param name="context">The modified document context.</param>
/// <param name="previous">The original document model.</param>
/// <returns>A list of messages from the comparison.</returns>
public override IEnumerable<ComparisonMessage> Compare(ComparisonContext context, SwaggerBase previous)
{
var priorOperation = previous as Operation;
var currentRoot = (context.CurrentRoot as ServiceDefinition);
var previousRoot = (context.PreviousRoot as ServiceDefinition);
if (priorOperation == null)
{
throw new ArgumentException("previous");
}
base.Compare(context, previous);
if (!OperationId.Equals(priorOperation.OperationId))
{
context.LogBreakingChange(ComparisonMessages.ModifiedOperationId);
}
CheckParameters(context, priorOperation);
if (Responses != null && priorOperation.Responses != null)
{
foreach (var response in Responses)
{
var oldResponse = priorOperation.FindResponse(response.Key, priorOperation.Responses);
context.PushProperty(response.Key);
if (oldResponse == null)
{
context.LogBreakingChange(ComparisonMessages.AddingResponseCode, response.Key);
}
else
{
response.Value.Compare(context, oldResponse);
}
context.Pop();
}
foreach (var response in priorOperation.Responses)
{
var newResponse = this.FindResponse(response.Key, this.Responses);
if (newResponse == null)
{
context.PushProperty(response.Key);
context.LogBreakingChange(ComparisonMessages.RemovedResponseCode, response.Key);
context.Pop();
}
}
}
return context.Messages;
}
private void CheckParameters(ComparisonContext context, Operation priorOperation)
{
// Check that no parameters were removed or reordered, and compare them if it's not the case.
var currentRoot = (context.CurrentRoot as ServiceDefinition);
var previousRoot = (context.PreviousRoot as ServiceDefinition);
foreach (var oldParam in priorOperation.Parameters
.Select(p => string.IsNullOrEmpty(p.Reference) ? p : FindReferencedParameter(p.Reference, previousRoot.Parameters)))
{
SwaggerParameter newParam = FindParameter(oldParam.Name, Parameters, currentRoot.Parameters);
context.PushProperty(oldParam.Name);
if (newParam != null)
{
newParam.Compare(context, oldParam);
}
else if (oldParam.IsRequired)
{
context.LogBreakingChange(ComparisonMessages.RemovedRequiredParameter, oldParam.Name);
}
context.Pop();
}
// Check that no required parameters were added.
foreach (var newParam in Parameters
.Select(p => string.IsNullOrEmpty(p.Reference) ? p : FindReferencedParameter(p.Reference, currentRoot.Parameters))
.Where(p => p != null && p.IsRequired))
{
if (newParam == null) continue;
SwaggerParameter oldParam = FindParameter(newParam.Name, priorOperation.Parameters, previousRoot.Parameters);
if (oldParam == null)
{
context.PushProperty(newParam.Name);
context.LogBreakingChange(ComparisonMessages.AddingRequiredParameter, newParam.Name);
context.Pop();
}
}
}
private SwaggerParameter FindParameter(string name, IEnumerable<SwaggerParameter> operationParameters, IDictionary<string, SwaggerParameter> clientParameters)
{
if (Parameters != null)
{
foreach (var param in operationParameters)
{
if (name.Equals(param.Name))
return param;
var pRef = FindReferencedParameter(param.Reference, clientParameters);
if (pRef != null && name.Equals(pRef.Name))
{
return pRef;
}
}
}
return null;
}
private OperationResponse FindResponse(string name, IDictionary<string, OperationResponse> responses)
{
OperationResponse response = null;
this.Responses.TryGetValue(name, out response);
return response;
}
private static SwaggerParameter FindReferencedParameter(string reference, IDictionary<string, SwaggerParameter> parameters)
{
if (reference != null && reference.StartsWith("#", StringComparison.Ordinal))
{
var parts = reference.Split('/');
if (parts.Length == 3 && parts[1].Equals("parameters"))
{
SwaggerParameter p = null;
if (parameters.TryGetValue(parts[2], out p))
{
return p;
}
}
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace QBank.Api.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//
// Copyright (c) Vaughn Friesen
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace AudioInfo
{
namespace ID3
{
public class ID3
{
/// <summary>
/// The constructor
/// </summary>
/// <param name="FileName">The name of the file to read tags from</param>
public ID3(string FileName)
{
m_FileName = FileName;
m_V1Tag = new ID3v1();
m_V2Tag = new ID3v2();
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="Copy">The ID3 object to copy from</param>
public ID3(ID3 Copy)
{
m_FileName = Copy.m_FileName;
m_V1Tag = new ID3v1(Copy.m_V1Tag);
m_V2Tag = new ID3v2(Copy.m_V2Tag);
}
public readonly List<Error> Errors = new List<Error>();
private readonly string m_FileName;
private ID3v1 m_V1Tag;
private ID3v2 m_V2Tag;
public ID3v1 V1Tag
{
get { return m_V1Tag; }
}
public ID3v2 V2Tag
{
get { return m_V2Tag; }
}
/// <summary>
/// Loads the ID3v1 tags
/// </summary>
/// <returns>One of the following values: Id3Result.Success,
/// Id3Result.CannotOpenFile, Id3Result.NoTag, Id3Result.InvalidTag.</returns>
public Id3Result ReadV1Tag()
{
BinaryReader reader;
m_V1Tag = new ID3v1();
// Open the file
try { reader = new BinaryReader(File.Open(m_FileName, FileMode.Open)); }
catch
{
Errors.Add(new Error(471, "Failed to open file \"" + m_FileName + "\"."));
return Id3Result.CannotOpenFile;
}
// Seek to where the id3v1 tag should be
try { reader.BaseStream.Seek(-128, SeekOrigin.End); }
catch
{
reader.Close();
return Id3Result.NoTag;
}
// Make sure there's an id3v1 tag
byte[] Header = new byte[3];
reader.Read(Header, 0, 3);
if ((Header[0] != 'T') || (Header[1] != 'A') || (Header[2] != 'G'))
{
reader.Close();
return Id3Result.NoTag;
}
// Read the tag
if (!m_V1Tag.Read(reader, Errors))
{
reader.Close();
return Id3Result.InvalidTag;
}
reader.Close();
return Id3Result.Success;
}
/// <summary>
/// Loads the ID3v2 tags
/// </summary>
/// <returns>One of the following values: Id3Result.Success,
/// Id3Result.CannotOpenFile, Id3Result.NoTag, Id3Result.InvalidTag.</returns>
public Id3Result ReadV2Tag()
{
BinaryReader reader;
m_V2Tag = new ID3v2();
// Open the file
try { reader = new BinaryReader(File.Open(m_FileName, FileMode.Open)); }
catch
{
Errors.Add(new Error(472, "Failed to open file \"" + m_FileName + "\"."));
return Id3Result.CannotOpenFile;
}
// Make sure there is an ID3v2 tag
byte[] HeaderBytes = new byte[3];
reader.Read(HeaderBytes, 0, 3);
if ((HeaderBytes[0] != 'I') || (HeaderBytes[1] != 'D') || (HeaderBytes[2] != '3'))
{
reader.Close();
return Id3Result.NoTag;
}
// Go back to the beginning
reader.BaseStream.Seek(0, SeekOrigin.Begin);
// Read the tag
if (!m_V2Tag.Read(reader, Errors))
{
reader.Close();
return Id3Result.InvalidTag;
}
reader.Close();
return Id3Result.Success;
}
/// <summary>
/// Writes the ID3 tags
/// </summary>
/// <param name="WriteV1Tag">Whether a version 1 tag should be written</param>
/// <param name="WriteV2Tag">Whether a version 2 tag should be written</param>
/// <returns>One of the following values: Id3Result.Success,
/// Id3Result.CannotOpenFile, Id3Result.CannotCreateTempFile</returns>
public Id3Result WriteTags(bool WriteV1Tag, bool WriteV2Tag)
{
bool HasTag1 = false;
bool HasTag2 = false;
// See if there's already an ID3v1 tag
switch ((new ID3(m_FileName)).ReadV1Tag())
{
case Id3Result.Success:
case Id3Result.InvalidTag:
HasTag1 = true;
break;
case Id3Result.NoTag:
HasTag1 = false;
break;
case Id3Result.CannotOpenFile:
return Id3Result.CannotOpenFile;
}
// See if there's an ID3v2 tag
switch ((new ID3(m_FileName)).ReadV2Tag())
{
case Id3Result.Success:
case Id3Result.InvalidTag:
HasTag2 = true;
break;
case Id3Result.NoTag:
HasTag2 = false;
break;
case Id3Result.CannotOpenFile:
return Id3Result.CannotOpenFile;
}
// We'll make a temporary copy of the file so we don't lose the original
// if something messes up
string TempFileName = "";
BinaryWriter writer;
// Try to create a temp file
try
{
TempFileName = Path.GetTempFileName();
writer = new BinaryWriter(File.Open(TempFileName, FileMode.Create));
}
catch
{
File.Delete(TempFileName);
return Id3Result.CannotCreateTempFile;
}
// Open the original file for reading
BinaryReader reader;
try
{
reader = new BinaryReader(File.Open(m_FileName, FileMode.Open));
}
catch
{
return Id3Result.CannotOpenFile;
}
// Copy the file to the temp file
// If it has a v2 tag already start after the tag
int StartPos = 0;
if (HasTag2)
{
// Get the size of the v2 tag
byte[] Header = new byte[10];
reader.Read(Header, 0, 10);
int V2Length;
// Get the tag length
V2Length = (Header[6] << 21);
V2Length += (Header[7] << 14);
V2Length += (Header[8] << 7);
V2Length += Header[9];
StartPos = V2Length + 10;
}
// Write a v2 tag to the temp file
if (WriteV2Tag)
V2Tag.Write(writer);
int BufferSize = 1024 * 1024; // 1MB buffer
// Copy the actual file data from the file to the temp file
if (HasTag1)
{
// We have to read up to (but not including) the v1 tag
long TagPos = reader.BaseStream.Seek(-128, SeekOrigin.End);
// Go to the beginning of the ID3v2 tag (if there is one)
reader.BaseStream.Seek(StartPos, SeekOrigin.Begin);
long FileLength = TagPos - StartPos; // Length of file minus tags
if (FileLength < BufferSize)
{
// Less than BufferSize from start to beginning of tag, copy it
// all in one shot
byte[] buffer = new byte[FileLength];
reader.Read(buffer, 0, (int)FileLength);
writer.Write(buffer);
}
else
{
// Make a buffer
byte[] buffer = new byte[BufferSize];
// See how many buffers it will take to get to the tag
int NumBuffers = (int)(FileLength / BufferSize);
for (int x = 0; x < NumBuffers; x++)
{
reader.Read(buffer, 0, BufferSize);
writer.Write(buffer);
}
int LastBuffer = (int)(FileLength % BufferSize);
reader.Read(buffer, 0, LastBuffer);
writer.Write(buffer, 0, LastBuffer);
}
}
else
{
// No v1 tag, just copy the whole file from the v2 tag
// Make a buffer
byte[] buffer = new byte[BufferSize];
// Go to the beginning of the v2 tag
reader.BaseStream.Seek(StartPos, SeekOrigin.Begin);
int Result = reader.Read(buffer, 0, BufferSize);
while (Result > 0)
{
writer.Write(buffer, 0, Result);
Result = reader.Read(buffer, 0, BufferSize);
}
}
// Write an ID3v1 tag
if (WriteV1Tag)
V1Tag.Write(writer);
// Close our files
writer.Close();
reader.Close();
// Copy the temp file to the other file
File.Copy(TempFileName, m_FileName, true);
// Clean up our mess
File.Delete(TempFileName);
// Successful
return Id3Result.Success;
}
}
public enum Id3Result
{
Success, CannotOpenFile, NoTag, InvalidTag, CannotCreateTempFile
}
}
}
| |
//
// Document.cs
//
// Author:
// Jonathan Pobst <monkey@jpobst.com>
//
// Copyright (c) 2010 Jonathan Pobst
//
// 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.Linq;
using Mono.Unix;
using Gdk;
using Gtk;
using System.Collections.Generic;
using Cairo;
using System.ComponentModel;
using Pinta;
namespace Pinta.Core
{
// The differentiation between Document and DocumentWorkspace is
// somewhat arbitrary. In general:
// Document - Data about the image itself
// Workspace - Data about Pinta's state for the image
public class Document
{
private string filename;
private bool is_dirty;
private int layer_name_int = 2;
private int current_layer = -1;
// The layer for tools to use until their output is committed
private Layer tool_layer;
// The layer used for selections
private Layer selection_layer;
private bool show_selection;
private DocumentSelection selection;
public DocumentSelection Selection
{
get { return selection; }
set
{
selection = value;
// Listen for any changes to this selection.
selection.SelectionModified += (sender, args) => {
OnSelectionChanged ();
};
// Notify listeners that our selection has been modified.
OnSelectionChanged();
}
}
public DocumentSelection PreviousSelection = new DocumentSelection ();
public Document (Gdk.Size size)
{
Selection = new DocumentSelection ();
Guid = Guid.NewGuid ();
Workspace = new DocumentWorkspace (this);
IsDirty = false;
HasFile = false;
HasBeenSavedInSession = false;
ImageSize = size;
UserLayers = new List<UserLayer>();
tool_layer = CreateLayer ("Tool Layer");
tool_layer.Hidden = true;
selection_layer = CreateLayer ("Selection Layer");
selection_layer.Hidden = true;
ResetSelectionPaths ();
}
#region Public Properties
public UserLayer CurrentUserLayer
{
get { return UserLayers[current_layer]; }
}
public int CurrentUserLayerIndex {
get { return current_layer; }
}
/// <summary>
/// Just the file name, like "dog.jpg".
/// </summary>
public string Filename {
get { return filename; }
set {
if (filename != value) {
filename = value;
OnRenamed ();
}
}
}
public Guid Guid { get; private set; }
public bool HasFile { get; set; }
//Determines whether or not the Document has been saved to the file that it is currently associated with in the
//current session. This should be false if the Document has not yet been saved, if it was just loaded into
//Pinta from a file, or if the user just clicked Save As.
public bool HasBeenSavedInSession { get; set; }
public DocumentWorkspaceHistory History { get { return Workspace.History; } }
public Gdk.Size ImageSize { get; set; }
public bool IsDirty {
get { return is_dirty; }
set {
if (is_dirty != value) {
is_dirty = value;
OnIsDirtyChanged ();
}
}
}
public List<UserLayer> UserLayers { get; private set; }
/// <summary>
/// Just the directory name, like "C:\MyPictures".
/// </summary>
public string Pathname { get; set; }
/// <summary>
/// Directory and file name, like "C:\MyPictures\dog.jpg".
/// </summary>
public string PathAndFileName {
get { return System.IO.Path.Combine (Pathname, Filename); }
set {
if (string.IsNullOrEmpty (value)) {
Pathname = string.Empty;
Filename = string.Empty;
} else {
Pathname = System.IO.Path.GetDirectoryName (value);
Filename = System.IO.Path.GetFileName (value);
}
}
}
public Layer SelectionLayer {
get { return selection_layer; }
}
public bool ShowSelection {
get { return show_selection; }
set {
show_selection = value;
PintaCore.Actions.Edit.Deselect.Sensitive = show_selection;
PintaCore.Actions.Edit.EraseSelection.Sensitive = show_selection;
PintaCore.Actions.Edit.FillSelection.Sensitive = show_selection;
PintaCore.Actions.Image.CropToSelection.Sensitive = show_selection;
PintaCore.Actions.Edit.InvertSelection.Sensitive = show_selection;
}
}
public bool ShowSelectionLayer { get; set; }
public Layer ToolLayer {
get {
if (tool_layer.Surface.Width != ImageSize.Width || tool_layer.Surface.Height != ImageSize.Height) {
(tool_layer.Surface as IDisposable).Dispose ();
tool_layer = CreateLayer ("Tool Layer");
tool_layer.Hidden = true;
}
return tool_layer;
}
}
public DocumentWorkspace Workspace { get; private set; }
public delegate void LayerCloneEvent();
#endregion
#region Public Methods
// Adds a new layer above the current one
public UserLayer AddNewLayer(string name)
{
UserLayer layer;
if (string.IsNullOrEmpty (name))
layer = CreateLayer ();
else
layer = CreateLayer (name);
UserLayers.Insert (current_layer + 1, layer);
if (UserLayers.Count == 1)
current_layer = 0;
layer.PropertyChanged += RaiseLayerPropertyChangedEvent;
PintaCore.Layers.OnLayerAdded ();
return layer;
}
public Gdk.Rectangle ClampToImageSize (Gdk.Rectangle r)
{
int x = Utility.Clamp (r.X, 0, ImageSize.Width);
int y = Utility.Clamp (r.Y, 0, ImageSize.Height);
int width = Math.Min (r.Width, ImageSize.Width - x);
int height = Math.Min (r.Height, ImageSize.Height - y);
return new Gdk.Rectangle (x, y, width, height);
}
public void Clear ()
{
while (UserLayers.Count > 0) {
Layer l = UserLayers[UserLayers.Count - 1];
UserLayers.RemoveAt (UserLayers.Count - 1);
(l.Surface as IDisposable).Dispose ();
}
current_layer = -1;
PintaCore.Layers.OnLayerRemoved ();
}
// Clean up any native resources we had
public void Close ()
{
// Dispose all of our layers
while (UserLayers.Count > 0) {
Layer l = UserLayers[UserLayers.Count - 1];
UserLayers.RemoveAt (UserLayers.Count - 1);
(l.Surface as IDisposable).Dispose ();
}
current_layer = -1;
if (tool_layer != null)
(tool_layer.Surface as IDisposable).Dispose ();
if (selection_layer != null)
(selection_layer.Surface as IDisposable).Dispose ();
Selection.Dispose ();
PreviousSelection.Dispose ();
Workspace.History.Clear ();
}
public Context CreateClippedContext ()
{
Context g = new Context (CurrentUserLayer.Surface);
Selection.Clip (g);
return g;
}
public Context CreateClippedContext (bool antialias)
{
Context g = new Context (CurrentUserLayer.Surface);
Selection.Clip (g);
g.Antialias = antialias ? Antialias.Subpixel : Antialias.None;
return g;
}
public Context CreateClippedToolContext ()
{
Context g = new Context (ToolLayer.Surface);
Selection.Clip (g);
return g;
}
public Context CreateClippedToolContext (bool antialias)
{
Context g = new Context (ToolLayer.Surface);
Selection.Clip (g);
g.Antialias = antialias ? Antialias.Subpixel : Antialias.None;
return g;
}
public UserLayer CreateLayer ()
{
return CreateLayer (string.Format ("{0} {1}", Catalog.GetString ("Layer"), layer_name_int++));
}
public UserLayer CreateLayer (int width, int height)
{
return CreateLayer (string.Format ("{0} {1}", Catalog.GetString ("Layer"), layer_name_int++), width, height);
}
public UserLayer CreateLayer (string name)
{
return CreateLayer (name, ImageSize.Width, ImageSize.Height);
}
public UserLayer CreateLayer(string name, int width, int height)
{
Cairo.ImageSurface surface = new Cairo.ImageSurface (Cairo.Format.ARGB32, width, height);
UserLayer layer = new UserLayer(surface) { Name = name };
return layer;
}
public void CreateSelectionLayer ()
{
Layer old = selection_layer;
selection_layer = CreateLayer ();
if (old != null)
(old.Surface as IDisposable).Dispose ();
}
public void CreateSelectionLayer (int width, int height)
{
Layer old = selection_layer;
selection_layer = CreateLayer (width, height);
if (old != null)
(old.Surface as IDisposable).Dispose ();
}
// Delete the current layer
public void DeleteCurrentLayer ()
{
Layer layer = CurrentUserLayer;
UserLayers.RemoveAt (current_layer);
// Only change this if this wasn't already the bottom layer
if (current_layer > 0)
current_layer--;
layer.PropertyChanged -= RaiseLayerPropertyChangedEvent;
PintaCore.Layers.OnLayerRemoved ();
}
// Delete the layer
public void DeleteLayer (int index, bool dispose)
{
Layer layer = UserLayers[index];
UserLayers.RemoveAt (index);
if (dispose)
(layer.Surface as IDisposable).Dispose ();
// Only change this if this wasn't already the bottom layer
if (current_layer > 0)
current_layer--;
layer.PropertyChanged -= RaiseLayerPropertyChangedEvent;
PintaCore.Layers.OnLayerRemoved ();
}
public void DestroySelectionLayer ()
{
ShowSelectionLayer = false;
SelectionLayer.Clear ();
SelectionLayer.Transform.InitIdentity();
}
// Duplicate current layer
public UserLayer DuplicateCurrentLayer()
{
UserLayer source = CurrentUserLayer;
UserLayer layer = CreateLayer(string.Format("{0} {1}", source.Name, Catalog.GetString("copy")));
using (Cairo.Context g = new Cairo.Context (layer.Surface)) {
g.SetSource (source.Surface);
g.Paint ();
}
layer.Hidden = source.Hidden;
layer.Opacity = source.Opacity;
layer.Tiled = source.Tiled;
UserLayers.Insert (++current_layer, layer);
layer.PropertyChanged += RaiseLayerPropertyChangedEvent;
PintaCore.Layers.OnLayerAdded ();
return layer;
}
public void FinishSelection ()
{
// We don't have an uncommitted layer, abort
if (!ShowSelectionLayer)
return;
FinishPixelsHistoryItem hist = new FinishPixelsHistoryItem ();
hist.TakeSnapshot ();
Layer layer = SelectionLayer;
using (Cairo.Context g = new Cairo.Context (CurrentUserLayer.Surface)) {
layer.Draw(g);
}
DestroySelectionLayer ();
Workspace.Invalidate ();
Workspace.History.PushNewItem (hist);
}
// Flatten image
public void FlattenImage ()
{
if (UserLayers.Count < 2)
throw new InvalidOperationException ("Cannot flatten image because there is only one layer.");
// Find the "bottom" layer
var bottom_layer = UserLayers[0];
var old_surf = bottom_layer.Surface;
// Replace the bottom surface with the flattened image,
// and dispose the old surface
bottom_layer.Surface = GetFlattenedImage ();
(old_surf as IDisposable).Dispose ();
// Reset our layer pointer to the only remaining layer
current_layer = 0;
// Delete all other layers
while (UserLayers.Count > 1)
UserLayers.RemoveAt (1);
PintaCore.Layers.OnLayerRemoved ();
Workspace.Invalidate ();
}
// Flip image horizontally
public void FlipImageHorizontal ()
{
foreach (var layer in UserLayers)
layer.FlipHorizontal ();
Workspace.Invalidate ();
}
// Flip image vertically
public void FlipImageVertical ()
{
foreach (var layer in UserLayers)
layer.FlipVertical ();
Workspace.Invalidate ();
}
public ImageSurface GetClippedLayer (int index)
{
Cairo.ImageSurface surf = new Cairo.ImageSurface (Cairo.Format.Argb32, ImageSize.Width, ImageSize.Height);
using (Cairo.Context g = new Cairo.Context (surf)) {
g.AppendPath(Selection.SelectionPath);
g.Clip ();
g.SetSource (UserLayers[index].Surface);
g.Paint ();
}
return surf;
}
/// <summary>
/// Gets the final pixel color for the given point, taking layers, opacity, and blend modes into account.
/// </summary>
public ColorBgra GetComputedPixel (int x, int y)
{
using (var dst = new ImageSurface (Format.Argb32, 1, 1)) {
using (var g = new Context (dst)) {
foreach (var layer in GetLayersToPaint ()) {
var color = layer.Surface.GetColorBgraUnchecked (x, y).ToCairoColor ();
g.SetBlendMode (layer.BlendMode);
g.SetSourceColor (color);
g.Rectangle (dst.GetBounds ().ToCairoRectangle ());
g.PaintWithAlpha (layer.Opacity);
}
}
return dst.GetPixel (0, 0).ToColorBgra ();
}
}
public ImageSurface GetFlattenedImage ()
{
// Create a new image surface
var surf = new Cairo.ImageSurface (Cairo.Format.Argb32, ImageSize.Width, ImageSize.Height);
// Blend each visible layer onto our surface
foreach (var layer in GetLayersToPaint (include_tool_layer: false)) {
using (var g = new Context (surf))
layer.Draw (g);
}
surf.MarkDirty ();
return surf;
}
public List<Layer> GetLayersToPaint (bool include_tool_layer = true)
{
List<Layer> paint = new List<Layer> ();
foreach (var layer in UserLayers) {
if (!layer.Hidden)
paint.Add (layer);
if (layer == CurrentUserLayer) {
if (!ToolLayer.Hidden && include_tool_layer)
paint.Add (ToolLayer);
if (ShowSelectionLayer)
paint.Add (SelectionLayer);
}
if (!layer.Hidden)
{
foreach (ReEditableLayer rel in layer.ReEditableLayers)
{
//Make sure that each UserLayer's ReEditableLayer is in use before adding it to the List of Layers to Paint.
if (rel.IsLayerSetup)
{
paint.Add(rel.Layer);
}
}
}
}
return paint;
}
/// <param name="canvasOnly">false for the whole selection, true for the part only on our canvas</param>
public Gdk.Rectangle GetSelectedBounds (bool canvasOnly)
{
var bounds = Selection.SelectionPath.GetBounds();
if (canvasOnly)
bounds = ClampToImageSize (bounds);
return bounds;
}
public int IndexOf(UserLayer layer)
{
return UserLayers.IndexOf (layer);
}
// Adds a new layer above the current one
public void Insert(UserLayer layer, int index)
{
UserLayers.Insert (index, layer);
if (UserLayers.Count == 1)
current_layer = 0;
layer.PropertyChanged += RaiseLayerPropertyChangedEvent;
PintaCore.Layers.OnLayerAdded ();
}
// Flatten current layer
public void MergeCurrentLayerDown ()
{
if (current_layer == 0)
throw new InvalidOperationException ("Cannot flatten layer because current layer is the bottom layer.");
// Get our source and destination layers
var source = CurrentUserLayer;
var dest = UserLayers[current_layer - 1];
// Blend the layers
using (var g = new Context (dest.Surface))
source.Draw (g);
DeleteCurrentLayer ();
}
// Move current layer down
public void MoveCurrentLayerDown ()
{
if (current_layer == 0)
throw new InvalidOperationException ("Cannot move layer down because current layer is the bottom layer.");
UserLayer layer = CurrentUserLayer;
UserLayers.RemoveAt (current_layer);
UserLayers.Insert (--current_layer, layer);
PintaCore.Layers.OnSelectedLayerChanged ();
Workspace.Invalidate ();
}
// Move current layer up
public void MoveCurrentLayerUp ()
{
if (current_layer == UserLayers.Count)
throw new InvalidOperationException ("Cannot move layer up because current layer is the top layer.");
UserLayer layer = CurrentUserLayer;
UserLayers.RemoveAt (current_layer);
UserLayers.Insert (++current_layer, layer);
PintaCore.Layers.OnSelectedLayerChanged ();
Workspace.Invalidate ();
}
public void ResetSelectionPaths()
{
var rect = new Cairo.Rectangle (0, 0, ImageSize.Width, ImageSize.Height);
Selection.CreateRectangleSelection (rect);
PreviousSelection.CreateRectangleSelection (rect);
ShowSelection = false;
}
/// <summary>
/// Resizes the canvas.
/// </summary>
/// <param name="width">The new width of the canvas.</param>
/// <param name="height">The new height of the canvas.</param>
/// <param name="anchor">Direction in which to adjust the canvas</param>
/// <param name='compoundAction'>
/// Optionally, the history item for resizing the canvas can be added to
/// a CompoundHistoryItem if it is part of a larger action (e.g. pasting an image).
/// </param>
public void ResizeCanvas (int width, int height, Anchor anchor, CompoundHistoryItem compoundAction)
{
double scale;
if (ImageSize.Width == width && ImageSize.Height == height)
return;
PintaCore.Tools.Commit ();
ResizeHistoryItem hist = new ResizeHistoryItem (ImageSize);
hist.Icon = "Menu.Image.CanvasSize.png";
hist.Text = Catalog.GetString ("Resize Canvas");
hist.StartSnapshotOfImage ();
scale = Workspace.Scale;
ImageSize = new Gdk.Size (width, height);
foreach (var layer in UserLayers)
layer.ResizeCanvas (width, height, anchor);
hist.FinishSnapshotOfImage ();
if (compoundAction != null) {
compoundAction.Push (hist);
} else {
Workspace.History.PushNewItem (hist);
}
ResetSelectionPaths ();
Workspace.Scale = scale;
}
public void ResizeImage (int width, int height)
{
double scale;
if (ImageSize.Width == width && ImageSize.Height == height)
return;
PintaCore.Tools.Commit ();
ResizeHistoryItem hist = new ResizeHistoryItem (ImageSize);
hist.StartSnapshotOfImage ();
scale = Workspace.Scale;
ImageSize = new Gdk.Size (width, height);
foreach (var layer in UserLayers)
layer.Resize (width, height);
hist.FinishSnapshotOfImage ();
Workspace.History.PushNewItem (hist);
ResetSelectionPaths ();
Workspace.Scale = scale;
}
// Rotate image 180 degrees (flip H+V)
public void RotateImage180 ()
{
RotateImage (180);
}
public void RotateImageCW ()
{
RotateImage (90);
}
public void RotateImageCCW ()
{
RotateImage (-90);
}
/// <summary>
/// Rotates the image by the specified angle (in degrees)
/// </summary>
private void RotateImage (double angle)
{
var new_size = Layer.RotateDimensions (ImageSize, angle);
foreach (var layer in UserLayers)
layer.Rotate (angle, new_size);
ImageSize = new_size;
Workspace.CanvasSize = new_size;
PintaCore.Actions.View.UpdateCanvasScale ();
Workspace.Invalidate ();
}
// Returns true if successful, false if canceled
public bool Save (bool saveAs)
{
return PintaCore.Actions.File.RaiseSaveDocument (this, saveAs);
}
public void SetCurrentUserLayer (int i)
{
// Ensure that the current tool's modifications are finalized before
// switching layers.
PintaCore.Tools.CurrentTool.DoCommit ();
current_layer = i;
PintaCore.Layers.OnSelectedLayerChanged ();
}
public void SetCurrentUserLayer(UserLayer layer)
{
SetCurrentUserLayer (UserLayers.IndexOf (layer));
}
/// <summary>
/// Pastes an image from the clipboard.
/// </summary>
/// <param name="toNewLayer">Set to TRUE to paste into a
/// new layer. Otherwise, will paste to the current layer.</param>
/// <param name="x">Optional. Location within image to paste to.
/// Position will be adjusted if pasted image would hang
/// over right or bottom edges of canvas.</param>
/// <param name="y">Optional. Location within image to paste to.
/// Position will be adjusted if pasted image would hang
/// over right or bottom edges of canvas.</param>
public void Paste (bool toNewLayer, int x = 0, int y = 0)
{
// Create a compound history item for recording several
// operations so that they can all be undone/redone together.
CompoundHistoryItem paste_action;
if (toNewLayer)
{
paste_action = new CompoundHistoryItem (Stock.Paste, Catalog.GetString ("Paste Into New Layer"));
}
else
{
paste_action = new CompoundHistoryItem (Stock.Paste, Catalog.GetString ("Paste"));
}
Gtk.Clipboard cb = Gtk.Clipboard.Get (Gdk.Atom.Intern ("CLIPBOARD", false));
// See if the current tool wants to handle the paste
// operation (e.g., the text tool could paste text)
if (!toNewLayer)
{
if (PintaCore.Tools.CurrentTool.TryHandlePaste (cb))
return;
}
PintaCore.Tools.Commit ();
// Don't dispose this, as we're going to give it to the history
Gdk.Pixbuf cbImage = null;
if (cb.WaitIsImageAvailable ()) {
cbImage = cb.WaitForImage ();
}
if (cbImage == null)
{
ShowClipboardEmptyDialog();
return;
}
Gdk.Size canvas_size = PintaCore.Workspace.ImageSize;
// If the image being pasted is larger than the canvas size, allow the user to optionally resize the canvas
if (cbImage.Width > canvas_size.Width || cbImage.Height > canvas_size.Height)
{
ResponseType response = ShowExpandCanvasDialog ();
if (response == ResponseType.Accept)
{
PintaCore.Workspace.ResizeCanvas (cbImage.Width, cbImage.Height,
Pinta.Core.Anchor.Center, paste_action);
PintaCore.Actions.View.UpdateCanvasScale ();
}
else if (response == ResponseType.Cancel || response == ResponseType.DeleteEvent)
{
return;
}
}
// If the pasted image would fall off bottom- or right-
// side of image, adjust paste position
x = Math.Max (0, Math.Min (x, canvas_size.Width - cbImage.Width));
y = Math.Max (0, Math.Min (y, canvas_size.Height - cbImage.Height));
// If requested, create a new layer, make it the current
// layer and record it's creation in the history
if (toNewLayer)
{
UserLayer l = AddNewLayer (string.Empty);
SetCurrentUserLayer (l);
paste_action.Push (new AddLayerHistoryItem ("Menu.Layers.AddNewLayer.png", Catalog.GetString ("Add New Layer"), UserLayers.IndexOf (l)));
}
// Copy the paste to the temp layer, which should be at least the size of this document.
CreateSelectionLayer (Math.Max(ImageSize.Width, cbImage.Width),
Math.Max(ImageSize.Height, cbImage.Height));
ShowSelectionLayer = true;
using (Cairo.Context g = new Cairo.Context (SelectionLayer.Surface))
{
g.DrawPixbuf (cbImage, new Cairo.Point (0, 0));
}
SelectionLayer.Transform.InitIdentity();
SelectionLayer.Transform.Translate (x, y);
PintaCore.Tools.SetCurrentTool (Catalog.GetString ("Move Selected Pixels"));
DocumentSelection old_selection = Selection.Clone();
bool old_show_selection = ShowSelection;
Selection.CreateRectangleSelection (new Cairo.Rectangle (x, y, cbImage.Width, cbImage.Height));
ShowSelection = true;
Workspace.Invalidate ();
paste_action.Push (new PasteHistoryItem (cbImage, old_selection, old_show_selection));
History.PushNewItem (paste_action);
}
private ResponseType ShowExpandCanvasDialog ()
{
const string markup = "<span weight=\"bold\" size=\"larger\">{0}</span>\n\n{1}";
string primary = Catalog.GetString ("Image larger than canvas");
string secondary = Catalog.GetString ("The image being pasted is larger than the canvas size. What would you like to do?");
string message = string.Format (markup, primary, secondary);
var enlarge_dialog = new MessageDialog (PintaCore.Chrome.MainWindow, DialogFlags.Modal, MessageType.Question, ButtonsType.None, message);
enlarge_dialog.AddButton (Catalog.GetString ("Expand canvas"), ResponseType.Accept);
enlarge_dialog.AddButton (Catalog.GetString ("Don't change canvas size"), ResponseType.Reject);
enlarge_dialog.AddButton (Stock.Cancel, ResponseType.Cancel);
enlarge_dialog.DefaultResponse = ResponseType.Accept;
ResponseType response = (ResponseType)enlarge_dialog.Run ();
enlarge_dialog.Destroy ();
return response;
}
public static void ShowClipboardEmptyDialog()
{
var primary = Catalog.GetString ("Image cannot be pasted");
var secondary = Catalog.GetString ("The clipboard does not contain an image.");
var markup = "<span weight=\"bold\" size=\"larger\">{0}</span>\n\n{1}\n";
markup = string.Format (markup, primary, secondary);
var md = new MessageDialog (Pinta.Core.PintaCore.Chrome.MainWindow, DialogFlags.Modal,
MessageType.Error, ButtonsType.None, true,
markup);
md.AddButton (Stock.Ok, ResponseType.Yes);
md.Run ();
md.Destroy ();
}
/// <summary>
/// Signal to the TextTool that an ImageSurface was cloned.
/// </summary>
public void SignalSurfaceCloned()
{
if (LayerCloned != null)
{
LayerCloned();
}
}
#endregion
#region Protected Methods
protected void OnIsDirtyChanged ()
{
if (IsDirtyChanged != null)
IsDirtyChanged (this, EventArgs.Empty);
}
protected void OnRenamed ()
{
if (Renamed != null)
Renamed (this, EventArgs.Empty);
}
#endregion
#region Private Methods
private void RaiseLayerPropertyChangedEvent (object sender, PropertyChangedEventArgs e)
{
PintaCore.Layers.RaiseLayerPropertyChangedEvent (sender, e);
}
private void OnSelectionChanged ()
{
if (SelectionChanged != null)
SelectionChanged.Invoke(this, EventArgs.Empty);
}
#endregion
#region Public Events
public event EventHandler IsDirtyChanged;
public event EventHandler Renamed;
public event LayerCloneEvent LayerCloned;
public event EventHandler SelectionChanged;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.ReflectionModel
{
public struct LazyMemberInfo
{
private readonly MemberTypes _memberType;
private MemberInfo[] _accessors;
private readonly Func<MemberInfo[]> _accessorsCreator;
public LazyMemberInfo(MemberInfo member)
{
Requires.NotNull(member, nameof(member));
EnsureSupportedMemberType(member.MemberType, "member");
_accessorsCreator = null;
_memberType = member.MemberType;
switch(_memberType)
{
case MemberTypes.Property:
PropertyInfo property = (PropertyInfo)member;
Assumes.NotNull(property);
_accessors = new MemberInfo[] { property.GetGetMethod(true), property.GetSetMethod(true) };
break;
case MemberTypes.Event:
EventInfo event_ = (EventInfo)member;
_accessors = new MemberInfo[] { event_.GetRaiseMethod(true), event_.GetAddMethod(true), event_.GetRemoveMethod(true) };
break;
default:
_accessors = new MemberInfo[] { member };
break;
}
}
public LazyMemberInfo(MemberTypes memberType, params MemberInfo[] accessors)
{
EnsureSupportedMemberType(memberType, "memberType");
Requires.NotNull(accessors, nameof(accessors));
string errorMessage;
if (!LazyMemberInfo.AreAccessorsValid(memberType, accessors, out errorMessage))
{
throw new ArgumentException(errorMessage, "accessors");
}
_memberType = memberType;
_accessors = accessors;
_accessorsCreator = null;
}
public LazyMemberInfo(MemberTypes memberType, Func<MemberInfo[]> accessorsCreator)
{
EnsureSupportedMemberType(memberType, "memberType");
Requires.NotNull(accessorsCreator, nameof(accessorsCreator));
_memberType = memberType;
_accessors = null;
_accessorsCreator = accessorsCreator;
}
public MemberTypes MemberType
{
get { return _memberType; }
}
public MemberInfo[] GetAccessors()
{
if ((_accessors == null) && (_accessorsCreator != null))
{
MemberInfo[] accessors = _accessorsCreator.Invoke();
string errorMessage;
if (!LazyMemberInfo.AreAccessorsValid(MemberType, accessors, out errorMessage))
{
throw new InvalidOperationException(errorMessage);
}
_accessors = accessors;
}
return _accessors;
}
public override int GetHashCode()
{
if (_accessorsCreator != null)
{
return MemberType.GetHashCode() ^ _accessorsCreator.GetHashCode();
}
else
{
Assumes.NotNull(_accessors);
Assumes.NotNull(_accessors[0]);
return MemberType.GetHashCode() ^ _accessors[0].GetHashCode();
}
}
public override bool Equals(object obj)
{
LazyMemberInfo that = (LazyMemberInfo)obj;
// Difefrent member types mean different members
if (_memberType != that._memberType)
{
return false;
}
// if any of the lazy memebers create accessors in a delay-loaded fashion, we simply compare the creators
if ((_accessorsCreator != null) || (that._accessorsCreator != null))
{
return object.Equals(_accessorsCreator, that._accessorsCreator);
}
// we are dealing with explicitly passed accessors in both cases
Assumes.NotNull(_accessors);
Assumes.NotNull(that._accessors);
return _accessors.SequenceEqual(that._accessors);
}
public static bool operator ==(LazyMemberInfo left, LazyMemberInfo right)
{
return left.Equals(right);
}
public static bool operator !=(LazyMemberInfo left, LazyMemberInfo right)
{
return !left.Equals(right);
}
private static void EnsureSupportedMemberType(MemberTypes memberType, string argument)
{
MemberTypes supportedTypes = MemberTypes.TypeInfo | MemberTypes.NestedType | MemberTypes.Constructor | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property | MemberTypes.Event;
Requires.IsInMembertypeSet(memberType, argument, supportedTypes);
}
private static bool AreAccessorsValid(MemberTypes memberType, MemberInfo[] accessors, out string errorMessage)
{
errorMessage = string.Empty;
if (accessors == null)
{
errorMessage = SR.LazyMemberInfo_AccessorsNull;
return false;
}
if (accessors.All(accessor => accessor == null))
{
errorMessage = SR.LazyMemberInfo_NoAccessors;
return false;
}
switch (memberType)
{
case MemberTypes.Property:
if (accessors.Length != 2)
{
errorMessage = SR.LazyMemberInfo_InvalidPropertyAccessors_Cardinality;
return false;
}
if (accessors.Where(accessor => (accessor != null) && (accessor.MemberType != MemberTypes.Method)).Any())
{
errorMessage = SR.LazyMemberinfo_InvalidPropertyAccessors_AccessorType;
return false;
}
break;
case MemberTypes.Event:
if (accessors.Length != 3)
{
errorMessage = SR.LazyMemberInfo_InvalidEventAccessors_Cardinality;
return false;
}
if (accessors.Where(accessor => (accessor != null) && (accessor.MemberType != MemberTypes.Method)).Any())
{
errorMessage = SR.LazyMemberinfo_InvalidEventAccessors_AccessorType;
return false;
}
break;
default:
if (
(accessors.Length != 1) ||
((accessors.Length == 1) && (accessors[0].MemberType != memberType)))
{
errorMessage = string.Format(CultureInfo.CurrentCulture, SR.LazyMemberInfo_InvalidAccessorOnSimpleMember, memberType);
return false;
}
break;
}
return true;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Cloud.OsConfig.V1Alpha
{
/// <summary>Resource name for the <c>Instance</c> resource.</summary>
public sealed partial class InstanceName : gax::IResourceName, sys::IEquatable<InstanceName>
{
/// <summary>The possible contents of <see cref="InstanceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/instances/{instance}</c>.
/// </summary>
ProjectLocationInstance = 1,
}
private static gax::PathTemplate s_projectLocationInstance = new gax::PathTemplate("projects/{project}/locations/{location}/instances/{instance}");
/// <summary>Creates a <see cref="InstanceName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="InstanceName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static InstanceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new InstanceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="InstanceName"/> with the pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="InstanceName"/> constructed from the provided ids.</returns>
public static InstanceName FromProjectLocationInstance(string projectId, string locationId, string instanceId) =>
new InstanceName(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string instanceId) =>
FormatProjectLocationInstance(projectId, locationId, instanceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InstanceName"/> with pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}</c>.
/// </returns>
public static string FormatProjectLocationInstance(string projectId, string locationId, string instanceId) =>
s_projectLocationInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)));
/// <summary>Parses the given resource name string into a new <see cref="InstanceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item>
/// </list>
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="InstanceName"/> if successful.</returns>
public static InstanceName Parse(string instanceName) => Parse(instanceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="InstanceName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="InstanceName"/> if successful.</returns>
public static InstanceName Parse(string instanceName, bool allowUnparsed) =>
TryParse(instanceName, allowUnparsed, out InstanceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item>
/// </list>
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string instanceName, out InstanceName result) => TryParse(instanceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string instanceName, bool allowUnparsed, out InstanceName result)
{
gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationInstance.TryParseName(instanceName, out resourceName))
{
result = FromProjectLocationInstance(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(instanceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private InstanceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
InstanceId = instanceId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="InstanceName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/instances/{instance}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param>
public InstanceName(string projectId, string locationId, string instanceId) : this(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string InstanceId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationInstance: return s_projectLocationInstance.Expand(ProjectId, LocationId, InstanceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as InstanceName);
/// <inheritdoc/>
public bool Equals(InstanceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(InstanceName a, InstanceName b) => !(a == b);
}
}
| |
//
// mcs/class/System.Data/System.Data/XmlDataLoader.cs
//
// Purpose: Loads XmlDocument to DataSet
//
// class: XmlDataLoader
// assembly: System.Data.dll
// namespace: System.Data
//
// Author:
// Ville Palo <vi64pa@koti.soon.fi>
// Atsushi Enomoto <atsushi@ximian.com>
//
// (c)copyright 2002 Ville Palo
// (C)2004 Novell Inc.
//
// XmlDataLoader is included within the Mono Class Library.
//
//
// Copyright (C) 2004 Novell, Inc (http://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.
//
using System;
using System.Data;
using System.Xml;
using System.Collections;
using System.Globalization;
namespace System.Data
{
internal class XmlDataLoader
{
private DataSet DSet;
public XmlDataLoader (DataSet set)
{
DSet = set;
}
public XmlReadMode LoadData (XmlReader reader, XmlReadMode mode)
{
XmlReadMode Result = mode;
switch (mode) {
case XmlReadMode.Auto:
Result = DSet.Tables.Count == 0 ? XmlReadMode.InferSchema : XmlReadMode.IgnoreSchema;
ReadModeSchema (reader, DSet.Tables.Count == 0 ? XmlReadMode.Auto : XmlReadMode.IgnoreSchema);
break;
case XmlReadMode.InferSchema:
Result = XmlReadMode.InferSchema;
ReadModeSchema (reader, mode);
break;
case XmlReadMode.IgnoreSchema:
Result = XmlReadMode.IgnoreSchema;
ReadModeSchema (reader, mode);
break;
default:
reader.Skip ();
break;
}
return Result;
}
#region reading
// Read information from the reader.
private void ReadModeSchema (XmlReader reader, XmlReadMode mode)
{
bool inferSchema = mode == XmlReadMode.InferSchema || mode == XmlReadMode.Auto;
bool fillRows = mode != XmlReadMode.InferSchema;
// This check is required for full DiffGram.
// It is not described in MSDN and it is impossible
// with WriteXml(), but when writing XML using
// XmlSerializer, the output is like this:
// <dataset>
// <schema>...</schema>
// <diffgram>...</diffgram>
// </dataset>
//
// FIXME: This, this check should (also) be done
// after reading the top-level element.
//check if the current element is schema.
if (reader.LocalName == "schema") {
if (mode != XmlReadMode.Auto)
reader.Skip(); // skip the schema node.
else
DSet.ReadXmlSchema(reader);
reader.MoveToContent();
}
// load an XmlDocument from the reader.
XmlDocument doc = new XmlDocument ();
doc.Load (reader);
if (doc.DocumentElement == null)
return;
// treatment for .net compliancy :
// if xml representing dataset has exactly depth of 2 elements,
// than the root element actually represents datatable and not dataset
// so we add new root element to doc
// in order to create an element representing dataset.
//
// FIXME: Consider attributes.
// <root a='1' b='2' /> is regarded as a valid DataTable.
int rootNodeDepth = XmlNodeElementsDepth(doc.DocumentElement);
switch (rootNodeDepth) {
case 1:
if (inferSchema) {
DSet.DataSetName = doc.DocumentElement.LocalName;
DSet.Prefix = doc.DocumentElement.Prefix;
DSet.Namespace = doc.DocumentElement.NamespaceURI;
}
return;
case 2:
// create new document
XmlDocument newDoc = new XmlDocument();
// create element for dataset
XmlElement datasetElement = newDoc.CreateElement("dummy");
// make the new created element to be the new doc root
newDoc.AppendChild(datasetElement);
// import all the elements from doc and insert them into new doc
XmlNode root = newDoc.ImportNode(doc.DocumentElement,true);
datasetElement.AppendChild(root);
doc = newDoc;
break;
default:
if (inferSchema) {
DSet.DataSetName = doc.DocumentElement.LocalName;
DSet.Prefix = doc.DocumentElement.Prefix;
DSet.Namespace = doc.DocumentElement.NamespaceURI;
}
break;
}
// set EnforceConstraint to false - we do not want any validation during
// load time.
bool origEnforceConstraint = DSet.EnforceConstraints;
DSet.EnforceConstraints = false;
// The childs are tables.
XmlNodeList nList = doc.DocumentElement.ChildNodes;
// FIXME: When reading DataTable (not DataSet),
// the nodes are column items, not rows.
for (int i = 0; i < nList.Count; i++) {
XmlNode node = nList[i];
// node represents a table onky if it is of type XmlNodeType.Element
if (node.NodeType == XmlNodeType.Element) {
AddRowToTable(node, null, inferSchema, fillRows);
}
}
// set the EnforceConstraints to original value;
DSet.EnforceConstraints = origEnforceConstraint;
}
#endregion // reading
#region Private helper methods
private void ReadColumns (XmlReader reader, DataRow row, DataTable table, string TableName)
{
do {
if (reader.NodeType == XmlNodeType.Element) {
DataColumn col = table.Columns [reader.LocalName];
if (col != null) {
row [col] = StringToObject (col.DataType, reader.Value);
}
reader.Read ();
}
else {
reader.Read ();
}
} while (table.TableName != reader.LocalName
|| reader.NodeType != XmlNodeType.EndElement);
}
internal static object StringToObject (Type type, string value)
{
if (type == null) return value;
switch (Type.GetTypeCode (type)) {
case TypeCode.Boolean: return XmlConvert.ToBoolean (value);
case TypeCode.Byte: return XmlConvert.ToByte (value);
case TypeCode.Char: return (char)XmlConvert.ToInt32 (value);
case TypeCode.DateTime: return XmlConvert.ToDateTime (value);
case TypeCode.Decimal: return XmlConvert.ToDecimal (value);
case TypeCode.Double: return XmlConvert.ToDouble (value);
case TypeCode.Int16: return XmlConvert.ToInt16 (value);
case TypeCode.Int32: return XmlConvert.ToInt32 (value);
case TypeCode.Int64: return XmlConvert.ToInt64 (value);
case TypeCode.SByte: return XmlConvert.ToSByte (value);
case TypeCode.Single: return XmlConvert.ToSingle (value);
case TypeCode.UInt16: return XmlConvert.ToUInt16 (value);
case TypeCode.UInt32: return XmlConvert.ToUInt32 (value);
case TypeCode.UInt64: return XmlConvert.ToUInt64 (value);
}
if (type == typeof (TimeSpan)) return XmlConvert.ToTimeSpan (value);
if (type == typeof (Guid)) return XmlConvert.ToGuid (value);
if (type == typeof (byte[])) return Convert.FromBase64String (value);
return Convert.ChangeType (value, type);
}
private void AddRowToTable(XmlNode tableNode, DataColumn relationColumn, bool inferSchema, bool fillRows)
{
Hashtable rowValue = new Hashtable();
DataTable table;
// Check if the table exists in the DataSet. If not create one.
if (DSet.Tables.Contains(tableNode.LocalName))
table = DSet.Tables[tableNode.LocalName];
else if (inferSchema) {
table = new DataTable(tableNode.LocalName);
DSet.Tables.Add(table);
}
else
return;
// For elements that are inferred as tables and that contain text
// but have no child elements, a new column named "TableName_Text"
// is created for the text of each of the elements.
// If an element is inferred as a table and has text, but also has child elements,
// the text is ignored.
// Note : if an element is inferred as a table and has text
// and has no child elements,
// but the repeated ements of this table have child elements,
// then the text is ignored.
if(!HaveChildElements(tableNode) && HaveText(tableNode) &&
!IsRepeatedHaveChildNodes(tableNode)) {
string columnName = tableNode.Name + "_Text";
if (!table.Columns.Contains(columnName)) {
table.Columns.Add(columnName);
}
rowValue.Add(columnName, tableNode.InnerText);
}
// Get the child nodes of the table. Any child can be one of the following tow:
// 1. DataTable - if there was a relation with another table..
// 2. DataColumn - column of the current table.
XmlNodeList childList = tableNode.ChildNodes;
for (int i = 0; i < childList.Count; i++) {
XmlNode childNode = childList[i];
// we are looping through elements only
// Note : if an element is inferred as a table and has text, but also has child elements,
// the text is ignored.
if (childNode.NodeType != XmlNodeType.Element)
continue;
// Elements that have attributes are inferred as tables.
// Elements that have child elements are inferred as tables.
// Elements that repeat are inferred as a single table.
if (IsInferedAsTable(childNode)) {
// child node infered as table
if (inferSchema) {
// We need to create new column for the relation between the current
// table and the new table we found (the child table).
string newRelationColumnName = table.TableName + "_Id";
if (!table.Columns.Contains(newRelationColumnName)) {
DataColumn newRelationColumn = new DataColumn(newRelationColumnName, typeof(int));
newRelationColumn.AllowDBNull = false;
newRelationColumn.AutoIncrement = true;
// we do not want to serialize this column so MappingType is Hidden.
newRelationColumn.ColumnMapping = MappingType.Hidden;
table.Columns.Add(newRelationColumn);
}
// Add a row to the new table we found.
AddRowToTable(childNode, table.Columns[newRelationColumnName], inferSchema, fillRows);
}
else
AddRowToTable(childNode, null, inferSchema, fillRows);
}
else {
// Elements that have no attributes or child elements, and do not repeat,
// are inferred as columns.
object val = null;
if (childNode.FirstChild != null)
val = childNode.FirstChild.Value;
else
val = "";
if (table.Columns.Contains(childNode.LocalName))
rowValue.Add(childNode.LocalName, val);
else if (inferSchema) {
table.Columns.Add(childNode.LocalName);
rowValue.Add(childNode.LocalName, val);
}
}
}
// Column can be attribute of the table element.
XmlAttributeCollection aCollection = tableNode.Attributes;
for (int i = 0; i < aCollection.Count; i++) {
XmlAttribute attr = aCollection[i];
//the atrribute can be the namespace.
if (attr.Prefix.Equals("xmlns"))
table.Namespace = attr.Value;
else { // the attribute is a column.
if (!table.Columns.Contains(attr.LocalName)) {
DataColumn col = table.Columns.Add(attr.LocalName);
col.ColumnMapping = MappingType.Attribute;
}
table.Columns[attr.LocalName].Namespace = table.Namespace;
rowValue.Add(attr.LocalName, attr.Value);
}
}
// If the current table is a child table we need to add a new column for the relation
// and add a new relation to the DataSet.
if (relationColumn != null) {
if (!table.Columns.Contains(relationColumn.ColumnName)) {
DataColumn dc = new DataColumn(relationColumn.ColumnName, typeof(int));
// we do not want to serialize this column so MappingType is Hidden.
dc.ColumnMapping = MappingType.Hidden;
table.Columns.Add(dc);
// Convention of relation name is: ParentTableName_ChildTableName
DataRelation dr = new DataRelation(relationColumn.Table.TableName + "_" + dc.Table.TableName, relationColumn, dc);
dr.Nested = true;
DSet.Relations.Add(dr);
UniqueConstraint.SetAsPrimaryKey (dr.ParentTable.Constraints, dr.ParentKeyConstraint);
}
rowValue.Add (relationColumn.ColumnName, relationColumn.GetAutoIncrementValue());
}
// Create new row and add all values to the row.
// then add it to the table.
DataRow row = table.NewRow ();
IDictionaryEnumerator enumerator = rowValue.GetEnumerator ();
while (enumerator.MoveNext ()) {
row [enumerator.Key.ToString ()] = StringToObject (table.Columns[enumerator.Key.ToString ()].DataType, enumerator.Value.ToString ());
}
if (fillRows)
table.Rows.Add (row);
}
// this method calculates the depth of child nodes tree
// and it counts nodes of type XmlNodeType.Element only
private static int XmlNodeElementsDepth(XmlNode node)
{
int maxDepth = -1;
if ((node != null)) {
if ((node.HasChildNodes) && (node.FirstChild.NodeType == XmlNodeType.Element)) {
for (int i=0; i<node.ChildNodes.Count; i++) {
if (node.ChildNodes[i].NodeType == XmlNodeType.Element) {
int childDepth = XmlNodeElementsDepth(node.ChildNodes[i]);
maxDepth = (maxDepth < childDepth) ? childDepth : maxDepth;
}
}
}
else {
return 1;
}
}
else {
return -1;
}
return (maxDepth + 1);
}
private bool HaveChildElements(XmlNode node)
{
bool haveChildElements = true;
if(node.ChildNodes.Count > 0) {
foreach(XmlNode childNode in node.ChildNodes) {
if (childNode.NodeType != XmlNodeType.Element) {
haveChildElements = false;
break;
}
}
}
else {
haveChildElements = false;
}
return haveChildElements;
}
private bool HaveText(XmlNode node)
{
bool haveText = true;
if(node.ChildNodes.Count > 0) {
foreach(XmlNode childNode in node.ChildNodes) {
if (childNode.NodeType != XmlNodeType.Text) {
haveText = false;
break;
}
}
}
else {
haveText = false;
}
return haveText;
}
private bool IsRepeat(XmlNode node)
{
bool isRepeat = false;
if(node.ParentNode != null) {
foreach(XmlNode childNode in node.ParentNode.ChildNodes) {
if(childNode != node && childNode.Name == node.Name) {
isRepeat = true;
break;
}
}
}
return isRepeat;
}
private bool HaveAttributes(XmlNode node)
{
return (node.Attributes != null && node.Attributes.Count > 0);
}
private bool IsInferedAsTable(XmlNode node)
{
// Elements that have attributes are inferred as tables.
// Elements that have child elements are inferred as tables.
// Elements that repeat are inferred as a single table.
return (HaveChildElements(node) || HaveAttributes(node) ||
IsRepeat(node));
}
/// <summary>
/// Returns true is any node that is repeated node for the node supplied
/// (i.e. is child node of node's parent, have the same name and is not the node itself)
/// have child elements
/// </summary>
private bool IsRepeatedHaveChildNodes(XmlNode node)
{
bool isRepeatedHaveChildElements = false;
if(node.ParentNode != null) {
foreach(XmlNode childNode in node.ParentNode.ChildNodes) {
if(childNode != node && childNode.Name == node.Name) {
if (HaveChildElements(childNode)) {
isRepeatedHaveChildElements = true;
break;
}
}
}
}
return isRepeatedHaveChildElements;
}
#endregion // Private helper methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition
{
/// <summary>
/// The stage of the A record set definition allowing to add additional A records or
/// attach the record set to the parent.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithARecordIPv4AddressOrAttachable<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithARecordIPv4Address<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The entirety of a DNS zone record set definition as a part of parent definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IDefinition<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IARecordSetBlank<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithARecordIPv4Address<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithARecordIPv4AddressOrAttachable<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IAaaaRecordSetBlank<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAaaaRecordIPv6Address<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAaaaRecordIPv6AddressOrAttachable<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.ICaaRecordSetBlank<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithCaaRecordEntry<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithCaaRecordEntryOrAttachable<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.ICNameRecordSetBlank<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithCNameRecordAlias<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithCNameRecordSetAttachable<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IMXRecordSetBlank<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithMXRecordMailExchange<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithMXRecordMailExchangeOrAttachable<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.INSRecordSetBlank<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithNSRecordNameServer<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithNSRecordNameServerOrAttachable<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IPtrRecordSetBlank<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithPtrRecordTargetDomainName<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithPtrRecordTargetDomainNameOrAttachable<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.ISrvRecordSetBlank<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithSrvRecordEntry<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithSrvRecordEntryOrAttachable<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.ITxtRecordSetBlank<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithTxtRecordTextValue<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithTxtRecordTextValueOrAttachable<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The stage of the record set definition allowing to specify the Time To Live (TTL) for the records in this record set.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithTtl<ParentT>
{
/// <summary>
/// Specifies the Time To Live for the records in the record set.
/// </summary>
/// <param name="ttlInSeconds">TTL in seconds.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT> WithTimeToLive(long ttlInSeconds);
}
/// <summary>
/// The first stage of a AAAA record definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IAaaaRecordSetBlank<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAaaaRecordIPv6Address<ParentT>
{
}
/// <summary>
/// The first stage of a SRV record definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface ISrvRecordSetBlank<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithSrvRecordEntry<ParentT>
{
}
/// <summary>
/// The stage of the CNAME record set definition allowing attach the record set to the parent.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithCNameRecordSetAttachable<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The stage of the NS record set definition allowing to add additional NS records or
/// attach the record set to the parent.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithNSRecordNameServerOrAttachable<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithNSRecordNameServer<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The stage of a CNAME record definition allowing to add alias.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithCNameRecordAlias<ParentT>
{
/// <summary>
/// Creates a CNAME record with the provided alias.
/// </summary>
/// <param name="alias">The alias.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithCNameRecordSetAttachable<ParentT> WithAlias(string alias);
}
/// <summary>
/// The stage of the record set definition allowing to specify metadata.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithMetadata<ParentT>
{
/// <summary>
/// Adds a metadata to the resource.
/// </summary>
/// <param name="key">The key for the metadata.</param>
/// <param name="value">The value for the metadata.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT> WithMetadata(string key, string value);
}
/// <summary>
/// The stage of the record set definition allowing to enable ETag validation.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithETagCheck<ParentT>
{
/// <summary>
/// Specifies that If-None-Match header needs to set to to prevent updating an existing record set.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT> WithETagCheck();
}
/// <summary>
/// The stage of the AAAA record set definition allowing to add additional AAAA records or
/// attach the record set to the parent.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithAaaaRecordIPv6AddressOrAttachable<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAaaaRecordIPv6Address<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The stage of the MX record set definition allowing to add additional MX records or attach the record set
/// to the parent.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithMXRecordMailExchangeOrAttachable<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithMXRecordMailExchange<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The stage of the NS record set definition allowing to add a NS record.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithNSRecordNameServer<ParentT>
{
/// <summary>
/// Creates a NS record with the provided name server in this record set.
/// </summary>
/// <param name="nameServerHostName">The name server host name.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithNSRecordNameServerOrAttachable<ParentT> WithNameServer(string nameServerHostName);
}
/// <summary>
/// The first stage of a PTR record definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IPtrRecordSetBlank<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithPtrRecordTargetDomainName<ParentT>
{
}
/// <summary>
/// The stage of the SRV record set definition allowing to add additional SRV records or attach the record set
/// to the parent.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithSrvRecordEntryOrAttachable<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithSrvRecordEntry<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The stage of the TXT record set definition allowing to add additional TXT records or attach the record set
/// to the parent.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithTxtRecordTextValueOrAttachable<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithTxtRecordTextValue<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The final stage of the DNS zone record set definition.
/// At this stage, any remaining optional settings can be specified, or the DNS zone record set
/// definition can be attached to the parent traffic manager profile definition using DnsRecordSet.DefinitionStages.WithAttach.attach().
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithAttach<ParentT> :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithTtl<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithMetadata<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithETagCheck<ParentT>
{
}
/// <summary>
/// The first stage of a CNAME record set definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface ICNameRecordSetBlank<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithCNameRecordAlias<ParentT>
{
}
/// <summary>
/// The first stage of a NS record definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface INSRecordSetBlank<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithNSRecordNameServer<ParentT>
{
}
/// <summary>
/// The stage of the MX record set definition allowing to add first MX record.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithMXRecordMailExchange<ParentT>
{
/// <summary>
/// Creates and assigns priority to a MX record with the provided mail exchange server in this record set.
/// </summary>
/// <param name="mailExchangeHostName">The host name of the mail exchange server.</param>
/// <param name="priority">The priority for the mail exchange host, lower the value higher the priority.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithMXRecordMailExchangeOrAttachable<ParentT> WithMailExchange(string mailExchangeHostName, int priority);
}
/// <summary>
/// The stage of the SRV record definition allowing to add first service record.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithSrvRecordEntry<ParentT>
{
/// <summary>
/// Specifies a service record for a service.
/// </summary>
/// <param name="target">The canonical name of the target host running the service.</param>
/// <param name="port">The port on which the service is bounded.</param>
/// <param name="priority">The priority of the target host, lower the value higher the priority.</param>
/// <param name="weight">The relative weight (preference) of the records with the same priority, higher the value more the preference.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithSrvRecordEntryOrAttachable<ParentT> WithRecord(string target, int port, int priority, int weight);
}
/// <summary>
/// The stage of the Caa record definition allowing to add first service record.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithCaaRecordEntry<ParentT>
{
/// <summary>
/// Specifies a Caa record for a service.
/// </summary>
/// <param name="flags">The flags for this CAA record as an integer between 0 and 255.</param>
/// <param name="tag">The tag for this CAA record.</param>
/// <param name="value">The value for this CAA record.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithCaaRecordEntryOrAttachable<ParentT> WithRecord(int flags, string tag, string value);
}
/// <summary>
/// The stage of the TXT record definition allowing to add first TXT record.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithTxtRecordTextValue<ParentT>
{
/// <summary>
/// Creates a Txt record with the given text in this record set.
/// </summary>
/// <param name="text">The text value.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithTxtRecordTextValueOrAttachable<ParentT> WithText(string text);
}
/// <summary>
/// The stage of the Caa record set definition allowing to add additional Caa records or attach the record set
/// to the parent.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithCaaRecordEntryOrAttachable<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithCaaRecordEntry<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The stage of the A record set definition allowing to add first A record.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithARecordIPv4Address<ParentT>
{
/// <summary>
/// Creates an A record with the provided IPv4 address in this record set.
/// </summary>
/// <param name="ipv4Address">The IPv4 address.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithARecordIPv4AddressOrAttachable<ParentT> WithIPv4Address(string ipv4Address);
}
/// <summary>
/// The stage of the AAAA record set definition allowing to add first AAAA record.
/// </summary>
/// <typeparam name="ParentT">The return type of WithAttach.attach().</typeparam>
public interface IWithAaaaRecordIPv6Address<ParentT>
{
/// <summary>
/// Creates an AAAA record with the provided IPv6 address in this record set.
/// </summary>
/// <param name="ipv6Address">An IPv6 address.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAaaaRecordIPv6AddressOrAttachable<ParentT> WithIPv6Address(string ipv6Address);
}
/// <summary>
/// The first stage of a MX record definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IMXRecordSetBlank<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithMXRecordMailExchange<ParentT>
{
}
/// <summary>
/// The stage of the PTR record set definition allowing to add additional PTR records or
/// attach the record set to the parent.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithPtrRecordTargetDomainNameOrAttachable<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithPtrRecordTargetDomainName<ParentT>,
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithAttach<ParentT>
{
}
/// <summary>
/// The stage of the PTR record set definition allowing to add first CNAME record.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IWithPtrRecordTargetDomainName<ParentT>
{
/// <summary>
/// Creates a PTR record with the provided target domain name in this record set.
/// </summary>
/// <param name="targetDomainName">The target domain name.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithPtrRecordTargetDomainNameOrAttachable<ParentT> WithTargetDomainName(string targetDomainName);
}
/// <summary>
/// The first stage of an A record definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface IARecordSetBlank<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithARecordIPv4Address<ParentT>
{
}
/// <summary>
/// The first stage of a TXT record definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface ITxtRecordSetBlank<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithTxtRecordTextValue<ParentT>
{
}
/// <summary>
/// The first stage of a Caa record definition.
/// </summary>
/// <typeparam name="ParentT">The stage of the parent definition to return to after attaching this definition.</typeparam>
public interface ICaaRecordSetBlank<ParentT> :
Microsoft.Azure.Management.Dns.Fluent.DnsRecordSet.Definition.IWithCaaRecordEntry<ParentT>
{
}
}
| |
/*
* Copyright (c) 2009 Jim Radford http://www.jimradford.com
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Microsoft.Win32;
using WeifenLuo.WinFormsUI.Docking;
using log4net;
using System.Xml.Serialization;
using System.IO;
using System.Collections;
using System.Reflection;
namespace SuperPutty.Data
{
public enum ConnectionProtocol
{
SSH,
SSH2,
Telnet,
Rlogin,
Raw,
Serial,
Cygterm,
Mintty
}
public class SessionData : IComparable, ICloneable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(SessionData));
/// <summary>
/// Full session id (includes path for session tree)
/// </summary>
private string _SessionId;
[XmlAttribute]
public string SessionId
{
get { return this._SessionId; }
set
{
this.OldSessionId = SessionId;
this._SessionId = value;
}
}
internal string OldSessionId { get; set; }
private string _OldName;
[XmlIgnore]
public string OldName
{
get { return _OldName; }
set { _OldName = value; }
}
private string _SessionName;
[XmlAttribute]
public string SessionName
{
get { return _SessionName; }
set { OldName = _SessionName;
_SessionName = value;
if (SessionId == null)
{
SessionId = value;
}
}
}
private string _ImageKey;
[XmlAttribute]
public string ImageKey
{
get { return _ImageKey; }
set { _ImageKey = value; }
}
private string _Host;
[XmlAttribute]
public string Host
{
get { return _Host; }
set { _Host = value; }
}
private int _Port;
[XmlAttribute]
public int Port
{
get { return _Port; }
set { _Port = value; }
}
private ConnectionProtocol _Proto;
[XmlAttribute]
public ConnectionProtocol Proto
{
get { return _Proto; }
set { _Proto = value; }
}
private string _PuttySession;
[XmlAttribute]
public string PuttySession
{
get { return _PuttySession; }
set { _PuttySession = value; }
}
private string _Username;
[XmlAttribute]
public string Username
{
get { return _Username; }
set { _Username = value; }
}
private string _Password;
[XmlIgnore]
public string Password
{
get { return _Password; }
set { _Password = value; }
}
private string _ExtraArgs;
[XmlAttribute]
public string ExtraArgs
{
get { return _ExtraArgs; }
set { _ExtraArgs = value; }
}
/* Unused...ignore for now
private string _LastPath = ".";
public string LastPath
{
get { return _LastPath; }
set { _LastPath = value; }
}*/
private DockState m_LastDockstate = DockState.Document;
[XmlIgnore]
public DockState LastDockstate
{
get { return m_LastDockstate; }
set { m_LastDockstate = value; }
}
private bool m_AutoStartSession = false;
[XmlIgnore]
public bool AutoStartSession
{
get { return m_AutoStartSession; }
set { m_AutoStartSession = value; }
}
public SessionData(string sessionName, string hostName, int port, ConnectionProtocol protocol, string sessionConfig)
{
SessionName = sessionName;
Host = hostName;
Port = port;
Proto = protocol;
PuttySession = sessionConfig;
}
public SessionData()
{
}
internal void SaveToRegistry()
{
if (!String.IsNullOrEmpty(this.SessionName)
&& !String.IsNullOrEmpty(this.Host)
&& this.Port >= 0)
{
// detect if session was renamed
if (!String.IsNullOrEmpty(this.OldName) && this.OldName != this.SessionName)
{
RegistryRemove(this.OldName);
}
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions\" + this.SessionName, true);
if (key == null)
{
key = Registry.CurrentUser.CreateSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions\" + this.SessionName);
}
if (key != null)
{
key.SetValue("Host", this.Host);
key.SetValue("Port", this.Port);
key.SetValue("Proto", this.Proto);
key.SetValue("PuttySession", this.PuttySession);
if(!String.IsNullOrEmpty(this.Username))
key.SetValue("Login", this.Username);
//key.SetValue("Last Path", this.LastPath);
if(this.LastDockstate != DockState.Hidden && this.LastDockstate != DockState.Unknown)
key.SetValue("Last Dock", (int)this.LastDockstate);
key.SetValue("Auto Start", this.AutoStartSession);
if (this.SessionId != null)
{
key.SetValue("SessionId", this.SessionId);
}
key.Close();
}
else
{
Logger.Log("Unable to create registry key for " + this.SessionName);
}
}
}
void RegistryRemove(string sessionName)
{
if (!String.IsNullOrEmpty(sessionName))
{
Log.DebugFormat("Removing session, name={0}", sessionName);
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions", true);
try
{
if (key.OpenSubKey(sessionName) != null)
{
key.DeleteSubKeyTree(sessionName);
key.Close();
}
}
catch (UnauthorizedAccessException e)
{
Logger.Log(e);
}
}
}
/// <summary>
/// Read any existing saved sessions from the registry, decode and populate a list containing the data
/// </summary>
/// <returns>A list containing the entries retrieved from the registry</returns>
public static List<SessionData> LoadSessionsFromRegistry()
{
Log.Info("LoadSessionsFromRegistry...");
List<SessionData> sessionList = new List<SessionData>();
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions");
if (key != null)
{
string[] sessionKeys = key.GetSubKeyNames();
foreach (string session in sessionKeys)
{
SessionData sessionData = new SessionData();
RegistryKey itemKey = key.OpenSubKey(session);
if (itemKey != null)
{
sessionData.Host = (string)itemKey.GetValue("Host", "");
sessionData.Port = (int)itemKey.GetValue("Port", 22);
sessionData.Proto = (ConnectionProtocol)Enum.Parse(typeof(ConnectionProtocol), (string)itemKey.GetValue("Proto", "SSH"));
sessionData.PuttySession = (string)itemKey.GetValue("PuttySession", "Default Session");
sessionData.SessionName = session;
sessionData.SessionId = (string)itemKey.GetValue("SessionId", session);
sessionData.Username = (string)itemKey.GetValue("Login", "");
sessionData.LastDockstate = (DockState)itemKey.GetValue("Last Dock", DockState.Document);
sessionData.AutoStartSession = bool.Parse((string)itemKey.GetValue("Auto Start", "False"));
sessionList.Add(sessionData);
}
}
}
return sessionList;
}
public static List<SessionData> LoadSessionsFromFile(string fileName)
{
List<SessionData> sessions = new List<SessionData>();
if (File.Exists(fileName))
{
WorkaroundCygwinBug();
XmlSerializer s = new XmlSerializer(sessions.GetType());
using (TextReader r = new StreamReader(fileName))
{
sessions = (List<SessionData>)s.Deserialize(r);
}
Log.InfoFormat("Loaded {0} sessions from {1}", sessions.Count, fileName);
}
else
{
Log.WarnFormat("Could not load sessions, file doesn't exist. file={0}", fileName);
}
return sessions;
}
static void WorkaroundCygwinBug()
{
try
{
// work around known bug with cygwin
Dictionary<string, string> envVars = new Dictionary<string, string>();
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
{
string envVar = (string) de.Key;
if (envVars.ContainsKey(envVar.ToUpper()))
{
// duplicate found... (e.g. TMP and tmp)
Log.DebugFormat("Clearing duplicate envVariable, {0}", envVar);
Environment.SetEnvironmentVariable(envVar, null);
continue;
}
envVars.Add(envVar.ToUpper(), envVar);
}
}
catch (Exception ex)
{
Log.WarnFormat("Error working around cygwin issue: {0}", ex.Message);
}
}
public static void SaveSessionsToFile(List<SessionData> sessions, string fileName)
{
Log.InfoFormat("Saving {0} sessions to {1}", sessions.Count, fileName);
BackUpFiles(fileName, 20);
// sort and save file
sessions.Sort();
XmlSerializer s = new XmlSerializer(sessions.GetType());
using (TextWriter w = new StreamWriter(fileName))
{
s.Serialize(w, sessions);
}
}
private static void BackUpFiles(string fileName, int count)
{
if (File.Exists(fileName) && count > 0)
{
try
{
// backup
string fileBaseName = Path.GetFileNameWithoutExtension(fileName);
string dirName = Path.GetDirectoryName(fileName);
string backupName = Path.Combine(dirName, string.Format("{0}.{1:yyyyMMdd_hhmmss}.XML", fileBaseName, DateTime.Now));
File.Copy(fileName, backupName, true);
// limit last count saves
List<string> oldFiles = new List<string>(Directory.GetFiles(dirName, fileBaseName + ".*.XML"));
oldFiles.Sort();
oldFiles.Reverse();
if (oldFiles.Count > count)
{
for (int i = 20; i < oldFiles.Count; i++)
{
Log.InfoFormat("Cleaning up old file, {0}", oldFiles[i]);
File.Delete(oldFiles[i]);
}
}
}
catch (Exception ex)
{
Log.Error("Error backing up files", ex);
}
}
}
public int CompareTo(object obj)
{
SessionData s = obj as SessionData;
return s == null ? 1 : this.SessionId.CompareTo(s.SessionId);
}
public static string CombineSessionIds(string parent, string child)
{
if (parent == null && child == null)
{
return null;
}
else if (child == null)
{
return parent;
}
else if (parent == null)
{
return child;
}
else
{
return parent + "/" + child;
}
}
public static string GetSessionNameFromId(string sessionId)
{
string[] parts = GetSessionNameParts(sessionId);
return parts.Length > 0 ? parts[parts.Length - 1] : sessionId;
}
public static string[] GetSessionNameParts(string sessionId)
{
return sessionId.Split('/');
}
public static string GetSessionParentId(string sessionId)
{
string parentPath = null;
if (sessionId != null)
{
int idx = sessionId.LastIndexOf('/');
if (idx != -1)
{
parentPath = sessionId.Substring(0, idx);
}
}
return parentPath;
}
public object Clone()
{
SessionData session = new SessionData();
foreach (PropertyInfo pi in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (pi.CanWrite)
{
pi.SetValue(session, pi.GetValue(this, null), null);
}
}
return session;
}
public override string ToString()
{
if (this.Proto == ConnectionProtocol.Cygterm || this.Proto == ConnectionProtocol.Mintty)
{
return string.Format("{0}://{1}", this.Proto.ToString().ToLower(), this.Host);
}
else
{
return string.Format("{0}://{1}:{2}", this.Proto.ToString().ToLower(), this.Host, this.Port);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Binary.Structure;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary writer implementation.
/// </summary>
internal class BinaryWriter : IBinaryWriter, IBinaryRawWriter
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Stream. */
private readonly IBinaryStream _stream;
/** Builder (used only during build). */
private BinaryObjectBuilder _builder;
/** Handles. */
private BinaryHandleDictionary<object, long> _hnds;
/** Metadatas collected during this write session. */
private IDictionary<int, BinaryType> _metas;
/** Current stack frame. */
private Frame _frame;
/** Whether we are currently detaching an object. */
private bool _detaching;
/** Whether we are directly within peer loading object holder. */
private bool _isInWrapper;
/** Schema holder. */
private readonly BinaryObjectSchemaHolder _schema = BinaryObjectSchemaHolder.Current;
/// <summary>
/// Gets the marshaller.
/// </summary>
internal Marshaller Marshaller
{
get { return _marsh; }
}
/// <summary>
/// Write named boolean value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean value.</param>
public void WriteBoolean(string fieldName, bool val)
{
WriteFieldId(fieldName, BinaryUtils.TypeBool);
WriteBooleanField(val);
}
/// <summary>
/// Writes the boolean field.
/// </summary>
/// <param name="val">if set to <c>true</c> [value].</param>
internal void WriteBooleanField(bool val)
{
_stream.WriteByte(BinaryUtils.TypeBool);
_stream.WriteBool(val);
}
/// <summary>
/// Write boolean value.
/// </summary>
/// <param name="val">Boolean value.</param>
public void WriteBoolean(bool val)
{
_stream.WriteBool(val);
}
/// <summary>
/// Write named boolean array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean array.</param>
public void WriteBooleanArray(string fieldName, bool[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayBool);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayBool);
BinaryUtils.WriteBooleanArray(val, _stream);
}
}
/// <summary>
/// Write boolean array.
/// </summary>
/// <param name="val">Boolean array.</param>
public void WriteBooleanArray(bool[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayBool);
BinaryUtils.WriteBooleanArray(val, _stream);
}
}
/// <summary>
/// Write named byte value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte value.</param>
public void WriteByte(string fieldName, byte val)
{
WriteFieldId(fieldName, BinaryUtils.TypeByte);
WriteByteField(val);
}
/// <summary>
/// Write byte field value.
/// </summary>
/// <param name="val">Byte value.</param>
internal void WriteByteField(byte val)
{
_stream.WriteByte(BinaryUtils.TypeByte);
_stream.WriteByte(val);
}
/// <summary>
/// Write byte value.
/// </summary>
/// <param name="val">Byte value.</param>
public void WriteByte(byte val)
{
_stream.WriteByte(val);
}
/// <summary>
/// Write named byte array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte array.</param>
public void WriteByteArray(string fieldName, byte[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayByte);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayByte);
BinaryUtils.WriteByteArray(val, _stream);
}
}
/// <summary>
/// Write byte array.
/// </summary>
/// <param name="val">Byte array.</param>
public void WriteByteArray(byte[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayByte);
BinaryUtils.WriteByteArray(val, _stream);
}
}
/// <summary>
/// Write named short value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short value.</param>
public void WriteShort(string fieldName, short val)
{
WriteFieldId(fieldName, BinaryUtils.TypeShort);
WriteShortField(val);
}
/// <summary>
/// Write short field value.
/// </summary>
/// <param name="val">Short value.</param>
internal void WriteShortField(short val)
{
_stream.WriteByte(BinaryUtils.TypeShort);
_stream.WriteShort(val);
}
/// <summary>
/// Write short value.
/// </summary>
/// <param name="val">Short value.</param>
public void WriteShort(short val)
{
_stream.WriteShort(val);
}
/// <summary>
/// Write named short array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short array.</param>
public void WriteShortArray(string fieldName, short[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayShort);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayShort);
BinaryUtils.WriteShortArray(val, _stream);
}
}
/// <summary>
/// Write short array.
/// </summary>
/// <param name="val">Short array.</param>
public void WriteShortArray(short[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayShort);
BinaryUtils.WriteShortArray(val, _stream);
}
}
/// <summary>
/// Write named char value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char value.</param>
public void WriteChar(string fieldName, char val)
{
WriteFieldId(fieldName, BinaryUtils.TypeChar);
WriteCharField(val);
}
/// <summary>
/// Write char field value.
/// </summary>
/// <param name="val">Char value.</param>
internal void WriteCharField(char val)
{
_stream.WriteByte(BinaryUtils.TypeChar);
_stream.WriteChar(val);
}
/// <summary>
/// Write char value.
/// </summary>
/// <param name="val">Char value.</param>
public void WriteChar(char val)
{
_stream.WriteChar(val);
}
/// <summary>
/// Write named char array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char array.</param>
public void WriteCharArray(string fieldName, char[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayChar);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayChar);
BinaryUtils.WriteCharArray(val, _stream);
}
}
/// <summary>
/// Write char array.
/// </summary>
/// <param name="val">Char array.</param>
public void WriteCharArray(char[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayChar);
BinaryUtils.WriteCharArray(val, _stream);
}
}
/// <summary>
/// Write named int value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int value.</param>
public void WriteInt(string fieldName, int val)
{
WriteFieldId(fieldName, BinaryUtils.TypeInt);
WriteIntField(val);
}
/// <summary>
/// Writes the int field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteIntField(int val)
{
_stream.WriteByte(BinaryUtils.TypeInt);
_stream.WriteInt(val);
}
/// <summary>
/// Write int value.
/// </summary>
/// <param name="val">Int value.</param>
public void WriteInt(int val)
{
_stream.WriteInt(val);
}
/// <summary>
/// Write named int array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int array.</param>
public void WriteIntArray(string fieldName, int[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayInt);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayInt);
BinaryUtils.WriteIntArray(val, _stream);
}
}
/// <summary>
/// Write int array.
/// </summary>
/// <param name="val">Int array.</param>
public void WriteIntArray(int[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayInt);
BinaryUtils.WriteIntArray(val, _stream);
}
}
/// <summary>
/// Write named long value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long value.</param>
public void WriteLong(string fieldName, long val)
{
WriteFieldId(fieldName, BinaryUtils.TypeLong);
WriteLongField(val);
}
/// <summary>
/// Writes the long field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteLongField(long val)
{
_stream.WriteByte(BinaryUtils.TypeLong);
_stream.WriteLong(val);
}
/// <summary>
/// Write long value.
/// </summary>
/// <param name="val">Long value.</param>
public void WriteLong(long val)
{
_stream.WriteLong(val);
}
/// <summary>
/// Write named long array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long array.</param>
public void WriteLongArray(string fieldName, long[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayLong);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayLong);
BinaryUtils.WriteLongArray(val, _stream);
}
}
/// <summary>
/// Write long array.
/// </summary>
/// <param name="val">Long array.</param>
public void WriteLongArray(long[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayLong);
BinaryUtils.WriteLongArray(val, _stream);
}
}
/// <summary>
/// Write named float value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float value.</param>
public void WriteFloat(string fieldName, float val)
{
WriteFieldId(fieldName, BinaryUtils.TypeFloat);
WriteFloatField(val);
}
/// <summary>
/// Writes the float field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteFloatField(float val)
{
_stream.WriteByte(BinaryUtils.TypeFloat);
_stream.WriteFloat(val);
}
/// <summary>
/// Write float value.
/// </summary>
/// <param name="val">Float value.</param>
public void WriteFloat(float val)
{
_stream.WriteFloat(val);
}
/// <summary>
/// Write named float array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float array.</param>
public void WriteFloatArray(string fieldName, float[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayFloat);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayFloat);
BinaryUtils.WriteFloatArray(val, _stream);
}
}
/// <summary>
/// Write float array.
/// </summary>
/// <param name="val">Float array.</param>
public void WriteFloatArray(float[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayFloat);
BinaryUtils.WriteFloatArray(val, _stream);
}
}
/// <summary>
/// Write named double value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double value.</param>
public void WriteDouble(string fieldName, double val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDouble);
WriteDoubleField(val);
}
/// <summary>
/// Writes the double field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteDoubleField(double val)
{
_stream.WriteByte(BinaryUtils.TypeDouble);
_stream.WriteDouble(val);
}
/// <summary>
/// Write double value.
/// </summary>
/// <param name="val">Double value.</param>
public void WriteDouble(double val)
{
_stream.WriteDouble(val);
}
/// <summary>
/// Write named double array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double array.</param>
public void WriteDoubleArray(string fieldName, double[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayDouble);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDouble);
BinaryUtils.WriteDoubleArray(val, _stream);
}
}
/// <summary>
/// Write double array.
/// </summary>
/// <param name="val">Double array.</param>
public void WriteDoubleArray(double[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDouble);
BinaryUtils.WriteDoubleArray(val, _stream);
}
}
/// <summary>
/// Write named decimal value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal value.</param>
public void WriteDecimal(string fieldName, decimal? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDecimal);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeDecimal);
BinaryUtils.WriteDecimal(val.Value, _stream);
}
}
/// <summary>
/// Write decimal value.
/// </summary>
/// <param name="val">Decimal value.</param>
public void WriteDecimal(decimal? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeDecimal);
BinaryUtils.WriteDecimal(val.Value, _stream);
}
}
/// <summary>
/// Write named decimal array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal array.</param>
public void WriteDecimalArray(string fieldName, decimal?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayDecimal);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDecimal);
BinaryUtils.WriteDecimalArray(val, _stream);
}
}
/// <summary>
/// Write decimal array.
/// </summary>
/// <param name="val">Decimal array.</param>
public void WriteDecimalArray(decimal?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayDecimal);
BinaryUtils.WriteDecimalArray(val, _stream);
}
}
/// <summary>
/// Write named date value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date value.</param>
public void WriteTimestamp(string fieldName, DateTime? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeTimestamp);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeTimestamp);
BinaryUtils.WriteTimestamp(val.Value, _stream);
}
}
/// <summary>
/// Write date value.
/// </summary>
/// <param name="val">Date value.</param>
public void WriteTimestamp(DateTime? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeTimestamp);
BinaryUtils.WriteTimestamp(val.Value, _stream);
}
}
/// <summary>
/// Write named date array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date array.</param>
public void WriteTimestampArray(string fieldName, DateTime?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeTimestamp);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayTimestamp);
BinaryUtils.WriteTimestampArray(val, _stream);
}
}
/// <summary>
/// Write date array.
/// </summary>
/// <param name="val">Date array.</param>
public void WriteTimestampArray(DateTime?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayTimestamp);
BinaryUtils.WriteTimestampArray(val, _stream);
}
}
/// <summary>
/// Write named string value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String value.</param>
public void WriteString(string fieldName, string val)
{
WriteFieldId(fieldName, BinaryUtils.TypeString);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeString);
BinaryUtils.WriteString(val, _stream);
}
}
/// <summary>
/// Write string value.
/// </summary>
/// <param name="val">String value.</param>
public void WriteString(string val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeString);
BinaryUtils.WriteString(val, _stream);
}
}
/// <summary>
/// Write named string array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String array.</param>
public void WriteStringArray(string fieldName, string[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayString);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayString);
BinaryUtils.WriteStringArray(val, _stream);
}
}
/// <summary>
/// Write string array.
/// </summary>
/// <param name="val">String array.</param>
public void WriteStringArray(string[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayString);
BinaryUtils.WriteStringArray(val, _stream);
}
}
/// <summary>
/// Write named GUID value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID value.</param>
public void WriteGuid(string fieldName, Guid? val)
{
WriteFieldId(fieldName, BinaryUtils.TypeGuid);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeGuid);
BinaryUtils.WriteGuid(val.Value, _stream);
}
}
/// <summary>
/// Write GUID value.
/// </summary>
/// <param name="val">GUID value.</param>
public void WriteGuid(Guid? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeGuid);
BinaryUtils.WriteGuid(val.Value, _stream);
}
}
/// <summary>
/// Write named GUID array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID array.</param>
public void WriteGuidArray(string fieldName, Guid?[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayGuid);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayGuid);
BinaryUtils.WriteGuidArray(val, _stream);
}
}
/// <summary>
/// Write GUID array.
/// </summary>
/// <param name="val">GUID array.</param>
public void WriteGuidArray(Guid?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayGuid);
BinaryUtils.WriteGuidArray(val, _stream);
}
}
/// <summary>
/// Write named enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum value.</param>
public void WriteEnum<T>(string fieldName, T val)
{
WriteFieldId(fieldName, BinaryUtils.TypeEnum);
WriteEnum(val);
}
/// <summary>
/// Write enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Enum value.</param>
public void WriteEnum<T>(T val)
{
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (val == null)
WriteNullField();
else
{
// Unwrap nullable.
var valType = val.GetType();
var type = Nullable.GetUnderlyingType(valType) ?? valType;
if (!type.IsEnum)
{
throw new BinaryObjectException("Type is not an enum: " + type);
}
var handler = BinarySystemHandlers.GetWriteHandler(type);
if (handler != null)
{
// All enums except long/ulong.
handler.Write(this, val);
}
else
{
throw new BinaryObjectException(string.Format("Enum '{0}' has unsupported underlying type '{1}'. " +
"Use WriteObject instead of WriteEnum.",
type, Enum.GetUnderlyingType(type)));
}
}
}
/// <summary>
/// Write enum value.
/// </summary>
/// <param name="val">Enum value.</param>
/// <param name="type">Enum type.</param>
internal void WriteEnum(int val, Type type)
{
var desc = _marsh.GetDescriptor(type);
_stream.WriteByte(BinaryUtils.TypeEnum);
_stream.WriteInt(desc.TypeId);
_stream.WriteInt(val);
var metaHnd = _marsh.GetBinaryTypeHandler(desc);
SaveMetadata(desc, metaHnd.OnObjectWriteFinished());
}
/// <summary>
/// Write named enum array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum array.</param>
public void WriteEnumArray<T>(string fieldName, T[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArrayEnum);
WriteEnumArray(val);
}
/// <summary>
/// Write enum array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Enum array.</param>
public void WriteEnumArray<T>(T[] val)
{
WriteEnumArrayInternal(val, null);
}
/// <summary>
/// Writes the enum array.
/// </summary>
/// <param name="val">The value.</param>
/// <param name="elementTypeId">The element type id.</param>
public void WriteEnumArrayInternal(Array val, int? elementTypeId)
{
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryUtils.TypeArrayEnum);
BinaryUtils.WriteArray(val, this, elementTypeId);
}
}
/// <summary>
/// Write named object value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object value.</param>
public void WriteObject<T>(string fieldName, T val)
{
WriteFieldId(fieldName, BinaryUtils.TypeObject);
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (val == null)
WriteNullField();
else
Write(val);
}
/// <summary>
/// Write object value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Object value.</param>
public void WriteObject<T>(T val)
{
Write(val);
}
/// <summary>
/// Write named object array.
/// </summary>
/// <typeparam name="T">Element type.</typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object array.</param>
public void WriteArray<T>(string fieldName, T[] val)
{
WriteFieldId(fieldName, BinaryUtils.TypeArray);
WriteArray(val);
}
/// <summary>
/// Write object array.
/// </summary>
/// <typeparam name="T">Element type.</typeparam>
/// <param name="val">Object array.</param>
public void WriteArray<T>(T[] val)
{
WriteArrayInternal(val);
}
/// <summary>
/// Write object array.
/// </summary>
/// <param name="val">Object array.</param>
public void WriteArrayInternal(Array val)
{
if (val == null)
WriteNullRawField();
else
{
if (WriteHandle(_stream.Position, val))
return;
_stream.WriteByte(BinaryUtils.TypeArray);
BinaryUtils.WriteArray(val, this);
}
}
/// <summary>
/// Write named collection.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Collection.</param>
public void WriteCollection(string fieldName, ICollection val)
{
WriteFieldId(fieldName, BinaryUtils.TypeCollection);
WriteCollection(val);
}
/// <summary>
/// Write collection.
/// </summary>
/// <param name="val">Collection.</param>
public void WriteCollection(ICollection val)
{
if (val == null)
WriteNullField();
else
{
if (WriteHandle(_stream.Position, val))
return;
WriteByte(BinaryUtils.TypeCollection);
BinaryUtils.WriteCollection(val, this);
}
}
/// <summary>
/// Write named dictionary.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Dictionary.</param>
public void WriteDictionary(string fieldName, IDictionary val)
{
WriteFieldId(fieldName, BinaryUtils.TypeDictionary);
WriteDictionary(val);
}
/// <summary>
/// Write dictionary.
/// </summary>
/// <param name="val">Dictionary.</param>
public void WriteDictionary(IDictionary val)
{
if (val == null)
WriteNullField();
else
{
if (WriteHandle(_stream.Position, val))
return;
WriteByte(BinaryUtils.TypeDictionary);
BinaryUtils.WriteDictionary(val, this);
}
}
/// <summary>
/// Write NULL field.
/// </summary>
private void WriteNullField()
{
_stream.WriteByte(BinaryUtils.HdrNull);
}
/// <summary>
/// Write NULL raw field.
/// </summary>
private void WriteNullRawField()
{
_stream.WriteByte(BinaryUtils.HdrNull);
}
/// <summary>
/// Get raw writer.
/// </summary>
/// <returns>
/// Raw writer.
/// </returns>
public IBinaryRawWriter GetRawWriter()
{
if (_frame.RawPos == 0)
_frame.RawPos = _stream.Position;
return this;
}
/// <summary>
/// Set new builder.
/// </summary>
/// <param name="builder">Builder.</param>
/// <returns>Previous builder.</returns>
internal BinaryObjectBuilder SetBuilder(BinaryObjectBuilder builder)
{
BinaryObjectBuilder ret = _builder;
_builder = builder;
return ret;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="marsh">Marshaller.</param>
/// <param name="stream">Stream.</param>
internal BinaryWriter(Marshaller marsh, IBinaryStream stream)
{
_marsh = marsh;
_stream = stream;
}
/// <summary>
/// Write object.
/// </summary>
/// <param name="obj">Object.</param>
public void Write<T>(T obj)
{
// Handle special case for null.
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (obj == null)
{
_stream.WriteByte(BinaryUtils.HdrNull);
return;
}
// We use GetType() of a real object instead of typeof(T) to take advantage of
// automatic Nullable'1 unwrapping.
Type type = obj.GetType();
// Handle common case when primitive is written.
if (type.IsPrimitive)
{
WritePrimitive(obj, type);
return;
}
// Handle special case for builder.
if (WriteBuilderSpecials(obj))
return;
// Are we dealing with a well-known type?
var handler = BinarySystemHandlers.GetWriteHandler(type);
if (handler != null)
{
if (handler.SupportsHandles && WriteHandle(_stream.Position, obj))
return;
handler.Write(this, obj);
return;
}
// Wrap objects as required.
if (WrapperFunc != null && type != WrapperFunc.Method.ReturnType)
{
if (_isInWrapper)
{
_isInWrapper = false;
}
else
{
_isInWrapper = true;
Write(WrapperFunc(obj));
return;
}
}
// Suppose that we faced normal object and perform descriptor lookup.
var desc = _marsh.GetDescriptor(type);
// Writing normal object.
var pos = _stream.Position;
// Dealing with handles.
if (desc.Serializer.SupportsHandles && WriteHandle(pos, obj))
return;
// Skip header length as not everything is known now
_stream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current);
// Write type name for unregistered types
if (!desc.IsRegistered)
WriteString(type.AssemblyQualifiedName);
var headerSize = _stream.Position - pos;
// Preserve old frame.
var oldFrame = _frame;
// Push new frame.
_frame.RawPos = 0;
_frame.Pos = pos;
_frame.Struct = new BinaryStructureTracker(desc, desc.WriterTypeStructure);
_frame.HasCustomTypeData = false;
var schemaIdx = _schema.PushSchema();
try
{
// Write object fields.
desc.Serializer.WriteBinary(obj, this);
var dataEnd = _stream.Position;
// Write schema
var schemaOffset = dataEnd - pos;
int schemaId;
var flags = desc.UserType
? BinaryObjectHeader.Flag.UserType
: BinaryObjectHeader.Flag.None;
if (_frame.HasCustomTypeData)
flags |= BinaryObjectHeader.Flag.CustomDotNetType;
if (Marshaller.CompactFooter && desc.UserType)
flags |= BinaryObjectHeader.Flag.CompactFooter;
var hasSchema = _schema.WriteSchema(_stream, schemaIdx, out schemaId, ref flags);
if (hasSchema)
{
flags |= BinaryObjectHeader.Flag.HasSchema;
// Calculate and write header.
if (_frame.RawPos > 0)
_stream.WriteInt(_frame.RawPos - pos); // raw offset is in the last 4 bytes
// Update schema in type descriptor
if (desc.Schema.Get(schemaId) == null)
desc.Schema.Add(schemaId, _schema.GetSchema(schemaIdx));
}
else
schemaOffset = headerSize;
if (_frame.RawPos > 0)
flags |= BinaryObjectHeader.Flag.HasRaw;
var len = _stream.Position - pos;
var hashCode = BinaryArrayEqualityComparer.GetHashCode(Stream, pos + BinaryObjectHeader.Size,
dataEnd - pos - BinaryObjectHeader.Size);
var header = new BinaryObjectHeader(desc.IsRegistered ? desc.TypeId : BinaryUtils.TypeUnregistered,
hashCode, len, schemaId, schemaOffset, flags);
BinaryObjectHeader.Write(header, _stream, pos);
Stream.Seek(pos + len, SeekOrigin.Begin); // Seek to the end
}
finally
{
_schema.PopSchema(schemaIdx);
}
// Apply structure updates if any.
_frame.Struct.UpdateWriterStructure(this);
// Restore old frame.
_frame = oldFrame;
}
/// <summary>
/// Marks current object with a custom type data flag.
/// </summary>
public void SetCustomTypeDataFlag(bool hasCustomTypeData)
{
_frame.HasCustomTypeData = hasCustomTypeData;
}
/// <summary>
/// Write primitive type.
/// </summary>
/// <param name="val">Object.</param>
/// <param name="type">Type.</param>
private unsafe void WritePrimitive<T>(T val, Type type)
{
// .Net defines 14 primitive types. We support 12 - excluding IntPtr and UIntPtr.
// Types check sequence is designed to minimize comparisons for the most frequent types.
if (type == typeof(int))
WriteIntField(TypeCaster<int>.Cast(val));
else if (type == typeof(long))
WriteLongField(TypeCaster<long>.Cast(val));
else if (type == typeof(bool))
WriteBooleanField(TypeCaster<bool>.Cast(val));
else if (type == typeof(byte))
WriteByteField(TypeCaster<byte>.Cast(val));
else if (type == typeof(short))
WriteShortField(TypeCaster<short>.Cast(val));
else if (type == typeof(char))
WriteCharField(TypeCaster<char>.Cast(val));
else if (type == typeof(float))
WriteFloatField(TypeCaster<float>.Cast(val));
else if (type == typeof(double))
WriteDoubleField(TypeCaster<double>.Cast(val));
else if (type == typeof(sbyte))
{
var val0 = TypeCaster<sbyte>.Cast(val);
WriteByteField(*(byte*)&val0);
}
else if (type == typeof(ushort))
{
var val0 = TypeCaster<ushort>.Cast(val);
WriteShortField(*(short*) &val0);
}
else if (type == typeof(uint))
{
var val0 = TypeCaster<uint>.Cast(val);
WriteIntField(*(int*)&val0);
}
else if (type == typeof(ulong))
{
var val0 = TypeCaster<ulong>.Cast(val);
WriteLongField(*(long*)&val0);
}
else
throw BinaryUtils.GetUnsupportedTypeException(type, val);
}
/// <summary>
/// Try writing object as special builder type.
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>True if object was written, false otherwise.</returns>
private bool WriteBuilderSpecials<T>(T obj)
{
if (_builder != null)
{
// Special case for binary object during build.
BinaryObject portObj = obj as BinaryObject;
if (portObj != null)
{
if (!WriteHandle(_stream.Position, portObj))
_builder.ProcessBinary(_stream, portObj);
return true;
}
// Special case for builder during build.
BinaryObjectBuilder portBuilder = obj as BinaryObjectBuilder;
if (portBuilder != null)
{
if (!WriteHandle(_stream.Position, portBuilder))
_builder.ProcessBuilder(_stream, portBuilder);
return true;
}
}
return false;
}
/// <summary>
/// Add handle to handles map.
/// </summary>
/// <param name="pos">Position in stream.</param>
/// <param name="obj">Object.</param>
/// <returns><c>true</c> if object was written as handle.</returns>
private bool WriteHandle(long pos, object obj)
{
if (_hnds == null)
{
// Cache absolute handle position.
_hnds = new BinaryHandleDictionary<object, long>(obj, pos, ReferenceEqualityComparer<object>.Instance);
return false;
}
long hndPos;
if (!_hnds.TryGetValue(obj, out hndPos))
{
// Cache absolute handle position.
_hnds.Add(obj, pos);
return false;
}
_stream.WriteByte(BinaryUtils.HdrHnd);
// Handle is written as difference between position before header and handle position.
_stream.WriteInt((int)(pos - hndPos));
return true;
}
/// <summary>
/// Perform action with detached semantics.
/// </summary>
/// <param name="a"></param>
internal void WithDetach(Action<BinaryWriter> a)
{
if (_detaching)
a(this);
else
{
_detaching = true;
BinaryHandleDictionary<object, long> oldHnds = _hnds;
_hnds = null;
try
{
a(this);
}
finally
{
_detaching = false;
if (oldHnds != null)
{
// Merge newly recorded handles with old ones and restore old on the stack.
// Otherwise we can use current handles right away.
if (_hnds != null)
oldHnds.Merge(_hnds);
_hnds = oldHnds;
}
}
}
}
/// <summary>
/// Gets or sets a function to wrap all serializer objects.
/// </summary>
internal Func<object, object> WrapperFunc { get; set; }
/// <summary>
/// Stream.
/// </summary>
internal IBinaryStream Stream
{
get { return _stream; }
}
/// <summary>
/// Gets collected metadatas.
/// </summary>
/// <returns>Collected metadatas (if any).</returns>
internal ICollection<BinaryType> GetBinaryTypes()
{
return _metas == null ? null : _metas.Values;
}
/// <summary>
/// Write field ID.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="fieldTypeId">Field type ID.</param>
private void WriteFieldId(string fieldName, byte fieldTypeId)
{
if (_frame.RawPos != 0)
throw new BinaryObjectException("Cannot write named fields after raw data is written.");
var fieldId = _frame.Struct.GetFieldId(fieldName, fieldTypeId);
_schema.PushField(fieldId, _stream.Position - _frame.Pos);
}
/// <summary>
/// Saves metadata for this session.
/// </summary>
/// <param name="desc">The descriptor.</param>
/// <param name="fields">Fields metadata.</param>
internal void SaveMetadata(IBinaryTypeDescriptor desc, IDictionary<string, BinaryField> fields)
{
Debug.Assert(desc != null);
if (_metas == null)
{
_metas = new Dictionary<int, BinaryType>(1)
{
{desc.TypeId, new BinaryType(desc, _marsh, fields)}
};
}
else
{
BinaryType meta;
if (_metas.TryGetValue(desc.TypeId, out meta))
meta.UpdateFields(fields);
else
_metas[desc.TypeId] = new BinaryType(desc, _marsh, fields);
}
}
/// <summary>
/// Stores current writer stack frame.
/// </summary>
private struct Frame
{
/** Current object start position. */
public int Pos;
/** Current raw position. */
public int RawPos;
/** Current type structure tracker. */
public BinaryStructureTracker Struct;
/** Custom type data. */
public bool HasCustomTypeData;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace ProductiveRage.Immutable.Analyser
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class IAmImmutableAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "IAmImmutable";
private const string Category = "Design";
public static DiagnosticDescriptor MayNotHavePublicNonReadOnlyFieldsRule = new DiagnosticDescriptor(
DiagnosticId,
GetLocalizableString(nameof(Resources.IAmImmutableAnalyserTitle)),
GetLocalizableString(nameof(Resources.IAmImmutableFieldsMayNotBePublicAndMutableMessageFormat)),
Category,
DiagnosticSeverity.Error,
isEnabledByDefault: true
);
public static DiagnosticDescriptor MustHaveSettersOnPropertiesWithGettersAccessRule = new DiagnosticDescriptor(
DiagnosticId,
GetLocalizableString(nameof(Resources.IAmImmutableAnalyserTitle)),
GetLocalizableString(nameof(Resources.IAmImmutablePropertiesMustHaveSettersMessageFormat)),
Category,
DiagnosticSeverity.Error,
isEnabledByDefault: true
);
public static DiagnosticDescriptor MayNotHaveBridgeAttributesOnPropertiesWithGettersAccessRule = new DiagnosticDescriptor(
DiagnosticId,
GetLocalizableString(nameof(Resources.IAmImmutableAnalyserTitle)),
GetLocalizableString(nameof(Resources.IAmImmutablePropertiesMustNotHaveBridgeAttributesMessageFormat)),
Category,
DiagnosticSeverity.Error,
isEnabledByDefault: true
);
public static DiagnosticDescriptor MayNotHavePublicSettersRule = new DiagnosticDescriptor(
DiagnosticId,
GetLocalizableString(nameof(Resources.IAmImmutableAnalyserTitle)),
GetLocalizableString(nameof(Resources.IAmImmutablePropertiesMayNotHavePublicSetterMessageFormat)),
Category,
DiagnosticSeverity.Error,
isEnabledByDefault: true
);
public static DiagnosticDescriptor ConstructorWithLogicOtherThanCtorSetCallsShouldUseValidateMethod = new DiagnosticDescriptor(
DiagnosticId,
GetLocalizableString(nameof(Resources.IAmImmutableAnalyserTitle)),
GetLocalizableString(nameof(Resources.IAmImmutableValidationShouldNotBePerformedInConstructorMessageFormat)),
Category,
DiagnosticSeverity.Warning,
isEnabledByDefault: true
);
public static DiagnosticDescriptor ConstructorDoesNotCallValidateMethod = new DiagnosticDescriptor(
DiagnosticId,
GetLocalizableString(nameof(Resources.IAmImmutableAnalyserTitle)),
GetLocalizableString(nameof(Resources.IAmImmutableConstructorDoesNotCallValidateMethodMessageFormat)),
Category,
DiagnosticSeverity.Warning,
isEnabledByDefault: true
);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(
MayNotHavePublicNonReadOnlyFieldsRule,
MustHaveSettersOnPropertiesWithGettersAccessRule,
MayNotHaveBridgeAttributesOnPropertiesWithGettersAccessRule,
ConstructorWithLogicOtherThanCtorSetCallsShouldUseValidateMethod,
ConstructorDoesNotCallValidateMethod
);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(LookForIllegalIAmImmutableImplementations, SyntaxKind.ClassDeclaration);
}
private void LookForIllegalIAmImmutableImplementations(SyntaxNodeAnalysisContext context)
{
var classDeclaration = context.Node as ClassDeclarationSyntax;
if (classDeclaration == null)
return;
// Only bother looking this up (which is relatively expensive) if we know that we have to
var classImplementIAmImmutable = new Lazy<bool>(() => CommonAnalyser.ImplementsIAmImmutable(context.SemanticModel.GetDeclaredSymbol(classDeclaration)));
var publicMutableFields = classDeclaration.ChildNodes()
.OfType<FieldDeclarationSyntax>()
.Where(field => field.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.PublicKeyword)))
.Where(field => !field.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.ReadOnlyKeyword)));
foreach (var publicMutableField in publicMutableFields)
{
if (classImplementIAmImmutable.Value)
{
context.ReportDiagnostic(Diagnostic.Create(
MayNotHavePublicNonReadOnlyFieldsRule,
publicMutableField.GetLocation(),
string.Join(", ", publicMutableField.Declaration.Variables.Select(variable => variable.Identifier.Text))
));
}
}
// When the "With" methods updates create new instances, the existing instance is cloned and the target property updated - the constructor is not called on the
// new instance, which means that any validation in there is bypassed. I don't think that there's sufficient information available at runtime (in JavaScript) to
// create a new instance by calling the constructor instead of using this approach so, instead, validation is not allowed in the constructor - only "CtorSet"
// calls are acceptable with an optional "Validate" call that may appear at the end of the constructor. If this "Validate" method exists then it will be called
// after each "With" call in order to allow validation to be performed after each property update. The "Validate" method must have no parameters but may have
// any accessibility (private probably makes most sense).
var constructorsThatShouldUseValidateMethodIfClassImplementsIAmImmutable = new List<ConstructorDeclarationSyntax>();
var instanceConstructors = classDeclaration.ChildNodes()
.OfType<ConstructorDeclarationSyntax>()
.Where(constructor => (constructor.Body != null)) // If the code is in an invalid state then the Body property might be null - safe to ignore
.Where(constructor => !constructor.Modifiers.Any(modifier => modifier.Kind() == SyntaxKind.StaticKeyword));
foreach (var instanceConstructor in instanceConstructors)
{
var constructorShouldUseValidateMethodIfClassImplementsIAmImmutable = false;
var constructorChildNodes = instanceConstructor.Body.ChildNodes().ToArray();
foreach (var node in constructorChildNodes.Select((childNode, i) => new { Node = childNode, IsLastNode = i == (constructorChildNodes.Length - 1) }))
{
var expressionStatement = node.Node as ExpressionStatementSyntax;
if (expressionStatement == null)
{
constructorShouldUseValidateMethodIfClassImplementsIAmImmutable = true;
break;
}
var invocation = expressionStatement.Expression as InvocationExpressionSyntax;
if (invocation != null)
{
if (InvocationIsCtorSetCall(invocation, context) || (node.IsLastNode && InvocationIsAllowableValidateCall(invocation, context)))
continue;
}
constructorShouldUseValidateMethodIfClassImplementsIAmImmutable = true;
}
if (constructorShouldUseValidateMethodIfClassImplementsIAmImmutable)
constructorsThatShouldUseValidateMethodIfClassImplementsIAmImmutable.Add(instanceConstructor);
}
if (constructorsThatShouldUseValidateMethodIfClassImplementsIAmImmutable.Any())
{
if (classImplementIAmImmutable.Value)
{
foreach (var constructorThatShouldUseValidateMethod in constructorsThatShouldUseValidateMethodIfClassImplementsIAmImmutable)
{
context.ReportDiagnostic(Diagnostic.Create(
ConstructorWithLogicOtherThanCtorSetCallsShouldUseValidateMethod,
constructorThatShouldUseValidateMethod.GetLocation()
));
}
}
}
// If there is a Validate method that should be called and this constructor isn't calling it then warn
if (HasValidateMethodThatThisClassMustCall(classDeclaration))
{
var constructorsThatNeedToWarnAreNotCallingValidate = instanceConstructors
.Except(constructorsThatShouldUseValidateMethodIfClassImplementsIAmImmutable) // Don't warn about any constructors that are already being identified as needing attention
.Where(instanceConstructor =>
// If this constructors calls another of the constructor overloads then don't warn (only warn about constructors that DON'T call another overload)
(instanceConstructor.Initializer == null) || (instanceConstructor.Initializer.Kind() != SyntaxKind.ThisConstructorInitializer)
)
.Where(instanceConstructor =>
!instanceConstructor.Body.ChildNodes()
.OfType<ExpressionStatementSyntax>()
.Select(expressionStatement => expressionStatement.Expression as InvocationExpressionSyntax)
.Where(invocation => (invocation != null) && InvocationIsAllowableValidateCall(invocation, context))
.Any()
);
if (constructorsThatNeedToWarnAreNotCallingValidate.Any() && classImplementIAmImmutable.Value)
{
foreach (var constructorThatShouldUseValidateMethod in constructorsThatNeedToWarnAreNotCallingValidate)
{
context.ReportDiagnostic(Diagnostic.Create(
ConstructorDoesNotCallValidateMethod,
constructorThatShouldUseValidateMethod.GetLocation(),
classDeclaration.Identifier.Text
));
}
}
}
// This is likely to be the most expensive work (since it requires lookup of other symbols elsewhere in the solution, whereas the
// logic below only look at code in the current file) so only perform it when required (leave it as null until we absolutely need
// to know whether the current class implements IAmImmutable or not)
foreach (var property in classDeclaration.ChildNodes().OfType<PropertyDeclarationSyntax>())
{
if (property.ExplicitInterfaceSpecifier != null)
{
// Since CtorSet and With can not target properties that are not directly accessible through a reference to the
// IAmImmutable-implementing type (because "_ => _.Name" is acceptable as a property retriever but not something
// like "_ => ((IWhatever)_).Name") if a property is explicitly implemented for a base interface then the rules
// below need not be applied to it.
continue;
}
// If property.ExpressionBody is an ArrowExpressionClauseSyntax then it's C# 6 syntax for a read-only property that returns
// a value (which is different to a readonly auto-property, which introduces a backing field behind the scenes, this syntax
// doesn't introduce a new backing field, it returns an expression). In this case, there won't be an AccessorList (it will
// be null).
Diagnostic errorIfAny;
if (property.ExpressionBody is ArrowExpressionClauseSyntax)
{
errorIfAny = Diagnostic.Create(
MustHaveSettersOnPropertiesWithGettersAccessRule,
property.GetLocation(),
property.Identifier.Text
);
}
else
{
var getterIfDefined = property.AccessorList.Accessors.FirstOrDefault(a => a.Kind() == SyntaxKind.GetAccessorDeclaration);
var setterIfDefined = property.AccessorList.Accessors.FirstOrDefault(a => a.Kind() == SyntaxKind.SetAccessorDeclaration);
if ((getterIfDefined != null) && (setterIfDefined == null))
{
// If getterIfDefined is non-null but has a null Body then it's an auto-property getter, in which case not having
// a setter is allowed since it means that it's a read-only auto-property (for which Bridge will create a property
// setter for in the JavaScript)
if (getterIfDefined.Body != null)
{
errorIfAny = Diagnostic.Create(
MustHaveSettersOnPropertiesWithGettersAccessRule,
property.GetLocation(),
property.Identifier.Text
);
}
else
continue;
}
else if ((getterIfDefined != null) && CommonAnalyser.HasDisallowedAttribute(Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetDeclaredSymbol(context.SemanticModel, getterIfDefined)))
{
errorIfAny = Diagnostic.Create(
MayNotHaveBridgeAttributesOnPropertiesWithGettersAccessRule,
getterIfDefined.GetLocation(),
property.Identifier.Text
);
}
else if ((setterIfDefined != null) && CommonAnalyser.HasDisallowedAttribute(Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetDeclaredSymbol(context.SemanticModel, setterIfDefined)))
{
errorIfAny = Diagnostic.Create(
MayNotHaveBridgeAttributesOnPropertiesWithGettersAccessRule,
setterIfDefined.GetLocation(),
property.Identifier.Text
);
}
else if ((setterIfDefined != null) && IsPublic(property) && !IsPrivateOrProtected(setterIfDefined))
{
errorIfAny = Diagnostic.Create(
MayNotHavePublicSettersRule,
setterIfDefined.GetLocation(),
property.Identifier.Text
);
}
else
continue;
}
// Enountered a potential error if the current class implements IAmImmutable - so find out whether it does or not (if it
// doesn't then no further work is required and we can exit the entire process early)
if (!classImplementIAmImmutable.Value)
return;
context.ReportDiagnostic(errorIfAny);
}
}
private static bool IsPublic(PropertyDeclarationSyntax property)
{
if (property == null)
throw new ArgumentNullException(nameof(property));
return property.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.PublicKeyword));
}
private static bool IsPrivateOrProtected(AccessorDeclarationSyntax propertyAccessor)
{
if (propertyAccessor == null)
throw new ArgumentNullException(nameof(propertyAccessor));
return
propertyAccessor.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.PrivateKeyword)) ||
propertyAccessor.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.ProtectedKeyword));
}
private static bool InvocationIsCtorSetCall(InvocationExpressionSyntax invocation, SyntaxNodeAnalysisContext context)
{
if (invocation == null)
throw new ArgumentNullException(nameof(invocation));
var lastExpressionToken = invocation.Expression.GetLastToken();
if ((lastExpressionToken == null) || (lastExpressionToken.Text != "CtorSet"))
return false;
// Note: Don't need to do any work to ensure that this is a VALID "CtorSet" call since the CtorSetCallAnalyzer will do that
var ctorSetMethod = context.SemanticModel.GetSymbolInfo(invocation.Expression).Symbol as IMethodSymbol;
return
(ctorSetMethod != null) &&
(ctorSetMethod.ContainingAssembly != null) &&
(ctorSetMethod.ContainingAssembly.Name == CommonAnalyser.AnalyserAssemblyName);
}
private static bool HasValidateMethodThatThisClassMustCall(ClassDeclarationSyntax classDeclaration)
{
if (classDeclaration == null)
throw new ArgumentNullException(nameof(classDeclaration));
return TryToGetValidateMethodThatThisClassMustCall(classDeclaration) != null;
}
public static MethodDeclarationSyntax TryToGetValidateMethodThatThisClassMustCall(ClassDeclarationSyntax classDeclaration)
{
if (classDeclaration == null)
throw new ArgumentNullException(nameof(classDeclaration));
// 2018-04-08 DWR: This only checks for a Validate method declared on the current class - if there is one on a type that it is derived from then the responsibility is on that base
// type to call it (if that base type doesn't also implement IAmImmutable then this analyser won't be run on it and so it's still possible that the Validate method won't be called
// from the base type's constructor but we can't know for sure one way or the other if that other class is defined in an assembly that we don't have access to the source of and so
// we can't be 100% sure one way or the other, so let's keep it simple)
return classDeclaration.ChildNodes()
.OfType<MethodDeclarationSyntax>()
.FirstOrDefault(method =>
(method.Identifier.Text == "Validate") &&
!method.ParameterList.Parameters.Any() &&
ReturnsVoid(method) &&
(method.Arity == 0) &&
!method.Modifiers.Any(modifier => modifier.Kind() == SyntaxKind.StaticKeyword)
);
}
private static bool ReturnsVoid(MethodDeclarationSyntax method)
{
if (method == null)
throw new ArgumentNullException(nameof(method));
var predefinedReturnType = method.ReturnType as PredefinedTypeSyntax;
if (predefinedReturnType == null)
return false;
return predefinedReturnType.Keyword.Kind() == SyntaxKind.VoidKeyword;
}
private static bool InvocationIsAllowableValidateCall(InvocationExpressionSyntax invocation, SyntaxNodeAnalysisContext context)
{
if (invocation == null)
throw new ArgumentNullException(nameof(invocation));
var lastExpressionToken = invocation.Expression.GetLastToken();
if ((lastExpressionToken == null) || (lastExpressionToken.Text != "Validate"))
return false;
var validateMethod = context.SemanticModel.GetSymbolInfo(invocation.Expression).Symbol as IMethodSymbol;
return
(validateMethod != null) &&
!validateMethod.Parameters.Any() &&
(validateMethod.Arity == 0) &&
validateMethod.ReturnsVoid &&
!CommonAnalyser.HasDisallowedAttribute(validateMethod);
}
private static LocalizableString GetLocalizableString(string nameOfLocalizableResource)
{
return new LocalizableResourceString(nameOfLocalizableResource, Resources.ResourceManager, typeof(Resources));
}
}
}
| |
//
// AudioscrobblerConnection.cs
//
// Author:
// Chris Toshok <toshok@ximian.com>
// Alexander Hixon <hixon.alexander@mediati.org>
//
// Copyright (C) 2005-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Timers;
using System.Security.Cryptography;
using System.Web;
using Hyena;
using Mono.Unix;
namespace Lastfm
{
public class AudioscrobblerConnection
{
private enum State {
Idle,
NeedHandshake,
NeedTransmit,
WaitingForRequestStream,
WaitingForHandshakeResp,
WaitingForResponse
};
private const int TICK_INTERVAL = 2000; /* 2 seconds */
private const int FAILURE_LOG_MINUTES = 5; /* 5 minute delay on logging failure to upload information */
private const int RETRY_SECONDS = 60; /* 60 second delay for transmission retries */
private const int MAX_RETRY_SECONDS = 7200; /* 2 hours, as defined in the last.fm protocol */
private const int TIME_OUT = 5000; /* 5 seconds timeout for webrequests */
private const string CLIENT_ID = "bsh";
private const string CLIENT_VERSION = "0.1";
private const string SCROBBLER_URL = "http://post.audioscrobbler.com/";
private const string SCROBBLER_VERSION = "1.2.1";
private string post_url;
private string session_id = null;
private string now_playing_url;
private bool connected = false; /* if we're connected to network or not */
public bool Connected {
get { return connected; }
}
private bool started = false; /* engine has started and was/is connected to AS */
public bool Started {
get { return started; }
}
private System.Timers.Timer timer;
private DateTime next_interval;
private DateTime last_upload_failed_logged;
private IQueue queue;
private int hard_failures = 0;
private int hard_failure_retry_sec = 60;
private HttpWebRequest now_playing_post;
private bool now_playing_started;
private string current_now_playing_data;
private HttpWebRequest current_web_req;
private IAsyncResult current_async_result;
private State state;
internal AudioscrobblerConnection (IQueue queue)
{
LastfmCore.Account.Updated += AccountUpdated;
state = State.Idle;
this.queue = queue;
}
private void AccountUpdated (object o, EventArgs args)
{
Stop ();
session_id = null;
Start ();
}
public void UpdateNetworkState (bool connected)
{
Log.DebugFormat ("Audioscrobbler state: {0}", connected ? "connected" : "disconnected");
this.connected = connected;
}
public void Start ()
{
if (started) {
return;
}
started = true;
hard_failures = 0;
queue.TrackAdded += delegate(object o, EventArgs args) {
StartTransitionHandler ();
};
queue.Load ();
StartTransitionHandler ();
}
private void StartTransitionHandler ()
{
if (!started) {
// Don't run if we're not actually started.
return;
}
if (timer == null) {
timer = new System.Timers.Timer ();
timer.Interval = TICK_INTERVAL;
timer.AutoReset = true;
timer.Elapsed += new ElapsedEventHandler (StateTransitionHandler);
timer.Start ();
} else if (!timer.Enabled) {
timer.Start ();
}
}
public void Stop ()
{
StopTransitionHandler ();
if (current_web_req != null) {
current_web_req.Abort ();
}
queue.Save ();
started = false;
}
private void StopTransitionHandler ()
{
if (timer != null) {
timer.Stop ();
}
}
private void StateTransitionHandler (object o, ElapsedEventArgs e)
{
// if we're not connected, don't bother doing anything involving the network.
if (!connected) {
return;
}
if ((state == State.Idle || state == State.NeedTransmit) && hard_failures > 2) {
state = State.NeedHandshake;
hard_failures = 0;
}
// and address changes in our engine state
switch (state) {
case State.Idle:
if (LastfmCore.Account.UserName != null &&
LastfmCore.Account.SessionKey != null && session_id == null) {
state = State.NeedHandshake;
} else {
if (queue.Count > 0 && session_id != null) {
state = State.NeedTransmit;
} else if (current_now_playing_data != null && session_id != null) {
// Now playing info needs to be sent
NowPlaying (current_now_playing_data);
} else {
StopTransitionHandler ();
}
}
break;
case State.NeedHandshake:
if (DateTime.Now > next_interval) {
Handshake ();
}
break;
case State.NeedTransmit:
if (DateTime.Now > next_interval) {
TransmitQueue ();
}
break;
case State.WaitingForResponse:
case State.WaitingForRequestStream:
case State.WaitingForHandshakeResp:
// nothing here
break;
}
}
//
// Async code for transmitting the current queue of tracks
//
internal class TransmitState
{
public StringBuilder StringBuilder;
public int Count;
}
private void TransmitQueue ()
{
int num_tracks_transmitted;
// save here in case we're interrupted before we complete
// the request. we save it again when we get an OK back
// from the server
queue.Save ();
next_interval = DateTime.MinValue;
if (post_url == null || !connected) {
return;
}
StringBuilder sb = new StringBuilder ();
sb.AppendFormat ("s={0}", session_id);
sb.Append (queue.GetTransmitInfo (out num_tracks_transmitted));
current_web_req = (HttpWebRequest) WebRequest.Create (post_url);
current_web_req.UserAgent = LastfmCore.UserAgent;
current_web_req.Method = "POST";
current_web_req.ContentType = "application/x-www-form-urlencoded";
current_web_req.ContentLength = sb.Length;
//Console.WriteLine ("Sending {0} ({1} bytes) to {2}", sb.ToString (), sb.Length, post_url);
TransmitState ts = new TransmitState ();
ts.Count = num_tracks_transmitted;
ts.StringBuilder = sb;
state = State.WaitingForRequestStream;
current_async_result = current_web_req.BeginGetRequestStream (TransmitGetRequestStream, ts);
if (!(current_async_result.AsyncWaitHandle.WaitOne (TIME_OUT, false))) {
Log.Warning ("Audioscrobbler upload failed", "The request timed out and was aborted", false);
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
hard_failures++;
state = State.Idle;
current_web_req.Abort();
}
}
private void TransmitGetRequestStream (IAsyncResult ar)
{
Stream stream;
try {
stream = current_web_req.EndGetRequestStream (ar);
} catch (Exception e) {
Log.Exception ("Failed to get the request stream", e);
state = State.Idle;
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
return;
}
TransmitState ts = (TransmitState) ar.AsyncState;
StringBuilder sb = ts.StringBuilder;
StreamWriter writer = new StreamWriter (stream);
writer.Write (sb.ToString ());
writer.Close ();
state = State.WaitingForResponse;
current_async_result = current_web_req.BeginGetResponse (TransmitGetResponse, ts);
if (current_async_result == null) {
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
hard_failures++;
state = State.Idle;
}
}
private void TransmitGetResponse (IAsyncResult ar)
{
WebResponse resp;
try {
resp = current_web_req.EndGetResponse (ar);
}
catch (Exception e) {
Log.Warning (String.Format("Failed to get the response: {0}", e), false);
state = State.Idle;
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
return;
}
TransmitState ts = (TransmitState) ar.AsyncState;
Stream s = resp.GetResponseStream ();
StreamReader sr = new StreamReader (s, Encoding.UTF8);
string line;
line = sr.ReadLine ();
DateTime now = DateTime.Now;
if (line.StartsWith ("FAILED")) {
if (now - last_upload_failed_logged > TimeSpan.FromMinutes(FAILURE_LOG_MINUTES)) {
Log.Warning ("Audioscrobbler upload failed", line.Substring ("FAILED".Length).Trim(), false);
last_upload_failed_logged = now;
}
// retransmit the queue on the next interval
hard_failures++;
state = State.NeedTransmit;
}
else if (line.StartsWith ("BADSESSION")) {
if (now - last_upload_failed_logged > TimeSpan.FromMinutes(FAILURE_LOG_MINUTES)) {
Log.Warning ("Audioscrobbler upload failed", "session ID sent was invalid", false);
last_upload_failed_logged = now;
}
// attempt to re-handshake (and retransmit) on the next interval
session_id = null;
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
state = State.NeedHandshake;
return;
} else if (line.StartsWith ("OK")) {
/* if we've previously logged failures, be nice and log the successful upload. */
if (last_upload_failed_logged != DateTime.MinValue) {
Log.Debug ("Audioscrobbler upload succeeded");
last_upload_failed_logged = DateTime.MinValue;
}
hard_failures = 0;
// we succeeded, pop the elements off our queue
queue.RemoveRange (0, ts.Count);
queue.Save ();
state = State.Idle;
} else {
if (now - last_upload_failed_logged > TimeSpan.FromMinutes(FAILURE_LOG_MINUTES)) {
Log.Warning ("Audioscrobbler upload failed", String.Format ("Unrecognized response: {0}", line), false);
last_upload_failed_logged = now;
}
state = State.Idle;
}
}
//
// Async code for handshaking
//
private string UnixTime ()
{
return ((int) (DateTime.UtcNow - new DateTime (1970, 1, 1)).TotalSeconds).ToString ();
}
private void Handshake ()
{
string timestamp = UnixTime();
string authentication_token = Hyena.CryptoUtil.Md5Encode
(LastfmCore.ApiSecret + timestamp);
string api_url = LastfmCore.Account.ScrobbleUrl;
if (String.IsNullOrEmpty (api_url)) {
api_url = SCROBBLER_URL;
} else {
Log.DebugFormat ("Scrobbling to non-standard API URL: {0}", api_url);
}
string uri = String.Format ("{0}?hs=true&p={1}&c={2}&v={3}&u={4}&t={5}&a={6}&api_key={7}&sk={8}",
api_url,
SCROBBLER_VERSION,
CLIENT_ID, CLIENT_VERSION,
HttpUtility.UrlEncode (LastfmCore.Account.UserName),
timestamp,
authentication_token,
LastfmCore.ApiKey,
LastfmCore.Account.SessionKey);
current_web_req = (HttpWebRequest) WebRequest.Create (uri);
state = State.WaitingForHandshakeResp;
current_async_result = current_web_req.BeginGetResponse (HandshakeGetResponse, null);
if (current_async_result == null) {
next_interval = DateTime.Now + new TimeSpan (0, 0, hard_failure_retry_sec);
hard_failures++;
if (hard_failure_retry_sec < MAX_RETRY_SECONDS)
hard_failure_retry_sec *= 2;
state = State.NeedHandshake;
}
}
private void HandshakeGetResponse (IAsyncResult ar)
{
bool success = false;
bool hard_failure = false;
WebResponse resp;
try {
resp = current_web_req.EndGetResponse (ar);
}
catch (Exception e) {
Log.Warning ("Failed to handshake", e.ToString (), false);
// back off for a time before trying again
state = State.Idle;
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
return;
}
Stream s = resp.GetResponseStream ();
StreamReader sr = new StreamReader (s, Encoding.UTF8);
string line;
line = sr.ReadLine ();
if (line.StartsWith ("BANNED")) {
Log.Warning ("Audioscrobbler sign-on failed", "Player is banned", false);
} else if (line.StartsWith ("BADAUTH")) {
Log.Warning ("Audioscrobbler sign-on failed", Catalog.GetString ("Last.fm username is invalid or Banshee is not authorized to access your account."));
LastfmCore.Account.SessionKey = null;
} else if (line.StartsWith ("BADTIME")) {
Log.Warning ("Audioscrobbler sign-on failed",
"timestamp provided was not close enough to the current time", false);
} else if (line.StartsWith ("FAILED")) {
Log.Warning ("Audioscrobbler sign-on failed",
String.Format ("Temporary server failure: {0}", line.Substring ("FAILED".Length).Trim ()), false);
hard_failure = true;
} else if (line.StartsWith ("OK")) {
success = true;
} else {
Log.Error ("Audioscrobbler sign-on failed", String.Format ("Unknown error: {0}", line.Trim()));
hard_failure = true;
}
if (success == true) {
Log.Debug ("Audioscrobbler sign-on succeeded", "Session ID received");
session_id = sr.ReadLine ().Trim ();
now_playing_url = sr.ReadLine ().Trim ();
post_url = sr.ReadLine ().Trim ();
hard_failures = 0;
hard_failure_retry_sec = 60;
} else {
if (hard_failure == true) {
next_interval = DateTime.Now + new TimeSpan (0, 0, hard_failure_retry_sec);
hard_failures++;
if (hard_failure_retry_sec < MAX_RETRY_SECONDS)
hard_failure_retry_sec *= 2;
}
}
state = State.Idle;
}
//
// Async code for now playing
public void NowPlaying (string artist, string title, string album, double duration,
int tracknum)
{
NowPlaying (artist, title, album, duration, tracknum, "");
}
public void NowPlaying (string artist, string title, string album, double duration,
int tracknum, string mbrainzid)
{
if (String.IsNullOrEmpty(artist) || String.IsNullOrEmpty(title) || !connected) {
return;
}
string str_track_number = String.Empty;
if (tracknum != 0) {
str_track_number = tracknum.ToString();
}
// Fall back to prefixing the URL with a # in case we haven't actually
// authenticated yet. We replace it with the now_playing_url and session_id
// later on in NowPlaying(uri).
string dataprefix = "#";
if (session_id != null) {
dataprefix = String.Format ("s={0}", session_id);
}
string data = String.Format ("{0}&a={1}&t={2}&b={3}&l={4}&n={5}&m={6}",
dataprefix,
HttpUtility.UrlEncode(artist),
HttpUtility.UrlEncode(title),
HttpUtility.UrlEncode(album),
duration.ToString("F0"),
str_track_number,
mbrainzid);
NowPlaying (data);
}
private void NowPlaying (string data)
{
if (now_playing_started) {
return;
}
// If the URI begins with #, then we know the URI was created before we
// had actually authenticated. So, because we didn't know the session_id and
// now_playing_url previously, we should now, so we put that in and create our
// new URI.
if (data.StartsWith ("#") && session_id != null) {
data = String.Format ("s={0}{1}",
session_id,
data.Substring (1));
}
current_now_playing_data = data;
if (session_id == null) {
// Go connect - we'll come back later in main timer loop.
Start ();
return;
}
try {
now_playing_post = (HttpWebRequest) WebRequest.Create (now_playing_url);
now_playing_post.UserAgent = LastfmCore.UserAgent;
now_playing_post.Method = "POST";
now_playing_post.ContentType = "application/x-www-form-urlencoded";
if (state == State.Idle) {
// Don't actually POST it until we're idle (that is, we
// probably have stuff queued which will reset the Now
// Playing if we send them first).
now_playing_started = true;
now_playing_post.BeginGetRequestStream (NowPlayingGetRequestStream, data);
}
} catch (Exception ex) {
Log.Warning ("Audioscrobbler NowPlaying failed",
String.Format ("Exception while creating request: {0}", ex), false);
// Reset current_now_playing_data if it was the problem.
current_now_playing_data = null;
}
}
private void NowPlayingGetRequestStream (IAsyncResult ar)
{
try {
string data = ar.AsyncState as string;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] data_bytes = encoding.GetBytes (data);
Stream request_stream = now_playing_post.EndGetRequestStream (ar);
request_stream.Write (data_bytes, 0, data_bytes.Length);
request_stream.Close ();
now_playing_post.BeginGetResponse (NowPlayingGetResponse, null);
} catch (Exception e) {
Log.Exception (e);
}
}
private void NowPlayingGetResponse (IAsyncResult ar)
{
try {
WebResponse my_resp = now_playing_post.EndGetResponse (ar);
Stream s = my_resp.GetResponseStream ();
StreamReader sr = new StreamReader (s, Encoding.UTF8);
string line = sr.ReadLine ();
if (line == null) {
Log.Warning ("Audioscrobbler NowPlaying failed", "No response", false);
}
if (line.StartsWith ("BADSESSION")) {
Log.Warning ("Audioscrobbler NowPlaying failed", "Session ID sent was invalid", false);
// attempt to re-handshake on the next interval
session_id = null;
next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS);
state = State.NeedHandshake;
StartTransitionHandler ();
return;
} else if (line.StartsWith ("OK")) {
// NowPlaying submitted
Log.DebugFormat ("Submitted NowPlaying track to Audioscrobbler");
now_playing_started = false;
now_playing_post = null;
current_now_playing_data = null;
return;
} else {
Log.Warning ("Audioscrobbler NowPlaying failed", "Unexpected or no response", false);
}
}
catch (Exception e) {
Log.Warning ("Audioscrobbler NowPlaying failed",
String.Format("Failed to post NowPlaying: {0}", e), false);
}
// NowPlaying error/success is non-crucial.
hard_failures++;
if (hard_failures < 3) {
NowPlaying (current_now_playing_data);
} else {
// Give up - NowPlaying status information is non-critical.
current_now_playing_data = null;
now_playing_started = false;
now_playing_post = null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Dynamic;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Actions.Calls;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using System.Numerics;
namespace IronPython.Runtime {
public static partial class Converter {
#region Conversion Sites
private static readonly CallSite<Func<CallSite, object, int>> _intSite = MakeExplicitConvertSite<int>();
private static readonly CallSite<Func<CallSite, object, double>> _doubleSite = MakeExplicitConvertSite<double>();
private static readonly CallSite<Func<CallSite, object, Complex>> _complexSite = MakeExplicitConvertSite<Complex>();
private static readonly CallSite<Func<CallSite, object, BigInteger>> _bigIntSite = MakeExplicitConvertSite<BigInteger>();
private static readonly CallSite<Func<CallSite, object, string>> _stringSite = MakeExplicitConvertSite<string>();
private static readonly CallSite<Func<CallSite, object, bool>> _boolSite = MakeExplicitConvertSite<bool>();
private static readonly CallSite<Func<CallSite, object, char>> _charSite = MakeImplicitConvertSite<char>();
private static readonly CallSite<Func<CallSite, object, char>> _explicitCharSite = MakeExplicitConvertSite<char>();
private static readonly CallSite<Func<CallSite, object, IEnumerable>> _ienumerableSite = MakeImplicitConvertSite<IEnumerable>();
private static readonly CallSite<Func<CallSite, object, IEnumerator>> _ienumeratorSite = MakeImplicitConvertSite<IEnumerator>();
private static readonly Dictionary<Type, CallSite<Func<CallSite, object, object>>> _siteDict = new Dictionary<Type, CallSite<Func<CallSite, object, object>>>();
private static readonly CallSite<Func<CallSite, object, byte>> _byteSite = MakeExplicitConvertSite<byte>();
private static readonly CallSite<Func<CallSite, object, sbyte>> _sbyteSite = MakeExplicitConvertSite<sbyte>();
private static readonly CallSite<Func<CallSite, object, Int16>> _int16Site = MakeExplicitConvertSite<Int16>();
private static readonly CallSite<Func<CallSite, object, UInt16>> _uint16Site = MakeExplicitConvertSite<UInt16>();
private static readonly CallSite<Func<CallSite, object, UInt32>> _uint32Site = MakeExplicitConvertSite<UInt32>();
private static readonly CallSite<Func<CallSite, object, Int64>> _int64Site = MakeExplicitConvertSite<Int64>();
private static readonly CallSite<Func<CallSite, object, UInt64>> _uint64Site = MakeExplicitConvertSite<UInt64>();
private static readonly CallSite<Func<CallSite, object, decimal>> _decimalSite = MakeExplicitConvertSite<decimal>();
private static readonly CallSite<Func<CallSite, object, float>> _floatSite = MakeExplicitConvertSite<float>();
private static readonly CallSite<Func<CallSite, object, object>>
_tryByteSite = MakeExplicitTrySite<Byte>(),
_trySByteSite = MakeExplicitTrySite<SByte>(),
_tryInt16Site = MakeExplicitTrySite<Int16>(),
_tryInt32Site = MakeExplicitTrySite<Int32>(),
_tryInt64Site = MakeExplicitTrySite<Int64>(),
_tryUInt16Site = MakeExplicitTrySite<UInt16>(),
_tryUInt32Site = MakeExplicitTrySite<UInt32>(),
_tryUInt64Site = MakeExplicitTrySite<UInt64>(),
_tryDoubleSite = MakeExplicitTrySite<Double>(),
_tryCharSite = MakeExplicitTrySite<Char>(),
_tryBigIntegerSite = MakeExplicitTrySite<BigInteger>(),
_tryComplexSite = MakeExplicitTrySite<Complex>(),
_tryStringSite = MakeExplicitTrySite<String>();
private static CallSite<Func<CallSite, object, T>> MakeImplicitConvertSite<T>() {
return MakeConvertSite<T>(ConversionResultKind.ImplicitCast);
}
private static CallSite<Func<CallSite, object, T>> MakeExplicitConvertSite<T>() {
return MakeConvertSite<T>(ConversionResultKind.ExplicitCast);
}
private static CallSite<Func<CallSite, object, T>> MakeConvertSite<T>(ConversionResultKind kind) {
return CallSite<Func<CallSite, object, T>>.Create(
DefaultContext.DefaultPythonContext.Convert(
typeof(T),
kind
)
);
}
private static CallSite<Func<CallSite, object, object>> MakeExplicitTrySite<T>() {
return MakeTrySite<T>(ConversionResultKind.ExplicitTry);
}
private static CallSite<Func<CallSite, object, object>> MakeTrySite<T>(ConversionResultKind kind) {
return CallSite<Func<CallSite, object, object>>.Create(
DefaultContext.DefaultPythonContext.Convert(
typeof(T),
kind
)
);
}
#endregion
#region Conversion entry points
public static Int32 ConvertToInt32(object value) { return _intSite.Target(_intSite, value); }
public static String ConvertToString(object value) { return _stringSite.Target(_stringSite, value); }
public static BigInteger ConvertToBigInteger(object value) { return _bigIntSite.Target(_bigIntSite, value); }
public static Double ConvertToDouble(object value) { return _doubleSite.Target(_doubleSite, value); }
public static Complex ConvertToComplex(object value) { return _complexSite.Target(_complexSite, value); }
public static Boolean ConvertToBoolean(object value) { return _boolSite.Target(_boolSite, value); }
public static Int64 ConvertToInt64(object value) { return _int64Site.Target(_int64Site, value); }
public static Byte ConvertToByte(object value) { return _byteSite.Target(_byteSite, value); }
public static SByte ConvertToSByte(object value) { return _sbyteSite.Target(_sbyteSite, value); }
public static Int16 ConvertToInt16(object value) { return _int16Site.Target(_int16Site, value); }
public static UInt16 ConvertToUInt16(object value) { return _uint16Site.Target(_uint16Site, value); }
public static UInt32 ConvertToUInt32(object value) { return _uint32Site.Target(_uint32Site, value); }
public static UInt64 ConvertToUInt64(object value) { return _uint64Site.Target(_uint64Site, value); }
public static Single ConvertToSingle(object value) { return _floatSite.Target(_floatSite, value); }
public static Decimal ConvertToDecimal(object value) { return _decimalSite.Target(_decimalSite, value); }
public static Char ConvertToChar(object value) { return _charSite.Target(_charSite, value); }
internal static bool TryConvertToByte(object value, out Byte result) {
object res = _tryByteSite.Target(_tryByteSite, value);
if (res != null) {
result = (Byte)res;
return true;
}
result = default(Byte);
return false;
}
internal static bool TryConvertToSByte(object value, out SByte result) {
object res = _trySByteSite.Target(_trySByteSite, value);
if (res != null) {
result = (SByte)res;
return true;
}
result = default(SByte);
return false;
}
internal static bool TryConvertToInt16(object value, out Int16 result) {
object res = _tryInt16Site.Target(_tryInt16Site, value);
if (res != null) {
result = (Int16)res;
return true;
}
result = default(Int16);
return false;
}
internal static bool TryConvertToInt32(object value, out Int32 result) {
object res = _tryInt32Site.Target(_tryInt32Site, value);
if (res != null) {
result = (Int32)res;
return true;
}
result = default(Int32);
return false;
}
internal static bool TryConvertToInt64(object value, out Int64 result) {
object res = _tryInt64Site.Target(_tryInt64Site, value);
if (res != null) {
result = (Int64)res;
return true;
}
result = default(Int64);
return false;
}
internal static bool TryConvertToUInt16(object value, out UInt16 result) {
object res = _tryUInt16Site.Target(_tryUInt16Site, value);
if (res != null) {
result = (UInt16)res;
return true;
}
result = default(UInt16);
return false;
}
internal static bool TryConvertToUInt32(object value, out UInt32 result) {
object res = _tryUInt32Site.Target(_tryUInt32Site, value);
if (res != null) {
result = (UInt32)res;
return true;
}
result = default(UInt32);
return false;
}
internal static bool TryConvertToUInt64(object value, out UInt64 result) {
object res = _tryUInt64Site.Target(_tryUInt64Site, value);
if (res != null) {
result = (UInt64)res;
return true;
}
result = default(UInt64);
return false;
}
internal static bool TryConvertToDouble(object value, out Double result) {
object res = _tryDoubleSite.Target(_tryDoubleSite, value);
if (res != null) {
result = (Double)res;
return true;
}
result = default(Double);
return false;
}
internal static bool TryConvertToBigInteger(object value, out BigInteger result) {
object res = _tryBigIntegerSite.Target(_tryBigIntegerSite, value);
if (res != null) {
result = (BigInteger)res;
return true;
}
result = default(BigInteger);
return false;
}
internal static bool TryConvertToComplex(object value, out Complex result) {
object res = _tryComplexSite.Target(_tryComplexSite, value);
if (res != null) {
result = (Complex)res;
return true;
}
result = default(Complex);
return false;
}
internal static bool TryConvertToString(object value, out String result) {
object res = _tryStringSite.Target(_tryStringSite, value);
if (res != null) {
result = (String)res;
return true;
}
result = default(String);
return false;
}
internal static bool TryConvertToChar(object value, out Char result) {
object res = _tryCharSite.Target(_tryCharSite, value);
if (res != null) {
result = (Char)res;
return true;
}
result = default(Char);
return false;
}
#endregion
internal static Char ExplicitConvertToChar(object value) {
return _explicitCharSite.Target(_explicitCharSite, value);
}
public static T Convert<T>(object value) {
return (T)Convert(value, typeof(T));
}
/// <summary>
/// General conversion routine TryConvert - tries to convert the object to the desired type.
/// Try to avoid using this method, the goal is to ultimately remove it!
/// </summary>
internal static bool TryConvert(object value, Type to, out object result) {
try {
result = Convert(value, to);
return true;
} catch {
result = default(object);
return false;
}
}
internal static object Convert(object value, Type to) {
CallSite<Func<CallSite, object, object>> site;
lock (_siteDict) {
if (!_siteDict.TryGetValue(to, out site)) {
_siteDict[to] = site = CallSite<Func<CallSite, object, object>>.Create(
DefaultContext.DefaultPythonContext.ConvertRetObject(
to,
ConversionResultKind.ExplicitCast
)
);
}
}
object res = site.Target(site, value);
if (to.IsValueType && res == null &&
(!to.IsGenericType || to.GetGenericTypeDefinition() != typeof(Nullable<>))) {
throw MakeTypeError(to, value);
}
return res;
}
/// <summary>
/// This function tries to convert an object to IEnumerator, or wraps it into an adapter
/// Do not use this function directly. It is only meant to be used by Ops.GetEnumerator.
/// </summary>
internal static bool TryConvertToIEnumerator(object o, out IEnumerator e) {
try {
e = _ienumeratorSite.Target(_ienumeratorSite, o);
return e != null;
} catch {
e = null;
return false;
}
}
/// <summary>
/// This function tries to convert an object to IEnumerator, or wraps it into an adapter
/// Do not use this function directly. It is only meant to be used by Ops.GetEnumerator.
/// </summary>
internal static IEnumerator ConvertToIEnumerator(object o) {
return _ienumeratorSite.Target(_ienumeratorSite, o);
}
public static IEnumerable ConvertToIEnumerable(object o) {
return _ienumerableSite.Target(_ienumerableSite, o);
}
internal static bool TryConvertToIndex(object value, out int index) {
return TryConvertToIndex(value, true, out index);
}
/// <summary>
/// Attempts to convert value into a index usable for slicing and return the integer
/// value. If the conversion fails false is returned.
///
/// If throwOverflowError is true then BigInteger's outside the normal range of integers will
/// result in an OverflowError.
/// </summary>
internal static bool TryConvertToIndex(object value, bool throwOverflowError, out int index) {
int? res = ConvertToSliceIndexHelper(value, throwOverflowError);
if (!res.HasValue) {
object callable;
if (PythonOps.TryGetBoundAttr(value, "__index__", out callable)) {
res = ConvertToSliceIndexHelper(PythonCalls.Call(callable), throwOverflowError);
}
}
index = res.HasValue ? res.Value : 0;
return res.HasValue;
}
internal static bool TryConvertToIndex(object value, out object index) {
return TryConvertToIndex(value, true, out index);
}
/// <summary>
/// Attempts to convert value into a index usable for slicing and return the integer
/// value. If the conversion fails false is returned.
///
/// If throwOverflowError is true then BigInteger's outside the normal range of integers will
/// result in an OverflowError.
/// </summary>
internal static bool TryConvertToIndex(object value, bool throwOverflowError, out object index) {
index = ConvertToSliceIndexHelper(value);
if (index == null) {
object callable;
if (PythonOps.TryGetBoundAttr(value, "__index__", out callable)) {
index = ConvertToSliceIndexHelper(PythonCalls.Call(callable));
}
}
return index != null;
}
public static int ConvertToIndex(object value) {
int? res = ConvertToSliceIndexHelper(value, false);
if (res.HasValue) {
return res.Value;
}
object callable;
if (PythonOps.TryGetBoundAttr(value, "__index__", out callable)) {
object index = PythonCalls.Call(callable);
res = ConvertToSliceIndexHelper(index, false);
if (res.HasValue) {
return res.Value;
}
throw PythonOps.TypeError("__index__ returned bad value: {0}", DynamicHelpers.GetPythonType(index).Name);
}
throw PythonOps.TypeError("expected index value, got {0}", DynamicHelpers.GetPythonType(value).Name);
}
private static int? ConvertToSliceIndexHelper(object value, bool throwOverflowError) {
if (value is int) return (int)value;
if (value is Extensible<int>) return ((Extensible<int>)value).Value;
BigInteger bi;
Extensible<BigInteger> ebi;
if (value is BigInteger) {
bi = (BigInteger)value;
} else if ((ebi = value as Extensible<BigInteger>) != null) {
bi = ebi.Value;
} else {
return null;
}
int res;
if (bi.AsInt32(out res)) return res;
if (throwOverflowError) {
throw PythonOps.OverflowError("can't fit long into index");
}
return bi == BigInteger.Zero ? 0 : bi > 0 ? Int32.MaxValue : Int32.MinValue;
}
private static object ConvertToSliceIndexHelper(object value) {
if (value is int) return value;
if (value is Extensible<int>) return ScriptingRuntimeHelpers.Int32ToObject(((Extensible<int>)value).Value);
if (value is BigInteger) {
return value;
} else if (value is Extensible<BigInteger>) {
return ((Extensible<BigInteger>)value).Value;
}
return null;
}
internal static Exception CannotConvertOverflow(string name, object value) {
return PythonOps.OverflowError("Cannot convert {0}({1}) to {2}", PythonTypeOps.GetName(value), value, name);
}
private static Exception MakeTypeError(Type expectedType, object o) {
return MakeTypeError(DynamicHelpers.GetPythonTypeFromType(expectedType).Name.ToString(), o);
}
private static Exception MakeTypeError(string expectedType, object o) {
return PythonOps.TypeErrorForTypeMismatch(expectedType, o);
}
#region Cached Type instances
private static readonly Type StringType = typeof(System.String);
private static readonly Type Int32Type = typeof(System.Int32);
private static readonly Type DoubleType = typeof(System.Double);
private static readonly Type DecimalType = typeof(System.Decimal);
private static readonly Type Int64Type = typeof(System.Int64);
private static readonly Type CharType = typeof(System.Char);
private static readonly Type SingleType = typeof(System.Single);
private static readonly Type BooleanType = typeof(System.Boolean);
private static readonly Type BigIntegerType = typeof(BigInteger);
private static readonly Type ComplexType = typeof(Complex);
private static readonly Type DelegateType = typeof(Delegate);
private static readonly Type IEnumerableType = typeof(IEnumerable);
private static readonly Type TypeType = typeof(Type);
private static readonly Type NullableOfTType = typeof(Nullable<>);
private static readonly Type IListOfTType = typeof(System.Collections.Generic.IList<>);
private static readonly Type IDictOfTType = typeof(System.Collections.Generic.IDictionary<,>);
private static readonly Type IEnumerableOfTType = typeof(System.Collections.Generic.IEnumerable<>);
private static readonly Type IListOfObjectType = typeof(System.Collections.Generic.IList<object>);
private static readonly Type IEnumerableOfObjectType = typeof(IEnumerable<object>);
private static readonly Type IDictionaryOfObjectType = typeof(System.Collections.Generic.IDictionary<object, object>);
#endregion
#region Entry points called from the generated code
public static object ConvertToReferenceType(object fromObject, RuntimeTypeHandle typeHandle) {
if (fromObject == null) return null;
return Convert(fromObject, Type.GetTypeFromHandle(typeHandle));
}
public static object ConvertToNullableType(object fromObject, RuntimeTypeHandle typeHandle) {
if (fromObject == null) return null;
return Convert(fromObject, Type.GetTypeFromHandle(typeHandle));
}
public static object ConvertToValueType(object fromObject, RuntimeTypeHandle typeHandle) {
if (fromObject == null) throw PythonOps.InvalidType(fromObject, typeHandle);
return Convert(fromObject, Type.GetTypeFromHandle(typeHandle));
}
public static Type ConvertToType(object value) {
if (value == null) return null;
Type TypeVal = value as Type;
if (TypeVal != null) return TypeVal;
if (value is PythonType pythonTypeVal) return pythonTypeVal.UnderlyingSystemType;
if (value is TypeGroup typeCollision) {
Type nonGenericType;
if (typeCollision.TryGetNonGenericType(out nonGenericType)) {
return nonGenericType;
}
}
throw MakeTypeError("Type", value);
}
public static object ConvertToDelegate(object value, Type to) {
if (value == null) return null;
return DefaultContext.DefaultCLS.LanguageContext.DelegateCreator.GetDelegate(value, to);
}
#endregion
public static bool CanConvertFrom(Type fromType, Type toType, NarrowingLevel allowNarrowing) {
ContractUtils.RequiresNotNull(fromType, "fromType");
ContractUtils.RequiresNotNull(toType, "toType");
if (toType == fromType) return true;
if (toType.IsAssignableFrom(fromType)) return true;
#if FEATURE_COM
if (fromType.IsCOMObject && toType.IsInterface) return true; // A COM object could be cast to any interface
#endif
if (HasImplicitNumericConversion(fromType, toType)) return true;
// Handling the hole that Type is the only object that we 'box'
if (toType == TypeType &&
(typeof(PythonType).IsAssignableFrom(fromType) ||
typeof(TypeGroup).IsAssignableFrom(fromType))) return true;
// Support extensible types with simple implicit conversions to their base types
if (typeof(Extensible<int>).IsAssignableFrom(fromType) && CanConvertFrom(Int32Type, toType, allowNarrowing)) {
return true;
}
if (typeof(Extensible<BigInteger>).IsAssignableFrom(fromType) && CanConvertFrom(BigIntegerType, toType, allowNarrowing)) {
return true;
}
if (typeof(ExtensibleString).IsAssignableFrom(fromType) && CanConvertFrom(StringType, toType, allowNarrowing)) {
return true;
}
if (typeof(Extensible<double>).IsAssignableFrom(fromType) && CanConvertFrom(DoubleType, toType, allowNarrowing)) {
return true;
}
if (typeof(Extensible<Complex>).IsAssignableFrom(fromType) && CanConvertFrom(ComplexType, toType, allowNarrowing)) {
return true;
}
#if FEATURE_CUSTOM_TYPE_DESCRIPTOR
// try available type conversions...
var tcas = toType.GetCustomAttributes(typeof(TypeConverterAttribute), true);
foreach (TypeConverterAttribute tca in tcas) {
TypeConverter tc = GetTypeConverter(tca);
if (tc == null) continue;
if (tc.CanConvertFrom(fromType)) {
return true;
}
}
#endif
//!!!do user-defined implicit conversions here
if (allowNarrowing == PythonNarrowing.None) return false;
return HasNarrowingConversion(fromType, toType, allowNarrowing);
}
#if FEATURE_CUSTOM_TYPE_DESCRIPTOR
private static TypeConverter GetTypeConverter(TypeConverterAttribute tca) {
try {
ConstructorInfo ci = Type.GetType(tca.ConverterTypeName).GetConstructor(ReflectionUtils.EmptyTypes);
if (ci != null) return ci.Invoke(ArrayUtils.EmptyObjects) as TypeConverter;
} catch (TargetInvocationException) {
}
return null;
}
#endif
private static bool HasImplicitNumericConversion(Type fromType, Type toType) {
if (fromType.IsEnum) return false;
if (fromType == typeof(BigInteger)) {
if (toType == typeof(double)) return true;
if (toType == typeof(float)) return true;
if (toType == typeof(Complex)) return true;
return false;
}
if (fromType == typeof(bool)) {
if (toType == typeof(int)) return true;
return HasImplicitNumericConversion(typeof(int), toType);
}
switch (fromType.GetTypeCode()) {
case TypeCode.SByte:
switch (toType.GetTypeCode()) {
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Byte:
switch (toType.GetTypeCode()) {
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Int16:
switch (toType.GetTypeCode()) {
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.UInt16:
switch (toType.GetTypeCode()) {
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Int32:
switch (toType.GetTypeCode()) {
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.UInt32:
switch (toType.GetTypeCode()) {
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Int64:
switch (toType.GetTypeCode()) {
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.UInt64:
switch (toType.GetTypeCode()) {
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Char:
switch (toType.GetTypeCode()) {
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Single:
switch (toType.GetTypeCode()) {
case TypeCode.Double:
return true;
default:
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Double:
switch (toType.GetTypeCode()) {
default:
if (toType == ComplexType) return true;
return false;
}
default:
return false;
}
}
public static Candidate PreferConvert(Type t1, Type t2) {
if (t1 == typeof(bool) && t2 == typeof(int)) return Candidate.Two;
if (t1 == typeof(Decimal) && t2 == typeof(BigInteger)) return Candidate.Two;
//if (t1 == typeof(int) && t2 == typeof(BigInteger)) return Candidate.Two;
switch (t1.GetTypeCode()) {
case TypeCode.SByte:
switch (t2.GetTypeCode()) {
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return Candidate.Two;
default:
return Candidate.Equivalent;
}
case TypeCode.Int16:
switch (t2.GetTypeCode()) {
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return Candidate.Two;
default:
return Candidate.Equivalent;
}
case TypeCode.Int32:
switch (t2.GetTypeCode()) {
case TypeCode.UInt32:
case TypeCode.UInt64:
return Candidate.Two;
default:
return Candidate.Equivalent;
}
case TypeCode.Int64:
switch (t2.GetTypeCode()) {
case TypeCode.UInt64:
return Candidate.Two;
default:
return Candidate.Equivalent;
}
}
return Candidate.Equivalent;
}
private static bool HasNarrowingConversion(Type fromType, Type toType, NarrowingLevel allowNarrowing) {
if (allowNarrowing == PythonNarrowing.IndexOperator) {
if (toType == CharType && fromType == StringType) return true;
if (toType == StringType && fromType == CharType) return true;
//if (toType == Int32Type && fromType == BigIntegerType) return true;
//if (IsIntegral(fromType) && IsIntegral(toType)) return true;
//Check if there is an implicit convertor defined on fromType to toType
if (HasImplicitConversion(fromType, toType)) {
return true;
}
}
if (toType == DoubleType && fromType == DecimalType) return true;
if (toType == SingleType && fromType == DecimalType) return true;
if (toType.IsArray) {
return typeof(PythonTuple).IsAssignableFrom(fromType);
}
if (allowNarrowing == PythonNarrowing.IndexOperator) {
if (IsNumeric(fromType) && IsNumeric(toType)) {
if (fromType != typeof(float) && fromType != typeof(double) && fromType != typeof(decimal) && fromType != typeof(Complex)) {
return true;
}
}
if (fromType == typeof(bool) && IsNumeric(toType)) return true;
if (toType == CharType && fromType == StringType) return true;
if (toType == Int32Type && fromType == BooleanType) return true;
// Everything can convert to Boolean in Python
if (toType == BooleanType) return true;
if (DelegateType.IsAssignableFrom(toType) && IsPythonType(fromType)) return true;
if (IEnumerableType == toType && IsPythonType(fromType)) return true;
if (toType == typeof(IEnumerator)) {
if (IsPythonType(fromType)) return true;
} else if (toType.IsGenericType) {
Type genTo = toType.GetGenericTypeDefinition();
if (genTo == IEnumerableOfTType) {
return IEnumerableOfObjectType.IsAssignableFrom(fromType) ||
IEnumerableType.IsAssignableFrom(fromType) ||
fromType == typeof(OldInstance);
} else if (genTo == typeof(System.Collections.Generic.IEnumerator<>)) {
if (IsPythonType(fromType)) return true;
}
}
}
if (allowNarrowing == PythonNarrowing.All) {
//__int__, __float__, __long__
if (IsNumeric(fromType) && IsNumeric(toType)) return true;
if (toType == Int32Type && HasPythonProtocol(fromType, "__int__")) return true;
if (toType == DoubleType && HasPythonProtocol(fromType, "__float__")) return true;
if (toType == BigIntegerType && HasPythonProtocol(fromType, "__long__")) return true;
}
if (toType.IsGenericType) {
Type genTo = toType.GetGenericTypeDefinition();
if (genTo == IListOfTType) {
return IListOfObjectType.IsAssignableFrom(fromType);
} else if (genTo == NullableOfTType) {
if (fromType == typeof(DynamicNull) || CanConvertFrom(fromType, toType.GetGenericArguments()[0], allowNarrowing)) {
return true;
}
} else if (genTo == IDictOfTType) {
return IDictionaryOfObjectType.IsAssignableFrom(fromType);
}
}
if (fromType == BigIntegerType && toType == Int64Type) return true;
if (toType.IsEnum && fromType == Enum.GetUnderlyingType(toType)) return true;
return false;
}
private static bool HasImplicitConversion(Type fromType, Type toType) {
return
HasImplicitConversionWorker(fromType, fromType, toType) ||
HasImplicitConversionWorker(toType, fromType, toType);
}
private static bool HasImplicitConversionWorker(Type lookupType, Type fromType, Type toType) {
while (lookupType != null) {
foreach (MethodInfo method in lookupType.GetMethods()) {
if (method.Name == "op_Implicit" &&
method.GetParameters()[0].ParameterType.IsAssignableFrom(fromType) &&
toType.IsAssignableFrom(method.ReturnType)) {
return true;
}
}
lookupType = lookupType.BaseType;
}
return false;
}
/// <summary>
/// Converts a value to int ignoring floats
/// </summary>
public static int? ImplicitConvertToInt32(object o) {
if (o is int) {
return (int)o;
} else if (o is BigInteger) {
int res;
if (((BigInteger)o).AsInt32(out res)) {
return res;
}
} else if (o is Extensible<int>) {
return Converter.ConvertToInt32(o);
} else if (o is Extensible<BigInteger>) {
int res;
if (Converter.TryConvertToInt32(o, out res)) {
return res;
}
}
if (!(o is double) && !(o is float) && !(o is Extensible<double>)) {
object objres;
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__int__", out objres)) {
if (objres is int) {
return (int)objres;
}
}
}
return null;
}
internal static bool IsNumeric(Type t) {
if (t.IsEnum) return false;
const TypeCode TypeCodeDbNull = (TypeCode)2; // TypeCode.DBNull
switch (t.GetTypeCode()) {
case TypeCode.DateTime:
case TypeCodeDbNull:
case TypeCode.Char:
case TypeCode.Empty:
case TypeCode.String:
case TypeCode.Boolean:
return false;
case TypeCode.Object:
return t == BigIntegerType || t == ComplexType;
default:
return true;
}
}
private static bool IsPythonType(Type t) {
return t.FullName.StartsWith("IronPython."); //!!! this and the check below are hacks
}
private static bool HasPythonProtocol(Type t, string name) {
if (t.FullName.StartsWith(NewTypeMaker.TypePrefix)) return true;
if (t == typeof(OldInstance)) return true;
PythonType dt = DynamicHelpers.GetPythonTypeFromType(t);
if (dt == null) return false;
PythonTypeSlot tmp;
return dt.TryResolveSlot(DefaultContext.Default, name, out tmp);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute
{
/// <summary>
/// The Compute Management API includes operations for managing the load
/// balancers for your subscription.
/// </summary>
internal partial class LoadBalancerOperations : IServiceOperations<ComputeManagementClient>, ILoadBalancerOperations
{
/// <summary>
/// Initializes a new instance of the LoadBalancerOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LoadBalancerOperations(ComputeManagementClient client)
{
this._client = client;
}
private ComputeManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient.
/// </summary>
public ComputeManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Add an internal load balancer to a an existing deployment. When
/// used by an input endpoint, the internal load balancer will provide
/// an additional private VIP that can be used for load balancing to
/// the roles in this deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Load Balancer 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>
public async Task<OperationStatusResponse> BeginCreatingAsync(string serviceName, string deploymentName, LoadBalancerCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/loadbalancers";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-09-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement loadBalancerElement = new XElement(XName.Get("LoadBalancer", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(loadBalancerElement);
if (parameters.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
loadBalancerElement.Add(nameElement);
}
if (parameters.FrontendIPConfiguration != null)
{
XElement frontendIpConfigurationElement = new XElement(XName.Get("FrontendIpConfiguration", "http://schemas.microsoft.com/windowsazure"));
loadBalancerElement.Add(frontendIpConfigurationElement);
if (parameters.FrontendIPConfiguration.Type != null)
{
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = parameters.FrontendIPConfiguration.Type;
frontendIpConfigurationElement.Add(typeElement);
}
if (parameters.FrontendIPConfiguration.SubnetName != null)
{
XElement subnetNameElement = new XElement(XName.Get("SubnetName", "http://schemas.microsoft.com/windowsazure"));
subnetNameElement.Value = parameters.FrontendIPConfiguration.SubnetName;
frontendIpConfigurationElement.Add(subnetNameElement);
}
if (parameters.FrontendIPConfiguration.StaticVirtualNetworkIPAddress != null)
{
XElement staticVirtualNetworkIPAddressElement = new XElement(XName.Get("StaticVirtualNetworkIPAddress", "http://schemas.microsoft.com/windowsazure"));
staticVirtualNetworkIPAddressElement.Value = parameters.FrontendIPConfiguration.StaticVirtualNetworkIPAddress;
frontendIpConfigurationElement.Add(staticVirtualNetworkIPAddressElement);
}
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete an internal load balancer from the deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='loadBalancerName'>
/// Required. The name of the load balancer.
/// </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>
public async Task<OperationStatusResponse> BeginDeletingAsync(string serviceName, string deploymentName, string loadBalancerName, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (loadBalancerName == null)
{
throw new ArgumentNullException("loadBalancerName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/loadbalancers/";
url = url + Uri.EscapeDataString(loadBalancerName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-09-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates an internal load balancer associated with an existing
/// deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='loadBalancerName'>
/// Required. The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Load Balancer 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>
public async Task<OperationStatusResponse> BeginUpdatingAsync(string serviceName, string deploymentName, string loadBalancerName, LoadBalancerUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (loadBalancerName == null)
{
throw new ArgumentNullException("loadBalancerName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginUpdatingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/loadbalancers/";
url = url + Uri.EscapeDataString(loadBalancerName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-09-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement loadBalancerElement = new XElement(XName.Get("LoadBalancer", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(loadBalancerElement);
if (parameters.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = parameters.Name;
loadBalancerElement.Add(nameElement);
}
if (parameters.FrontendIPConfiguration != null)
{
XElement frontendIpConfigurationElement = new XElement(XName.Get("FrontendIpConfiguration", "http://schemas.microsoft.com/windowsazure"));
loadBalancerElement.Add(frontendIpConfigurationElement);
if (parameters.FrontendIPConfiguration.Type != null)
{
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = parameters.FrontendIPConfiguration.Type;
frontendIpConfigurationElement.Add(typeElement);
}
if (parameters.FrontendIPConfiguration.SubnetName != null)
{
XElement subnetNameElement = new XElement(XName.Get("SubnetName", "http://schemas.microsoft.com/windowsazure"));
subnetNameElement.Value = parameters.FrontendIPConfiguration.SubnetName;
frontendIpConfigurationElement.Add(subnetNameElement);
}
if (parameters.FrontendIPConfiguration.StaticVirtualNetworkIPAddress != null)
{
XElement staticVirtualNetworkIPAddressElement = new XElement(XName.Get("StaticVirtualNetworkIPAddress", "http://schemas.microsoft.com/windowsazure"));
staticVirtualNetworkIPAddressElement.Value = parameters.FrontendIPConfiguration.StaticVirtualNetworkIPAddress;
frontendIpConfigurationElement.Add(staticVirtualNetworkIPAddressElement);
}
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Add an internal load balancer to a an existing deployment. When
/// used by an input endpoint, the internal load balancer will provide
/// an additional private VIP that can be used for load balancing to
/// the roles in this deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Load Balancer 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>
public async Task<OperationStatusResponse> CreateAsync(string serviceName, string deploymentName, LoadBalancerCreateParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.LoadBalancers.BeginCreatingAsync(serviceName, deploymentName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Delete an internal load balancer from the deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='loadBalancerName'>
/// Required. The name of the load balancer.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string serviceName, string deploymentName, string loadBalancerName, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.LoadBalancers.BeginDeletingAsync(serviceName, deploymentName, loadBalancerName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// Updates an internal load balancer associated with an existing
/// deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the service.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='loadBalancerName'>
/// Required. The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Load Balancer 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>
public async Task<OperationStatusResponse> UpdateAsync(string serviceName, string deploymentName, string loadBalancerName, LoadBalancerUpdateParameters parameters, CancellationToken cancellationToken)
{
ComputeManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.LoadBalancers.BeginUpdatingAsync(serviceName, deploymentName, loadBalancerName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
#if !(NET35 || NET20 || PORTABLE40)
using System.Dynamic;
#endif
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private JsonContract _rootContract;
private int _rootLevel;
private readonly List<object> _serializeStack = new List<object>();
private JsonSerializerProxy _internalSerializer;
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
{
if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter");
_rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
_rootLevel = _serializeStack.Count + 1;
JsonContract contract = GetContractSafe(value);
try
{
if (ShouldWriteReference(value, null, contract, null, null))
{
WriteReference(jsonWriter, value);
}
else
{
SerializeValue(jsonWriter, value, contract, null, null, null);
}
}
catch (Exception ex)
{
if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
{
HandleError(jsonWriter, 0);
}
else
{
// clear context in case serializer is being used inside a converter
// if the converter wraps the error then not clearing the context will cause this error:
// "Current error context error is different to requested error."
ClearErrorContext();
throw;
}
}
finally
{
// clear root contract to ensure that if level was > 1 then it won't
// accidently be used for non root values
_rootContract = null;
}
}
private JsonSerializerProxy GetInternalSerializer()
{
if (_internalSerializer == null)
_internalSerializer = new JsonSerializerProxy(this);
return _internalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
return null;
return Serializer._contractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (contract.TypeCode == PrimitiveTypeCode.Bytes)
{
// if type name handling is enabled then wrap the base64 byte string in an object with the type name
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false);
JsonWriter.WriteValue(writer, contract.TypeCode, value);
writer.WriteEndObject();
return;
}
}
JsonWriter.WriteValue(writer, contract.TypeCode, value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
JsonConverter converter =
((member != null) ? member.Converter : null) ??
((containerProperty != null) ? containerProperty.ItemConverter : null) ??
((containerContract != null) ? containerContract.ItemConverter : null) ??
valueContract.Converter ??
Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
valueContract.InternalConverter;
if (converter != null && converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
if (!arrayContract.IsMultidimensionalArray)
SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
else
SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract)valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
break;
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
break;
#endif
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
case JsonContractType.Serializable:
SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
break;
#endif
case JsonContractType.Linq:
((JToken)value).WriteTo(writer, Serializer.Converters.ToArray());
break;
}
}
private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
isReference = property.IsReference;
if (isReference == null && containerProperty != null)
isReference = containerProperty.ItemIsReference;
if (isReference == null && collectionContract != null)
isReference = collectionContract.ItemIsReference;
if (isReference == null)
isReference = contract.IsReference;
return isReference;
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (value == null)
return false;
if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
return false;
bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);
if (isReference == null)
{
if (valueContract.ContractType == JsonContractType.Array)
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
else
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
}
if (!isReference.Value)
return false;
return Serializer.GetReferenceResolver().IsReferenced(this, value);
}
private bool ShouldWriteProperty(object memberValue, JsonProperty property)
{
if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
return false;
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue()))
return false;
return true;
}
private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
return true;
ReferenceLoopHandling? referenceLoopHandling = null;
if (property != null)
referenceLoopHandling = property.ReferenceLoopHandling;
if (referenceLoopHandling == null && containerProperty != null)
referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
if (referenceLoopHandling == null && containerContract != null)
referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
if (_serializeStack.IndexOf(value) != -1)
{
string message = "Self referencing loop detected";
if (property != null)
message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());
switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling))
{
case ReferenceLoopHandling.Error:
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
case ReferenceLoopHandling.Ignore:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
return false;
case ReferenceLoopHandling.Serialize:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
return true;
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null);
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false);
writer.WriteValue(reference);
writer.WriteEndObject();
}
private string GetReference(JsonWriter writer, object value)
{
try
{
string reference = Serializer.GetReferenceResolver().GetReference(this, value);
return reference;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex);
}
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
&& !(converter is ComponentConverter)
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
s = converter.ConvertToInvariantString(value);
return true;
}
}
#endif
#if NETFX_CORE || PORTABLE
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
OnSerializing(writer, contract, value);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
OnSerialized(writer, contract, value);
}
private void OnSerializing(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerializing(value, Serializer._context);
}
private void OnSerialized(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerialized(value, Serializer._context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
continue;
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
if (contract.ExtensionDataGetter != null)
{
IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value);
if (extensionData != null)
{
foreach (KeyValuePair<object, object> e in extensionData)
{
JsonContract keyContract = GetContractSafe(e.Key);
JsonContract valueContract = GetContractSafe(e.Value);
bool escape;
string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape);
if (ShouldWriteReference(e.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, e.Value);
}
else
{
if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName);
SerializeValue(writer, e.Value, valueContract, null, contract, member);
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue)
{
if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value))
{
if (property.PropertyContract == null)
property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
memberValue = property.ValueProvider.GetValue(value);
memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue);
if (ShouldWriteProperty(memberValue, property))
{
if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
{
property.WritePropertyName(writer);
WriteReference(writer, memberValue);
return false;
}
if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
return false;
if (memberValue == null)
{
JsonObjectContract objectContract = contract as JsonObjectContract;
Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default;
if (resolvedRequired == Required.Always)
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
return true;
}
}
memberContract = null;
memberValue = null;
return false;
}
private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
writer.WriteStartObject();
bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
// don't make readonly fields the referenced value because they can't be deserialized to
if (isReference && (member == null || member.Writable))
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, value);
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
}
private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null);
writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false);
writer.WriteValue(reference);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null);
writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false);
writer.WriteValue(typeName);
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
return;
_serializeStack.Add(value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
converter.WriteJson(writer, value, GetInternalSerializer());
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedCollection wrappedCollection = values as IWrappedCollection;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList);
_serializeStack.Add(underlyingList);
bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingList);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, values);
_serializeStack.Add(values);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);
SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, values);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
{
int dimension = indices.Length;
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
writer.WriteStartArray();
for (int i = 0; i < values.GetLength(dimension); i++)
{
newIndices[dimension] = i;
bool isTopLevel = (newIndices.Length == values.Rank);
if (isTopLevel)
{
object value = values.GetValue(newIndices);
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth + 1);
else
throw;
}
}
else
{
SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
}
}
writer.WriteEndArray();
}
private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
// don't make readonly fields the referenced value because they can't be deserialized to
isReference = (isReference && (member == null || member.Writable));
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
}
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
return writeMetadataObject;
}
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35)
[SecuritySafeCritical]
#endif
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (!JsonTypeReflector.FullyTrusted)
{
string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
@"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType());
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
}
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer._context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
JsonContract valueContract = GetContractSafe(serializationEntry.Value);
if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
WriteReference(writer, serializationEntry.Value);
}
else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
#if !(NET35 || NET20 || PORTABLE40)
private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
// only write non-dynamic properties that have an explicit attribute
if (property.HasMemberAttribute)
{
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
continue;
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
}
foreach (string memberName in value.GetDynamicMemberNames())
{
object memberValue;
if (contract.TryGetMember(value, memberName, out memberValue))
{
try
{
JsonContract valueContract = GetContractSafe(memberValue);
if (!ShouldWriteDynamicProperty(memberValue))
continue;
if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member))
{
string resolvedPropertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(memberName)
: memberName;
writer.WritePropertyName(resolvedPropertyName);
SerializeValue(writer, memberValue, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
private bool ShouldWriteDynamicProperty(object memberValue)
{
if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null)
return false;
if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) &&
(memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType()))))
return false;
return true;
}
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
TypeNameHandling resolvedTypeNameHandling =
((member != null) ? member.TypeNameHandling : null)
?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null)
?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
?? Serializer._typeNameHandling;
if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
return true;
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
{
if (member != null)
{
if (contract.UnderlyingType != member.PropertyContract.CreatedType)
return true;
}
else if (containerContract != null)
{
if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType)
return true;
}
else if (_rootContract != null && _serializeStack.Count == _rootLevel)
{
if (contract.UnderlyingType != _rootContract.CreatedType)
return true;
}
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary);
WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
if (contract.KeyContract == null)
contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
int initialDepth = writer.Top;
foreach (DictionaryEntry entry in values)
{
bool escape;
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);
propertyName = (contract.DictionaryKeyResolver != null)
? contract.DictionaryKeyResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName, escape);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName, escape);
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingDictionary);
}
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{
string propertyName;
if (contract.ContractType == JsonContractType.Primitive)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeString(sw, (DateTime)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#if !NET20
else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#endif
else
{
escape = true;
return Convert.ToString(name, CultureInfo.InvariantCulture);
}
}
else if (TryConvertToString(name, name.GetType(), out propertyName))
{
escape = true;
return propertyName;
}
else
{
escape = true;
return name.ToString();
}
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
if (writer.WriteState == WriteState.Property)
writer.WriteNull();
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
return true;
bool shouldSerialize = property.ShouldSerialize(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null);
return shouldSerialize;
}
private bool IsSpecified(JsonWriter writer, JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
return true;
bool isSpecified = property.GetIsSpecified(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null);
return isSpecified;
}
}
}
| |
//
// GtkExtensions.cs
//
// Author:
// Vsevolod Kukol <v.kukol@rubologic.de>
//
// Copyright (c) 2014 Vsevolod Kukol
//
// 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 Gdk;
namespace Xwt.GtkBackend
{
public static class Gtk2Extensions
{
public static void SetHasWindow (this Gtk.Widget widget, bool value)
{
if (value)
widget.WidgetFlags &= ~Gtk.WidgetFlags.NoWindow;
else
widget.WidgetFlags |= Gtk.WidgetFlags.NoWindow;
}
public static bool GetHasWindow (this Gtk.Widget widget)
{
return !widget.IsNoWindow;
}
public static void SetAppPaintable (this Gtk.Widget widget, bool value)
{
if (value)
widget.WidgetFlags |= Gtk.WidgetFlags.AppPaintable;
else
widget.WidgetFlags &= ~Gtk.WidgetFlags.AppPaintable;
}
public static void SetStateActive(this Gtk.Widget widget)
{
widget.State = Gtk.StateType.Active;
}
public static void SetStateNormal(this Gtk.Widget widget)
{
widget.State = Gtk.StateType.Normal;
}
public static void AddSignalHandler (this Gtk.Widget widget, string name, Delegate handler, Type args_type)
{
var signal = GLib.Signal.Lookup (widget, name, args_type);
signal.AddDelegate (handler);
}
public static void RemoveSignalHandler (this Gtk.Widget widget, string name, Delegate handler)
{
var signal = GLib.Signal.Lookup (widget, name);
signal.RemoveDelegate (handler);
}
public static Gdk.Pixbuf ToPixbuf (this Gdk.Window window, int src_x, int src_y, int width, int height)
{
return Gdk.Pixbuf.FromDrawable (window, Gdk.Colormap.System, src_x, src_y, 0, 0, width, height);
}
public static Gtk.CellRenderer[] GetCellRenderers (this Gtk.TreeViewColumn column)
{
return column.CellRenderers;
}
public static Gdk.DragAction GetSelectedAction (this Gdk.DragContext context)
{
return context.Action;
}
public static Gdk.Atom[] ListTargets (this Gdk.DragContext context)
{
return context.Targets;
}
public static void AddContent (this Gtk.Dialog dialog, Gtk.Widget widget, bool expand = true, bool fill = true, uint padding = 0)
{
dialog.VBox.PackStart (widget, expand, fill, padding);
}
public static void AddContent (this Gtk.MessageDialog dialog, Gtk.Widget widget, bool expand = true, bool fill = true, uint padding = 0)
{
var messageArea = dialog.GetMessageArea () ?? dialog.VBox;
messageArea.PackStart (widget, expand, fill, padding);
}
public static void SetContentSpacing (this Gtk.Dialog dialog, int spacing)
{
dialog.VBox.Spacing = spacing;
}
public static void SetTextColumn (this Gtk.ComboBox comboBox, int column)
{
((Gtk.ComboBoxEntry)comboBox).TextColumn = column;
}
public static void FixContainerLeak (this Gtk.Container c)
{
GtkWorkarounds.FixContainerLeak (c);
}
public static Xwt.Drawing.Color GetBackgroundColor (this Gtk.Widget widget)
{
return widget.GetBackgroundColor (Gtk.StateType.Normal);
}
public static Xwt.Drawing.Color GetBackgroundColor (this Gtk.Widget widget, Gtk.StateType state)
{
return widget.Style.Background (state).ToXwtValue ();
}
public static void SetBackgroundColor (this Gtk.Widget widget, Xwt.Drawing.Color color)
{
widget.SetBackgroundColor (Gtk.StateType.Normal, color);
}
public static void SetBackgroundColor (this Gtk.Widget widget, Gtk.StateType state, Xwt.Drawing.Color color)
{
widget.ModifyBg (state, color.ToGtkValue ());
}
public static void SetChildBackgroundColor (this Gtk.Container container, Xwt.Drawing.Color color)
{
foreach (var widget in container.Children)
widget.ModifyBg (Gtk.StateType.Normal, color.ToGtkValue ());
}
public static string GetText (this Gtk.TextInsertedArgs args)
{
return args.Text;
}
public static void RenderPlaceholderText (this Gtk.Entry entry, Gtk.ExposeEventArgs args, string placeHolderText, ref Pango.Layout layout)
{
// The Entry's GdkWindow is the top level window onto which
// the frame is drawn; the actual text entry is drawn into a
// separate window, so we can ensure that for themes that don't
// respect HasFrame, we never ever allow the base frame drawing
// to happen
if (args.Event.Window == entry.GdkWindow)
return;
if (entry.Text.Length > 0)
return;
RenderPlaceholderText_internal (entry, args, placeHolderText, ref layout, entry.Xalign, 0.5f, 1, 0);
}
static void RenderPlaceholderText_internal (Gtk.Widget widget, Gtk.ExposeEventArgs args, string placeHolderText, ref Pango.Layout layout, float xalign, float yalign, int xpad, int ypad)
{
if (layout == null) {
layout = new Pango.Layout (widget.PangoContext);
layout.FontDescription = widget.PangoContext.FontDescription.Copy ();
}
int wh, ww;
args.Event.Window.GetSize (out ww, out wh);
int width, height;
layout.SetText (placeHolderText);
layout.GetPixelSize (out width, out height);
int x = xpad + (int)((ww - width) * xalign);
int y = ypad + (int)((wh - height) * yalign);
using (var gc = new Gdk.GC (args.Event.Window)) {
gc.Copy (widget.Style.TextGC (Gtk.StateType.Normal));
Xwt.Drawing.Color color_a = widget.Style.Base (Gtk.StateType.Normal).ToXwtValue ();
Xwt.Drawing.Color color_b = widget.Style.Text (Gtk.StateType.Normal).ToXwtValue ();
gc.RgbFgColor = color_b.BlendWith (color_a, 0.5).ToGtkValue ();
args.Event.Window.DrawLayout (gc, x, y, layout);
}
}
public static double GetSliderPosition (this Gtk.Scale scale)
{
Gtk.Orientation orientation;
if (scale is Gtk.HScale)
orientation = Gtk.Orientation.Horizontal;
else if (scale is Gtk.VScale)
orientation = Gtk.Orientation.Vertical;
else
throw new InvalidOperationException ("Can not obtain slider position from " + scale.GetType ());
var padding = (int)scale.StyleGetProperty ("focus-padding");
var slwidth = Convert.ToDouble (scale.StyleGetProperty ("slider-width"));
int orientationSize;
if (orientation == Gtk.Orientation.Horizontal)
orientationSize = scale.Allocation.Width - (2 * padding);
else
orientationSize = scale.Allocation.Height - (2 * padding);
double prct = 0;
if (scale.Adjustment.Lower >= 0) {
prct = (scale.Value / (scale.Adjustment.Upper - scale.Adjustment.Lower));
} else if (scale.Adjustment.Upper <= 0) {
prct = (Math.Abs (scale.Value) / Math.Abs (scale.Adjustment.Lower - scale.Adjustment.Upper));
} else if (scale.Adjustment.Lower < 0) {
if (scale.Value >= 0)
prct = 0.5 + ((scale.Value / 2) / scale.Adjustment.Upper);
else
prct = 0.5 - Math.Abs ((scale.Value / 2) / scale.Adjustment.Lower);
}
if (orientation == Gtk.Orientation.Vertical || scale.Inverted)
prct = 1 - prct;
return (int)(((orientationSize - (slwidth)) * prct) + (slwidth / 2));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using InAudioLeanTween;
using InAudioSystem;
using InAudioSystem.ExtensionMethods;
using InAudioSystem.Internal;
using InAudioSystem.Runtime;
using UnityEngine;
using UnityEngine.Audio;
/// <summary>
/// InAudio class used to play audio with.
/// You can use this class to change the parameters of a playing node, but it is not made to be used directly.
/// You can used the OnCompleted callback to be notificed when it is done playing.
/// </summary>
public class InPlayer : MonoBehaviour
{
/// <summary>
/// To call when the audio is done playing
/// </summary>
public Action<GameObject, InAudioNode> OnCompleted;
/// <summary>
/// The volume of the player. This does not account for rolloff or if the playing nodes volumes.
/// </summary>
public float Volume
{
get { return audioParameters.Volume; }
set
{
audioParameters.StereoPan = Volume;
for (int i = 0; i < audioSources.Count; i++)
{
if (audioSources == null)
continue;
var source = audioSources[i];
SetVolume(source, audioParameters.Volume);
}
}
}
/// <summary>
/// The node playing. Not including any children nodes.
/// </summary>
public InAudioNode NodePlaying
{
get { return PlayingNode; }
}
/// <summary>
/// Break any looping sounds
/// </summary>
public void Break()
{
breakLoop = true;
}
/// <summary>
/// 3D SpatialBlend as in Audio Sources
/// </summary>
public float SpatialBlend
{
get { return audioParameters.SpatialBlend; }
set
{
for (int i = 0; i < audioSources.Count; i++)
{
audioSources[i].AudioSource.spatialBlend = value;
}
audioParameters.SpatialBlend = value;
}
}
/// <summary>
/// Set the audio mixer, does not affect children
/// </summary>
public AudioMixerGroup AudioMixer
{
get { return audioParameters.AudioMixer; }
set
{
for (int i = 0; i < audioSources.Count; i++)
{
audioSources[i].AudioSource.outputAudioMixerGroup = value;
}
audioParameters.AudioMixer = value;
}
}
/// <summary>
/// 3D Spread as in Audio Sources
/// </summary>
public float Spread
{
get { return _spread; }
set
{
for (int i = 0; i < audioSources.Count; i++)
{
audioSources[i].AudioSource.spread = value;
}
_spread = value;
}
}
/// <summary>
/// 2D Pan as in Audio Sources
/// </summary>
public float PanStereo
{
get { return audioParameters.StereoPan; }
set
{
for (int i = 0; i < audioSources.Count; i++)
{
audioSources[i].AudioSource.panStereo = value;
}
audioParameters.StereoPan = value;
}
}
/// <summary>
/// Stop the current playing sound
/// </summary>
public void Stop()
{
//Use a non zero amount to avoid any issues with sound glitching
StartCoroutine(StopAndMute(0.08f, LeanTweenType.notUsed));
}
/// <summary>
/// Stop with fade out
/// </summary>
/// <param name="fadeOutTime"></param>
public void Stop(float fadeOutTime, LeanTweenType tweenType = LeanTweenType.easeInOutQuad)
{
StartCoroutine(StopAndMute(fadeOutTime, tweenType));
}
/// <summary>
/// Set audiosource values from parameters. Note that Pitch is first applied on the next audioclip (looping).
/// </summary>
/// <param name="parameters"></param>
public void SetFromAudioParameters(AudioParameters parameters)
{
audioParameters.CopyFrom(parameters);
for (int i = 0; i < audioSources.Count; i++)
{
audioSources[i].AudioSource.spatialBlend = parameters.SpatialBlend;
audioSources[i].AudioSource.panStereo = parameters.StereoPan;
SetVolume(audioSources[i], parameters.Volume);
if (parameters.SetMixer)
{
audioSources[i].AudioSource.outputAudioMixerGroup = parameters.AudioMixer;
}
}
}
#region Internal
/// <summary>
/// Internal InAudio play method. Please use InAudio.Play(...) to play audio
/// </summary>
public void _internalPlay(InAudioNode node, GameObject controllingObject, RuntimeInfo playingInfo, float fade, LeanTweenType fadeType, AudioParameters parameters)
{
if (node.IsRootOrFolder)
{
Debug.LogWarning("InAudio: Cannot play Folder node \"" + node.Name + "\"");
return;
}
if (audioParameters == null)
{
audioParameters = new AudioParameters();
}
if (parameters != null)
{
audioParameters.CopyFrom(parameters);
}
else
{
audioParameters.Reset();
}
dspPool = InAudioInstanceFinder.DSPTimePool;
breakLoop = false;
controlling = controllingObject;
ParentBeforeFolder = TreeWalker.FindParentBeforeFolder(node);
ParentFolder = ParentBeforeFolder._parent._nodeData as InFolderData;
folderVolume = 1.0f;
if (ParentFolder != null)
{
folderVolume = ParentFolder.runtimeVolume;
ParentFolder.runtimePlayers.Add(this);
}
//This is to queue the next playing node, as the first clip will not yield a waitforseconds
//firstClip = true;
runtimeInfo = playingInfo;
PlayingNode = node;
DSPTime time = dspPool.GetObject();
time.CurrentEndTime = AudioSettings.dspTime;
isActive = true;
fadeVolume = 1f;
_spread = 0.0f;
if (fade > 0)
{
LTDescr tweever = LeanTween.value(controllingObject, f =>
{
fadeVolume = f;
SetFadeVolume(f);
}, 0f, 1f, fade);
tweever.tweenType = fadeType;
fadeVolume = 0;
SetFadeVolume(0);
}
StartCoroutine(StartPlay(node, time));
}
public void _internalPlayFollowing(InAudioNode node, GameObject controllingObject, RuntimeInfo playingInfo, float fade, LeanTweenType fadeType, AudioParameters parameters)
{
this.toFollow = controllingObject.transform;
internalUpdate();
_internalPlay(node, controllingObject, playingInfo, fade, fadeType, parameters);
}
/// <summary>
/// Private InAudio initialization.
/// </summary>
/// <param name="cleanup"></param>
public void internalInitialize(Action<ObjectAudioList> cleanup)
{
this.cleanup = cleanup;
}
public void internalSetFolderVolume(float volume)
{
folderVolume = volume;
for (int i = 0; i < audioSources.Count; i++)
{
if (audioSources == null)
continue;
var source = audioSources[i];
SetVolume(source, audioParameters.Volume);
}
}
public void internalUpdate()
{
if (toFollow != null)
{
transform.localPosition = new Vector3();
transform.localPosition = -transform.position + toFollow.position;
transform.localRotation = toFollow.rotation;
}
}
public void internalUpdateFalloff(Vector3 listenerPos)
{
if (audioSources == null)
return;
Vector3 pos = transform.position;
float distance = Vector3.Distance(pos, listenerPos);
for (int i = 0; i < audioSources.Count; i++)
{
var player = audioSources[i];
if (player != null && player.UsedNode != null)
{
CalcRolloff(player, distance);
}
}
}
private void CalcRolloff(InRuntimePlayer player, float distance)
{
var usedNode = GetRolloffNode(player.UsedNode);
var data = usedNode._nodeData as InAudioNodeData;
if (data != null)
{
player.Rolloff = 1f;
if (data.RolloffMode == AudioRolloffMode.Custom)
{
player.Rolloff = data.FalloffCurve.Evaluate(Mathf.Clamp01(distance/data.MaxDistance));
}
SetVolume(player, audioParameters.Volume);
//player.AudioSource.SetLoudness(player.OriginalVolume * attachedToBus.RuntimeSelfVolume * volume * player.Rolloff);
}
}
private InAudioNode GetRolloffNode(InAudioNode current)
{
var data = current._nodeData as InAudioNodeData;
if (data.OverrideAttenuation || current._parent.IsRootOrFolder)
return current;
else
{
return GetRolloffNode(current._parent);
}
}
public void internalDateUpdate(InAudioNode node)
{
if (audioSources == null)
return;
var data = node._nodeData as InAudioNodeData;
if (data == null)
return;
for (int i = 0; i < audioSources.Count; i++)
{
var player = audioSources[i];
if (player != null && player.UsedNode == node)
{
var audioSource = player.AudioSource;
audioSource.rolloffMode = data.RolloffMode;
audioSource.minDistance = data.MinDistance;
audioSource.maxDistance = data.MaxDistance;
}
}
}
private float SetVolume(InRuntimePlayer source, float volume)
{
float vol = source.OriginalVolume * volume * source.Rolloff * fadeVolume * folderVolume;
return source.AudioSource.SetLoudness(vol);
}
private void SetFadeVolume(float newFadeVolume)
{
for (int i = 0; i < audioSources.Count; i++)
{
if (audioSources == null)
continue;
var source = audioSources[i];
float vol = source.OriginalVolume*newFadeVolume*folderVolume;
source.AudioSource.SetLoudness(vol);
}
}
private void StopFast()
{
Cleanup();
StopAllCoroutines();
}
private IEnumerator StopAndMute(float fadeOutTime, LeanTweenType tweenType)
{
if (fadeOutTime < 0.1f)
{
float volume = 1.0f;
while (volume > 0.01)
{
volume -= 13.0f*Time.deltaTime;
for (int i = 0; i < audioSources.Count; ++i)
{
var source = audioSources[i];
if (audioSources[i] == null)
continue;
source.AudioSource.volume = volume;
}
yield return null;
}
FinalCleanup();
}
else
{
var tween = LeanTween.value(gameObject, (f, o) => (o as InPlayer).Volume = f, audioParameters.Volume*fadeVolume, 0.0f, fadeOutTime);
tween.onUpdateParam = this;
tween.tweenType = tweenType;
tween.onComplete = FinalCleanup;
}
}
private void FinalCleanup()
{
for (int i = 0; i < audioSources.Count; ++i)
{
var source = audioSources[i];
if (audioSources[i] == null)
continue;
source.AudioSource.Stop();
}
Cleanup();
StopAllCoroutines();
}
private float fadeVolume = 1.0f;
private float _spread;
private float folderVolume = 1.0f;
private GameObject controlling;
private InAudioNode PlayingNode;
private InAudioNode ParentBeforeFolder; //The nearest folder or root
private InFolderData ParentFolder; //The nearest folder or root
private readonly List<InRuntimePlayer> audioSources = new List<InRuntimePlayer>(1);
private InDSPTimePool dspPool;
//Set from InAudioEventWorker
private Action<ObjectAudioList> cleanup;
//private bool firstClip;
private Transform toFollow;
private bool isActive;
private RuntimeInfo runtimeInfo;
private bool breakLoop;
private int currentIndex;
private AudioParameters audioParameters = new AudioParameters();
public ReadOnlyCollection<InRuntimePlayer> PlayingSources
{
get { return new ReadOnlyCollection<InRuntimePlayer>(audioSources); }
}
private InRuntimePlayer Current
{
get { return audioSources[currentIndex]; }
}
private bool firstPlay = true;
private IEnumerator StartPlay(InAudioNode current, DSPTime endTime)
{
yield return StartCoroutine(NextNode(current, endTime, 0));
yield return new WaitForSeconds((float) (endTime.CurrentEndTime - AudioSettings.dspTime));
endTime.Player = null;
dspPool.ReleaseObject(endTime);
StopFast();
}
private IEnumerator NextNode(InAudioNode current, DSPTime endTime, float sampleOffset)
{
byte loops = 0;
var nodeData = current._nodeData as InAudioNodeData;
bool loopInfinite = nodeData.LoopInfinite;
if (!loopInfinite)
loops = RuntimeHelper.GetLoops(current);
endTime.CurrentEndTime += RuntimeHelper.InitialDelay(nodeData);
if (nodeData.Loop == false)
{
loops = 0;
loopInfinite = false;
}
for (int i = 0; i < 1 + loops || loopInfinite; ++i) //For at least once
{
if (current._type == AudioNodeType.Audio)
{
NextFreeAudioSource();
var audioData = current._nodeData as InAudioData;
float preOffset = sampleOffset + RuntimeHelper.Offset(nodeData);
if (preOffset > 0)
{
if (audioData.AudioClip != null)
{
int sampleCount = audioData.AudioClip.samples;
if (sampleOffset < sampleCount)
{
PlayNode(current, endTime, preOffset, audioData);
if (!firstPlay)
yield return
new WaitForSeconds((float) (endTime.CurrentEndTime - AudioSettings.dspTime) -
0.5f);
else
{
yield return
new WaitForSeconds((float) (endTime.CurrentEndTime - AudioSettings.dspTime)/2f);
}
firstPlay = false;
}
}
else
{
Debug.LogWarning("InAudio: Audio clip missing on audio node \"" + current.Name + "\", id=" + current._ID);
}
}
else
{
PlayNode(current, endTime, preOffset, audioData);
if (!firstPlay)
{
yield return new WaitForSeconds((float) (endTime.CurrentEndTime - AudioSettings.dspTime) - 0.5f);
}
else
{
yield return new WaitForSeconds((float) (endTime.CurrentEndTime - AudioSettings.dspTime)/2f);
}
firstPlay = false;
}
}
else if (current._type == AudioNodeType.Random)
{
sampleOffset += RuntimeHelper.Offset(nodeData);
var randomData = nodeData as RandomData;
if (current._children.Count != randomData.weights.Count)
{
Debug.LogWarning("InAudio: There is a problem with the random weights in the node \"" +
current.Name + "\", id=" + current._ID +
". \nPlease open the audio window for the node and follow instructions");
}
if (current._children.Count > 0)
{
int next = RuntimeHelper.SelectRandom(randomData);
if (next != -1)
{
yield return StartCoroutine(NextNode(current._children[next], endTime, sampleOffset));
}
else
{
Debug.LogWarning("InAudio: Cannot pick random as node \"" +
current.Name + "\", id=" + current._ID +
" has no children.\n");
}
}
}
else if (current._type == AudioNodeType.Sequence)
{
sampleOffset += RuntimeHelper.Offset(nodeData);
for (int j = 0; j < current._children.Count; ++j)
{
yield return StartCoroutine(NextNode(current._children[j], endTime, sampleOffset));
}
}
else if (current._type == AudioNodeType.Multi)
{
sampleOffset += RuntimeHelper.Offset(nodeData);
int childrenCount = current._children.Count;
Coroutine[] toStart = InAudioInstanceFinder.CoroutinePool.GetArray(childrenCount);
DSPTime[] childTimes = InAudioInstanceFinder.DSPArrayPool.GetArray(childrenCount);
for (int j = 0; j < childrenCount; ++j)
{
DSPTime dspTime = dspPool.GetObject();
dspTime.CurrentEndTime = endTime.CurrentEndTime;
childTimes[j] = dspTime;
}
for (int j = 0; j < childrenCount; ++j)
{
toStart[j] = StartCoroutine(NextNode(current._children[j], childTimes[j], sampleOffset));
}
for (int j = 0; j < childrenCount; j++)
{
yield return toStart[j];
}
for (int j = 0; j < childrenCount; ++j)
{
DSPTime dspTime = childTimes[j];
if (endTime.CurrentEndTime < dspTime.CurrentEndTime)
endTime.CurrentEndTime = dspTime.CurrentEndTime;
else
dspPool.ReleaseObject(dspTime);
}
InAudioInstanceFinder.CoroutinePool.Release(toStart);
InAudioInstanceFinder.DSPArrayPool.Release(childTimes);
}
if (breakLoop && (loops > 0 || loopInfinite))
{
breakLoop = false;
loops = 0;
loopInfinite = false;
}
}
}
private void PlayNode(InAudioNode current, DSPTime endTime, float offset, InAudioData audioData)
{
float nodeVolume;
double playTime = endTime.CurrentEndTime;
double timeLeft = 0;
if (endTime.Player != null && endTime.Player.clip != null)
{
int samples = endTime.Player.timeSamples;
if (samples > 0 && samples < endTime.Player.clip.samples)
{
timeLeft = TimeLeftOfClip(endTime, samples)/endTime.Player.pitch;
double dspTime = AudioSettings.dspTime;
playTime = dspTime + timeLeft;
}
}
float length = PlayScheduled(ParentBeforeFolder, current, audioData, playTime,
offset, out nodeVolume);
endTime.CurrentEndTime += length;
endTime.Player = Current.AudioSource;
}
private static double TimeLeftOfClip(DSPTime endTime, int samples)
{
return endTime.Player.clip.ExactLength() - (samples/(double) endTime.Player.clip.frequency);
}
private float PlayScheduled(InAudioNode startNode, InAudioNode currentNode, InAudioData audioData,
double playAtDSPTime, float offset, out float nodeVolume)
{
float length = 0;
nodeVolume = 1;
if (audioData.AudioClip != null)
{
var clip = audioData.AudioClip;
length = clip.ExactLength();
length -= offset;
float lengthOffset = offset*clip.frequency;
var source = Current.AudioSource;
source.clip = clip;
nodeVolume = RuntimeHelper.CalcVolume(startNode, currentNode);
Current.OriginalVolume = nodeVolume;
SetVolume(Current, audioParameters.Volume);
source.spatialBlend = RuntimeHelper.CalcBlend(startNode, currentNode);
source.pitch = RuntimeHelper.CalcPitch(startNode, currentNode) * audioParameters.Pitch;
source.rolloffMode = RuntimeHelper.CalcAttentutation(startNode, currentNode, source);
if (audioParameters.SetMixer)
{
source.outputAudioMixerGroup = audioParameters.AudioMixer;
}
else
{
source.outputAudioMixerGroup = currentNode.GetMixerGroup();
}
length = RuntimeHelper.LengthFromPitch(length, source.pitch);
Current.EndTime = playAtDSPTime + length;
Current.StartTime = playAtDSPTime;
Current.UsedNode = currentNode;
source.panStereo += audioParameters.StereoPan;
source.spread = _spread;
source.spatialBlend *= audioParameters.SpatialBlend;
source.timeSamples = (int) (lengthOffset);
source.PlayScheduled(playAtDSPTime);
}
else
{
Debug.LogWarning("InAudio: Audio clip missing on audio node \"" + currentNode.Name + "\", id=" + currentNode._ID);
}
return length;
}
private void NextFreeAudioSource()
{
double dspTime = AudioSettings.dspTime;
for (int i = 0; i < audioSources.Count; ++i)
{
if (audioSources[i].EndTime < dspTime)
{
currentIndex = i;
return;
}
}
var audioObject = InAudioInstanceFinder.InRuntimePlayerPool.GetObject();
var objectTransform = audioObject.transform;
objectTransform.parent = transform;
objectTransform.localPosition = new Vector3();
audioSources.Add(audioObject);
currentIndex = audioSources.Count - 1;
}
private void OnDisable()
{
if (isActive)
Cleanup();
}
private void OnDestroy()
{
Cleanup();
if (cleanup != null && runtimeInfo != null)
cleanup(runtimeInfo.PlacedIn);
}
private void Cleanup()
{
if(ParentFolder != null && ParentFolder.runtimePlayers != null)
{
ParentFolder.runtimePlayers.Remove(this);
}
if (OnCompleted != null)
{
OnCompleted(controlling, NodePlaying);
}
isActive = false;
if (PlayingNode != null && PlayingNode.CurrentInstances != null)
{
var instances = PlayingNode.CurrentInstances;
for (int i = 0; i < instances.Count; i++)
{
if (instances[i].Player == this)
{
instances.RemoveAt(i);
break;
}
}
}
for (int i = 0; i < audioSources.Count; i++)
{
audioSources[i].AudioSource.clip = null;
}
if (InAudioInstanceFinder.Instance != null)
{
var pool = InAudioInstanceFinder.InRuntimePlayerPool;
for (int i = audioSources.Count - 1; i >= 0; i--)
{
pool.QueueRelease(audioSources[i]);
}
audioSources.Clear();
}
var controllerPool = InAudioInstanceFinder.RuntimePlayerControllerPool;
if (controllerPool != null)
controllerPool.QueueRelease(this);
RuntimeHelper.ReleaseRuntimeInfo(runtimeInfo);
OnCompleted = null;
}
}
#endregion //Internal
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftLeftLogicalInt641()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalInt641();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogicalInt641
{
private struct TestStruct
{
public Vector128<Int64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalInt641 testClass)
{
var result = Sse2.ShiftLeftLogical(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector128<Int64> _clsVar;
private Vector128<Int64> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalInt641()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalInt641()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftLeftLogical(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShiftLeftLogical(
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftLeftLogical(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftLeftLogical(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalInt641();
var result = Sse2.ShiftLeftLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftLeftLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftLeftLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((long)(firstOp[0] << 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((long)(firstOp[i] << 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical)}<Int64>(Vector128<Int64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="OrderDetail.Designer.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary></summary>
// <remarks>Generated file.</remarks>
//-----------------------------------------------------------------------
using System;
using System.Data;
using Csla;
using Csla.Data;
using Csla.Rules.CommonRules;
using System.ComponentModel.DataAnnotations;
using ActionExtenderSample.DataAccess;
namespace ActionExtenderSample.Business
{
/// <summary>
/// OrderDetail (editable child object).<br/>
/// This is a generated base class of <see cref="OrderDetail"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="OrderDetailCollection"/> collection.
/// </remarks>
[Serializable]
public partial class OrderDetail : BusinessBase<OrderDetail>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="OrderDetailID"/> property.
/// </summary>
public static readonly PropertyInfo<Guid> OrderDetailIDProperty = RegisterProperty<Guid>(p => p.OrderDetailID, "Order Detail ID");
/// <summary>
/// Gets or sets the Order Detail ID.
/// </summary>
/// <value>The Order Detail ID.</value>
public Guid OrderDetailID
{
get { return GetProperty(OrderDetailIDProperty); }
private set { SetProperty(OrderDetailIDProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ProductID"/> property.
/// </summary>
public static readonly PropertyInfo<Guid> ProductIDProperty = RegisterProperty<Guid>(p => p.ProductID, "Product ID");
/// <summary>
/// Gets or sets the Product ID.
/// </summary>
/// <value>The Product ID.</value>
[Required]
public Guid ProductID
{
get { return GetProperty(ProductIDProperty); }
set { SetProperty(ProductIDProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="PurchaseUnitPrice"/> property.
/// </summary>
public static readonly PropertyInfo<Decimal> PurchaseUnitPriceProperty = RegisterProperty<Decimal>(p => p.PurchaseUnitPrice, "Purchase Unit Price");
/// <summary>
/// Gets or sets the Purchase Unit Price.
/// </summary>
/// <value>The Purchase Unit Price.</value>
[Required]
public Decimal PurchaseUnitPrice
{
get { return GetProperty(PurchaseUnitPriceProperty); }
set { SetProperty(PurchaseUnitPriceProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Quantity"/> property.
/// </summary>
public static readonly PropertyInfo<int> QuantityProperty = RegisterProperty<int>(p => p.Quantity, "Quantity");
/// <summary>
/// Gets or sets the Quantity.
/// </summary>
/// <value>The Quantity.</value>
[Required]
public int Quantity
{
get { return GetProperty(QuantityProperty); }
set { SetProperty(QuantityProperty, value); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="OrderDetail"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private OrderDetail()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Business Rules and Property Authorization
/// <summary>
/// Override this method in your business class to be notified when you need to set up shared business rules.
/// </summary>
/// <remarks>
/// This method is automatically called by CSLA.NET when your object should associate
/// per-type validation rules with its properties.
/// </remarks>
protected override void AddBusinessRules()
{
base.AddBusinessRules();
// Property Business Rules
// Quantity
BusinessRules.AddRule(new MinValue<int>(QuantityProperty, 1));
AddBusinessRulesExtend();
}
/// <summary>
/// Allows the set up of custom shared business rules.
/// </summary>
partial void AddBusinessRulesExtend();
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="OrderDetail"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(OrderDetailIDProperty, Guid.NewGuid());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="OrderDetail"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Child_Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(OrderDetailIDProperty, dr.GetGuid("OrderDetailID"));
LoadProperty(ProductIDProperty, dr.GetGuid("ProductID"));
LoadProperty(PurchaseUnitPriceProperty, dr.GetDecimal("PurchaseUnitPrice"));
LoadProperty(QuantityProperty, dr.GetInt32("Quantity"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Inserts a new <see cref="OrderDetail"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(Order parent)
{
using (var dalManager = DalFactoryActionExtenderSample.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IOrderDetailDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.OrderID,
OrderDetailID,
ProductID,
PurchaseUnitPrice,
Quantity
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="OrderDetail"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
using (var dalManager = DalFactoryActionExtenderSample.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IOrderDetailDal>();
using (BypassPropertyChecks)
{
dal.Update(
OrderDetailID,
ProductID,
PurchaseUnitPrice,
Quantity
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="OrderDetail"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactoryActionExtenderSample.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IOrderDetailDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(OrderDetailIDProperty));
}
OnDeletePost(args);
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Xml;
using Google.GData.Client;
namespace Google.GData.GoogleBase {
///////////////////////////////////////////////////////////////////////
/// <summary>Read-only base class for numbers with units.</summary>
///////////////////////////////////////////////////////////////////////
public abstract class NumberUnit
{
/// <summary>unit name</summary>
protected readonly string unit;
///////////////////////////////////////////////////////////////////////
/// <summary>Creates a NumberUnit object, leaving the responsability
/// of deciding what the number is to subclasses.</summary>
/// <param name="unit">unit name</param>
///////////////////////////////////////////////////////////////////////
protected NumberUnit(string unit)
{
this.unit = unit;
}
/// <summary>The number as a float value.</summary>
abstract protected float asFloat();
/// <summary>The number as an integer value.</summary>
abstract protected int asInt();
///////////////////////////////////////////////////////////////////////
/// <summary>The unit</summary>
///////////////////////////////////////////////////////////////////////
[CLSCompliant(false)]
public string Unit
{
get
{
return unit;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>The value, as an integer. if the number is a float,
/// the value will be rounded.</summary>
///////////////////////////////////////////////////////////////////////
public int IntValue
{
get
{
return asInt();
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>The value, as a float.</summary>
///////////////////////////////////////////////////////////////////////
public float FloatValue
{
get
{
return asFloat();
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Returns the unit portion of a string, everything
/// following the first space.</summary>
///////////////////////////////////////////////////////////////////////
protected static string ExtractUnit(string str)
{
return str.Substring(FindSpace(str) + 1);
}
///////////////////////////////////////////////////////////////////////
/// <summary>Returns the number portion of a string, everything
/// preceding the first space.</summary>
///////////////////////////////////////////////////////////////////////
protected static string ExtractNumber(string str)
{
return str.Substring(0, FindSpace(str));
}
private static int FindSpace(string str)
{
int space = str.IndexOf(' ');
if (space == -1)
{
throw new FormatException("'" + str + "' lacks a unit");
}
return space;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>A float with a unit.</summary>
///////////////////////////////////////////////////////////////////////
public class FloatUnit : NumberUnit
{
private readonly float number;
///////////////////////////////////////////////////////////////////////
/// <summary>Creates a FloatUnit.</summary>
/// <param name="number">the value</param>
/// <param name="unit">the unit</param>
///////////////////////////////////////////////////////////////////////
public FloatUnit(float number, String unit)
: base(unit)
{
this.number = number;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Copy constructor.</summary>
///////////////////////////////////////////////////////////////////////
public FloatUnit(NumberUnit orig)
: base(orig.Unit)
{
this.number = orig.FloatValue;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Extracts the number and unit from a string
/// of the form: <c>number " " unit</c></summary>
/// <exception cref="FormatException">Thrown when the string
/// representation could not be used to generate a valid
/// FloatUnit.</exception>
///////////////////////////////////////////////////////////////////////
public FloatUnit(String str)
: base(ExtractUnit(str))
{
this.number = NumberFormat.ToFloat(ExtractNumber(str));
}
///////////////////////////////////////////////////////////////////////
/// <summary>Returns a string representation for the FloatUnit that
/// can be used to re-created another FloatUnit.</summary>
///////////////////////////////////////////////////////////////////////
public override string ToString()
{
return NumberFormat.ToString(number) + " " + Unit;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Returns the value, as a float.</summary>
///////////////////////////////////////////////////////////////////////
protected override float asFloat()
{
return number;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Returns the value, after converting it to an integer.
/// </summary>
///////////////////////////////////////////////////////////////////////
protected override int asInt()
{
return (int)number;
}
/// <summary>The value, as a float.</summary>
public float Value {
get
{
return number;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Two FloatUnit are equal if both their value and their
/// units are equal. No unit conversion is ever done.</summary>
///////////////////////////////////////////////////////////////////////
public override bool Equals(object o)
{
if (Object.ReferenceEquals(this, o))
{
return true;
}
if (!(o is FloatUnit))
{
return false;
}
FloatUnit other = o as FloatUnit;
return other.number == number && other.unit == unit;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Generates a hash code for this element that is
/// consistent with its Equals() method.</summary>
///////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return 49 * (19 + ((int)number)) + unit.GetHashCode();
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>An integer with a unit.</summary>
///////////////////////////////////////////////////////////////////////
public class IntUnit : NumberUnit
{
private readonly int number;
///////////////////////////////////////////////////////////////////////
/// <summary>Creates an IntUnit</summary>
/// <param name="number">value</param>
/// <param name="unit">unit, as a string</param>
///////////////////////////////////////////////////////////////////////
public IntUnit(int number, String unit)
: base(unit)
{
this.number = number;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Copy constructor.</summary>
///////////////////////////////////////////////////////////////////////
public IntUnit(NumberUnit orig)
: base(orig.Unit)
{
this.number = orig.IntValue;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Extracts the number and unit from a string
/// of the form: <c>number " " unit</c></summary>
/// <exception cref="FormatException">Thrown when the string
/// representation could not be used to generate a valid
/// IntUnit.</exception>
///////////////////////////////////////////////////////////////////////
public IntUnit(string str)
: base(ExtractUnit(str))
{
this.number = NumberFormat.ToInt(ExtractNumber(str));
}
///////////////////////////////////////////////////////////////////////
/// <summary>Returns a string representation for the FloatUnit that
/// can be used to re-created another FloatUnit.</summary>
///////////////////////////////////////////////////////////////////////
public override string ToString()
{
return NumberFormat.ToString(number) + " " + Unit;
}
/// <summary>Returns the value as a float.</summary>
protected override float asFloat()
{
return number;
}
/// <summary>Returns the value.</summary>
protected override int asInt()
{
return number;
}
/// <summary>The value, as an integer.</summary>
public int Value {
get
{
return number;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Two IntUnit are equal if both their value and their
/// units are equal. No unit conversion is ever done. An IntUnit
/// is never equal to a FloatUnit, even if they have the same
/// value and unit.</summary>
///////////////////////////////////////////////////////////////////////
public override bool Equals(object o)
{
if (Object.ReferenceEquals(this, o))
{
return true;
}
if (!(o is IntUnit))
{
return false;
}
IntUnit other = o as IntUnit;
return other.number == number && other.unit == unit;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Generates a hash code for this element that is
/// consistent with its Equals() method.</summary>
///////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return 49 * (7 + number) + unit.GetHashCode();
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Test.Common;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[ActiveIssue(20470, TargetFrameworkMonikers.UapAot)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetEventSource is only part of .NET Core.")]
public abstract class DiagnosticsTest : HttpClientTestBase
{
[Fact]
public static void EventSource_ExistsWithCorrectId()
{
Type esType = typeof(HttpClient).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
Assert.NotNull(esType);
Assert.Equal("Microsoft-System-Net-Http", EventSource.GetName(esType));
Assert.Equal(Guid.Parse("bdd9a83e-1929-5482-0d73-2fe5e1c0e16d"), EventSource.GetGuid(esType));
Assert.NotEmpty(EventSource.GenerateManifest(esType, "assemblyPathToIncludeInManifest"));
}
// Diagnostic tests are each invoked in their own process as they enable/disable
// process-wide EventSource-based tracing, and other tests in the same process
// could interfere with the tests, as well as the enabling of tracing interfering
// with those tests.
/// <remarks>
/// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler
/// DiagnosticSources, since the global logging mechanism makes them conflict inherently.
/// </remarks>
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticSourceLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool requestLogged = false;
Guid requestGuid = Guid.Empty;
bool responseLogged = false;
Guid responseGuid = Guid.Empty;
bool exceptionLogged = false;
bool activityLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
requestGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId");
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response");
responseGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId");
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.RanToCompletion, requestStatus);
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
exceptionLogged = true;
}
else if (kvp.Key.StartsWith("System.Net.Http.HttpRequestOut"))
{
activityLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable( s => !s.Contains("HttpRequestOut"));
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
Assert.True(requestLogged, "Request was not logged.");
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout.");
Assert.Equal(requestGuid, responseGuid);
Assert.False(exceptionLogged, "Exception was logged for successful request");
Assert.False(activityLogged, "HttpOutReq was logged while HttpOutReq logging was disabled");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
/// <remarks>
/// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler
/// DiagnosticSources, since the global logging mechanism makes them conflict inherently.
/// </remarks>
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticSourceNoLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool requestLogged = false;
bool responseLogged = false;
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<List<string>> requestLines = server.AcceptConnectionSendResponseAndCloseAsync();
Task<HttpResponseMessage> response = client.GetAsync(url);
await new Task[] { response, requestLines }.WhenAllOrAnyFailed();
AssertNoHeadersAreInjected(requestLines.Result);
response.Result.Dispose();
}).Wait();
}
Assert.False(requestLogged, "Request was logged while logging disabled.");
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while logging disabled.");
WaitForFalse(() => responseLogged, TimeSpan.FromSeconds(1), "Response was logged while logging disabled.");
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while logging disabled.");
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[ActiveIssue(23771, TestPlatforms.AnyUnix)]
[OuterLoop("Uses external server")]
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SendAsync_HttpTracingEnabled_Succeeds(bool useSsl)
{
RemoteInvoke(async (useSocketsHttpHandlerString, useSslString) =>
{
using (var listener = new TestEventListener("Microsoft-System-Net-Http", EventLevel.Verbose))
{
var events = new ConcurrentQueue<EventWrittenEventArgs>();
await listener.RunWithCallbackAsync(events.Enqueue, async () =>
{
// Exercise various code paths to get coverage of tracing
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
// Do a get to a loopback server
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
server.AcceptConnectionSendResponseAndCloseAsync(),
client.GetAsync(url));
});
// Do a post to a remote server
byte[] expectedData = Enumerable.Range(0, 20000).Select(i => unchecked((byte)i)).ToArray();
Uri remoteServer = bool.Parse(useSslString) ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer;
var content = new ByteArrayContent(expectedData);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
});
// We don't validate receiving specific events, but rather that we do at least
// receive some events, and that enabling tracing doesn't cause other failures
// in processing.
Assert.DoesNotContain(events, ev => ev.EventId == 0); // make sure there are no event source error messages
Assert.InRange(events.Count, 1, int.MaxValue);
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), useSsl.ToString()).Dispose();
}
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool exceptionLogged = false;
bool responseLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Faulted, requestStatus);
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception");
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut"));
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1),
"Response with exception was not logged within 1 second timeout.");
Assert.True(exceptionLogged, "Exception was not logged");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[ActiveIssue(23209)]
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticCancelledLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool cancelLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Canceled, status);
Volatile.Write(ref cancelLogged, true);
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut"));
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
CancellationTokenSource tcs = new CancellationTokenSource();
Task request = server.AcceptConnectionAsync(connection =>
{
tcs.Cancel();
return connection.ReadRequestHeaderAndSendResponseAsync();
});
Task response = client.GetAsync(url, tcs.Token);
await Assert.ThrowsAnyAsync<Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request));
}).Wait();
}
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1),
"Cancellation was not logged within 1 second timeout.");
diagnosticListenerObserver.Disable();
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[Fact]
public void SendAsync_ExpectedDiagnosticSourceActivityLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool requestLogged = false;
bool responseLogged = false;
bool activityStartLogged = false;
bool activityStopLogged = false;
bool exceptionLogged = false;
Activity parentActivity = new Activity("parent");
parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString());
parentActivity.AddBaggage("moreBaggage", Guid.NewGuid().ToString());
parentActivity.AddTag("tag", "tag"); //add tag to ensure it is not injected into request
parentActivity.Start();
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true;}
else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
Assert.NotNull(kvp.Value);
Assert.NotNull(Activity.Current);
Assert.Equal(parentActivity, Activity.Current.Parent);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
Assert.NotNull(Activity.Current);
Assert.Equal(parentActivity, Activity.Current.Parent);
Assert.True(Activity.Current.Duration != TimeSpan.Zero);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response");
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.RanToCompletion, requestStatus);
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut"));
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<List<string>> requestLines = server.AcceptConnectionSendResponseAndCloseAsync();
Task<HttpResponseMessage> response = client.GetAsync(url);
await new Task[] { response, requestLines }.WhenAllOrAnyFailed();
AssertHeadersAreInjected(requestLines.Result, parentActivity);
response.Result.Dispose();
}).Wait();
}
Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
Assert.False(requestLogged, "Request was logged when Activity logging was enabled.");
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout.");
Assert.False(exceptionLogged, "Exception was logged for successful request");
Assert.False(responseLogged, "Response was logged when Activity logging was enabled.");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticSourceUrlFilteredActivityLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")){activityStartLogged = true;}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) {activityStopLogged = true;}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable((s, r, _) =>
{
if (s.StartsWith("System.Net.Http.HttpRequestOut"))
{
var request = r as HttpRequestMessage;
if (request != null)
return !request.RequestUri.Equals(Configuration.Http.RemoteEchoServer);
}
return true;
});
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while URL disabled.");
// Poll with a timeout since logging response is not synchronized with returning a response.
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while URL disabled.");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionActivityLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool exceptionLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Faulted, requestStatus);
activityStopLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception");
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
"Response with exception was not logged within 1 second timeout.");
Assert.True(exceptionLogged, "Exception was not logged");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP HTTP stack doesn't support .Proxy property")]
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticSynchronousExceptionActivityLogging()
{
if (IsCurlHandler)
{
// The only way to throw a synchronous exception for CurlHandler through
// DiagnosticHandler is when the Request uri scheme is Https, and the
// backend doesn't support SSL.
return;
}
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool exceptionLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Faulted, requestStatus);
activityStopLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception");
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandlerString))
using (HttpClient client = new HttpClient(handler))
{
// Set a https proxy.
handler.Proxy = new WebProxy($"https://{Guid.NewGuid()}.com", false);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"http://{Guid.NewGuid()}.com");
if (bool.Parse(useSocketsHttpHandlerString))
{
// Forces a synchronous exception for SocketsHttpHandler.
// SocketsHttpHandler only allow http scheme for proxies.
// We cannot use Assert.Throws<Exception>(() => { SendAsync(...); }) to verify the
// synchronous exception here, because DiagnosticsHandler SendAsync() method has async
// modifier, and returns Task. If the call is not awaited, the current test method will continue
// run before the call is completed, thus Assert.Throws() will not capture the exception.
// We need to wait for the Task to complete synchronously, to validate the exception.
Task sendTask = client.SendAsync(request);
Assert.True(sendTask.IsFaulted);
Assert.IsType<NotSupportedException>(sendTask.Exception.InnerException);
}
else
{
// Forces a synchronous exception for WinHttpHandler.
// WinHttpHandler will not allow (proxy != null && !UseCustomProxy).
handler.UseProxy = false;
// We cannot use Assert.Throws<Exception>(() => { SendAsync(...); }) to verify the
// synchronous exception here, because DiagnosticsHandler SendAsync() method has async
// modifier, and returns Task. If the call is not awaited, the current test method will continue
// run before the call is completed, thus Assert.Throws() will not capture the exception.
// We need to wait for the Task to complete synchronously, to validate the exception.
Task sendTask = client.SendAsync(request);
Assert.True(sendTask.IsFaulted);
Assert.IsType<InvalidOperationException>(sendTask.Exception.InnerException);
}
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
"Response with exception was not logged within 1 second timeout.");
Assert.True(exceptionLogged, "Exception was not logged");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticSourceNewAndDeprecatedEventsLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool requestLogged = false;
bool responseLogged = false;
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true;}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityStopLogged = true; }
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
Assert.True(requestLogged, "Request was not logged.");
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout.");
Assert.True(responseLogged, "Response was not logged.");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionOnlyActivityLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool exceptionLogged = false;
bool activityLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception");
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.Exception"));
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => exceptionLogged, TimeSpan.FromSeconds(1),
"Exception was not logged within 1 second timeout.");
Assert.False(activityLogged, "HttpOutReq was logged when logging was disabled");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticStopOnlyActivityLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(Activity.Current);
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.HttpRequestOut"));
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
"HttpRequestOut.Stop was not logged within 1 second timeout.");
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged when start logging was disabled");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[ActiveIssue(23209)]
[OuterLoop("Uses external server")]
[Fact]
public void SendAsync_ExpectedDiagnosticCancelledActivityLogging()
{
RemoteInvoke(useSocketsHttpHandlerString =>
{
bool cancelLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key == "System.Net.Http.HttpRequestOut.Stop")
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Canceled, status);
Volatile.Write(ref cancelLogged, true);
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString))
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
CancellationTokenSource tcs = new CancellationTokenSource();
Task request = server.AcceptConnectionAsync(connection =>
{
tcs.Cancel();
return connection.ReadRequestHeaderAndSendResponseAsync();
});
Task response = client.GetAsync(url, tcs.Token);
await Assert.ThrowsAnyAsync<Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request));
}).Wait();
}
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1),
"Cancellation was not logged within 1 second timeout.");
diagnosticListenerObserver.Disable();
return SuccessExitCode;
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[Fact]
public void SendAsync_NullRequest_ThrowsArgumentNullException()
{
RemoteInvoke(async () =>
{
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(null);
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (MyHandler handler = new MyHandler())
{
// Getting the Task first from the .SendAsync() call also tests
// that the exception comes from the async Task path.
Task t = handler.SendAsync(null);
if (PlatformDetection.IsUap)
{
await Assert.ThrowsAsync<HttpRequestException>(() => t);
}
else
{
await Assert.ThrowsAsync<ArgumentNullException>(() => t);
}
}
}
diagnosticListenerObserver.Disable();
return SuccessExitCode;
}).Dispose();
}
private class MyHandler : HttpClientHandler
{
internal Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
{
return SendAsync(request, CancellationToken.None);
}
}
private static T GetPropertyValueFromAnonymousTypeInstance<T>(object obj, string propertyName)
{
Type t = obj.GetType();
PropertyInfo p = t.GetRuntimeProperty(propertyName);
object propertyValue = p.GetValue(obj);
Assert.NotNull(propertyValue);
Assert.IsAssignableFrom<T>(propertyValue);
return (T)propertyValue;
}
private static void WaitForTrue(Func<bool> p, TimeSpan timeout, string message)
{
// Assert that spin doesn't time out.
Assert.True(SpinWait.SpinUntil(p, timeout), message);
}
private static void WaitForFalse(Func<bool> p, TimeSpan timeout, string message)
{
// Assert that spin times out.
Assert.False(SpinWait.SpinUntil(p, timeout), message);
}
private static void AssertHeadersAreInjected(List<string> requestLines, Activity parent)
{
string requestId = null;
var correlationContext = new List<NameValueHeaderValue>();
foreach (var line in requestLines)
{
if (line.StartsWith("Request-Id"))
{
requestId = line.Substring("Request-Id".Length).Trim(' ', ':');
}
if (line.StartsWith("Correlation-Context"))
{
var corrCtxString = line.Substring("Correlation-Context".Length).Trim(' ', ':');
foreach (var kvp in corrCtxString.Split(','))
{
correlationContext.Add(NameValueHeaderValue.Parse(kvp));
}
}
}
Assert.True(requestId != null, "Request-Id was not injected when instrumentation was enabled");
Assert.True(requestId.StartsWith(parent.Id));
Assert.NotEqual(parent.Id, requestId);
List<KeyValuePair<string, string>> baggage = parent.Baggage.ToList();
Assert.Equal(baggage.Count, correlationContext.Count);
foreach (var kvp in baggage)
{
Assert.Contains(new NameValueHeaderValue(kvp.Key, kvp.Value), correlationContext);
}
}
private static void AssertNoHeadersAreInjected(List<string> requestLines)
{
foreach (var line in requestLines)
{
Assert.False(line.StartsWith("Request-Id"),
"Request-Id header was injected when instrumentation was disabled");
Assert.False(line.StartsWith("Correlation-Context"),
"Correlation-Context header was injected when instrumentation was disabled");
}
}
}
}
| |
/* ====================================================================
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.Util
{
using System;
using System.IO;
/// <summary>
/// Wraps an <see cref="T:System.IO.Stream"/> providing <see cref="T:NPOI.Util.ILittleEndianInput"/><p/>
///
/// This class does not buffer any input, so the stream Read position maintained
/// by this class is consistent with that of the inner stream.
/// </summary>
/// <remarks>
/// @author Josh Micich
/// </remarks>
public class LittleEndianInputStream : ILittleEndianInput
{
Stream in1 = null;
/// <summary>
/// Reads up to <code>byte.length</code> bytes of data from this
/// input stream into an array of bytes. This method blocks until some
/// input is available.
///
/// simulate java FilterInputStream
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
public int Read(byte[] b)
{
return Read(b, 0, b.Length);
}
/// <summary>
/// Reads up to <code>len</code> bytes of data from this input stream
/// into an array of bytes.If<code> len</code> is not zero, the method
/// blocks until some input is available; otherwise, no
/// bytes are read and<code>0</code> is returned.
///
/// simulate java FilterInputStream
/// </summary>
/// <param name="b"></param>
/// <param name="off"></param>
/// <param name="len"></param>
/// <returns></returns>
public int Read(byte[] b, int off, int len)
{
return in1.Read(b, off, len);
}
private int readLimit = -1;
private long markPos = -1;
public void Mark(int readlimit)
{
this.readLimit = readlimit;
this.markPos = in1.Position;
}
public void Reset()
{
in1.Seek(markPos - in1.Position, SeekOrigin.Current);
}
public long Skip(long n)
{
return in1.Seek(n, SeekOrigin.Current);
}
public int Available()
{
return (int)(in1.Length - in1.Position);
}
public LittleEndianInputStream(Stream is1)
{
in1 = is1;
}
public int ReadByte()
{
return (byte)ReadUByte();
}
public int ReadUByte()
{
int ch;
try
{
ch = in1.ReadByte();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
CheckEOF(ch);
return ch;
}
public double ReadDouble()
{
return BitConverter.Int64BitsToDouble(ReadLong());
}
public int ReadInt()
{
int ch1;
int ch2;
int ch3;
int ch4;
try
{
ch1 = in1.ReadByte();
ch2 = in1.ReadByte();
ch3 = in1.ReadByte();
ch4 = in1.ReadByte();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
CheckEOF(ch1 | ch2 | ch3 | ch4);
return (ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0);
}
public long ReadUInt()
{
long retNum = ReadInt();
return retNum & 0x00FFFFFFFFL;
}
public long ReadLong()
{
int b0;
int b1;
int b2;
int b3;
int b4;
int b5;
int b6;
int b7;
try
{
b0 = in1.ReadByte();
b1 = in1.ReadByte();
b2 = in1.ReadByte();
b3 = in1.ReadByte();
b4 = in1.ReadByte();
b5 = in1.ReadByte();
b6 = in1.ReadByte();
b7 = in1.ReadByte();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
CheckEOF(b0 | b1 | b2 | b3 | b4 | b5 | b6 | b7);
return (((long)b7 << 56) +
((long)b6 << 48) +
((long)b5 << 40) +
((long)b4 << 32) +
((long)b3 << 24) +
(b2 << 16) +
(b1 << 8) +
(b0 << 0));
}
public short ReadShort()
{
return (short)ReadUShort();
}
public int ReadUShort()
{
int ch1;
int ch2;
try
{
ch1 = in1.ReadByte();
ch2 = in1.ReadByte();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
CheckEOF(ch1 | ch2);
return (ch2 << 8) + (ch1 << 0);
}
private static void CheckEOF(int value)
{
if (value < 0)
{
throw new RuntimeException("Unexpected end-of-file");
}
}
public void ReadFully(byte[] buf)
{
ReadFully(buf, 0, buf.Length);
}
public void ReadFully(byte[] buf, int off, int len)
{
int max = off + len;
for (int i = off; i < max; i++)
{
byte ch;
try
{
ch = (byte)in1.ReadByte();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
CheckEOF(ch);
buf[i] = ch;
}
}
internal void Close()
{
in1.Close();
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Data;
using System.Windows.Interop;
using System.Windows.Media;
namespace PerMonitorDpi
{
public class PerMonitorDpiHelper : DependencyObject
{
public PerMonitorDpiHelper(Window window)
{
Debug.WriteLine(
string.Format("Process DPI Awareness: {0}", NativeMethods.GetProcessDpiAwareness(IntPtr.Zero)));
this.window = window;
this.systemDpi = window.GetSystemDpi();
this.hwndSource = PresentationSource.FromVisual(window) as HwndSource;
if (this.hwndSource != null)
{
this.currentDpi = this.hwndSource.GetDpi();
this.ChangeDpi(this.currentDpi);
this.hwndSource.AddHook(this.WndProc);
this.window.Closed += (sender, args) => this.hwndSource.RemoveHook(this.WndProc);
}
}
/// <summary>
/// It can be used for <see cref="FrameworkElement.LayoutTransform"/>.
/// </summary>
public Transform DpiScaleTransform
{
get { return (Transform)this.GetValue(DpiScaleTransformProperty); }
set { this.SetValue(DpiScaleTransformProperty, value); }
}
public static readonly DependencyProperty DpiScaleTransformProperty =
DependencyProperty.Register("DpiScaleTransform", typeof(Transform), typeof(PerMonitorDpiHelper), new UIPropertyMetadata(Transform.Identity));
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == (int)NativeMethods.WindowMessage.WM_DPICHANGED)
{
var dpiX = wParam.ToHiWord();
var dpiY = wParam.ToLoWord();
this.ChangeDpi(new Dpi(dpiX, dpiY));
handled = true;
}
return IntPtr.Zero;
}
/// <summary>
/// Bind <see cref="DpiScaleTransform"/> to the specified <see cref="FrameworkElement"/> object's <see cref="FrameworkElement.LayoutTransformProperty"/>.
/// </summary>
/// <param name="element">
/// The element which uses the <see cref="DpiScaleTransform"/> as its <see cref="FrameworkElement.LayoutTransform"/>.
/// If the parameter is <c>null</c>, the method does nothing and return immediately.
/// </param>
public void BindLayoutTransformTo(FrameworkElement element)
{
if (element == null)
return;
element.SetBinding(FrameworkElement.LayoutTransformProperty, new Binding()
{
Source = this,
Path = new PropertyPath(DpiScaleTransformProperty)
});
}
private void ChangeDpi(Dpi dpi)
{
if (!PerMonitorDpiMethods.IsSupported) return;
this.DpiScaleTransform = (dpi == this.systemDpi)
? Transform.Identity
: new ScaleTransform((double)dpi.X / this.systemDpi.X, (double)dpi.Y / this.systemDpi.Y);
this.window.Width = this.window.Width * dpi.X / this.currentDpi.X;
this.window.Height = this.window.Height * dpi.Y / this.currentDpi.Y;
Debug.WriteLine(string.Format("DPI Change: {0} -> {1} (System: {2})",
this.currentDpi, dpi, this.systemDpi));
this.currentDpi = dpi;
}
private Dpi systemDpi;
private Dpi currentDpi;
private readonly Window window;
private readonly HwndSource hwndSource;
}
internal static class PerMonitorDpiMethods
{
public static bool IsSupported
{
get
{
var version = Environment.OSVersion.Version;
return version.Major * 1000 + version.Minor >= 6003; // Windows 8.1: 6.3
}
}
public static Dpi GetSystemDpi(this Visual visual)
{
var source = PresentationSource.FromVisual(visual);
if (source != null && source.CompositionTarget != null)
{
return new Dpi(
(uint)(Dpi.Default.X * source.CompositionTarget.TransformToDevice.M11),
(uint)(Dpi.Default.Y * source.CompositionTarget.TransformToDevice.M22));
}
return Dpi.Default;
}
public static Dpi GetDpi(this HwndSource hwndSource, MonitorDpiType dpiType = MonitorDpiType.Default)
{
if (!IsSupported) return Dpi.Default;
var hMonitor = NativeMethods.MonitorFromWindow(
hwndSource.Handle,
NativeMethods.MonitorDefaultTo.Nearest);
uint dpiX = 1, dpiY = 1;
NativeMethods.GetDpiForMonitor(hMonitor, dpiType, ref dpiX, ref dpiY);
return new Dpi(dpiX, dpiY);
}
}
public struct Dpi
{
public static readonly Dpi Default = new Dpi(96, 96);
public uint X { get; set; }
public uint Y { get; set; }
public Dpi(uint x, uint y)
: this()
{
this.X = x;
this.Y = y;
}
public static bool operator ==(Dpi dpi1, Dpi dpi2)
{
return dpi1.X == dpi2.X && dpi1.Y == dpi2.Y;
}
public static bool operator !=(Dpi dpi1, Dpi dpi2)
{
return !(dpi1 == dpi2);
}
public bool Equals(Dpi other)
{
return this.X == other.X && this.Y == other.Y;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Dpi && Equals((Dpi)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((int)this.X * 397) ^ (int)this.Y;
}
}
public override string ToString()
{
return string.Format("[X={0},Y={1}]", X, Y);
}
}
/// <summary>
/// Identifies dots per inch (dpi) type.
/// </summary>
public enum MonitorDpiType
{
/// <summary>
/// MDT_Effective_DPI
/// <para>Effective DPI that incorporates accessibility overrides and matches what Desktop Window Manage (DWM) uses to scale desktop applications.</para>
/// </summary>
EffectiveDpi = 0,
/// <summary>
/// MDT_Angular_DPI
/// <para>DPI that ensures rendering at a compliant angular resolution on the screen, without incorporating accessibility overrides.</para>
/// </summary>
AngularDpi = 1,
/// <summary>
/// MDT_Raw_DPI
/// <para>Linear DPI of the screen as measures on the screen itself.</para>
/// </summary>
RawDpi = 2,
/// <summary>
/// MDT_Default
/// </summary>
Default = EffectiveDpi,
}
internal static class NativeMethods
{
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromWindow(IntPtr hwnd, MonitorDefaultTo dwFlags);
[DllImport("shcore.dll")]
public static extern void GetDpiForMonitor(IntPtr hmonitor, MonitorDpiType dpiType, ref uint dpiX, ref uint dpiY);
[DllImport("shcore.dll")]
private static extern int GetProcessDpiAwareness(IntPtr handle, ref ProcessDpiAwareness awareness);
public static ProcessDpiAwareness GetProcessDpiAwareness(IntPtr handle)
{
ProcessDpiAwareness pda = ProcessDpiAwareness.Unaware;
if (GetProcessDpiAwareness(handle, ref pda) == 0)
return pda;
return ProcessDpiAwareness.Unaware;
}
public enum MonitorDefaultTo
{
Null = 0,
Primary = 1,
Nearest = 2,
}
public enum WindowMessage
{
WM_DPICHANGED = 0x02E0,
}
public enum ProcessDpiAwareness
{
Unaware = 0,
SystemDpiAware = 1,
PerMonitorDpiAware = 2
}
}
internal static class IntPtrExtensions
{
public static ushort ToLoWord(this IntPtr dword)
{
return (ushort)((uint)dword & 0xffff);
}
public static ushort ToHiWord(this IntPtr dword)
{
return (ushort)((uint)dword >> 16);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO.Pipelines;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Connections.Client.Internal;
using Xunit;
namespace Microsoft.AspNetCore.SignalR.Client.Tests
{
public class ServerSentEventsParserTests
{
[Theory]
[InlineData("\r\n", "")]
[InlineData("\r\n:\r\n", "")]
[InlineData("\r\n:comment\r\n", "")]
[InlineData("data: \r\r\n\r\n", "\r")]
[InlineData(":comment\r\ndata: \r\r\n\r\n", "\r")]
[InlineData("data: A\rB\r\n\r\n", "A\rB")]
[InlineData("data: Hello, World\r\n\r\n", "Hello, World")]
[InlineData("data: Hello, World\r\n\r\ndata: ", "Hello, World")]
[InlineData("data: Hello, World\r\n\r\n:comment\r\ndata: ", "Hello, World")]
[InlineData("data: Hello, World\r\n\r\n:comment", "Hello, World")]
[InlineData("data: Hello, World\r\n\r\n:comment\r\n", "Hello, World")]
[InlineData("data: Hello, World\r\n:comment\r\n\r\n", "Hello, World")]
[InlineData("data: SGVsbG8sIFdvcmxk\r\n\r\n", "SGVsbG8sIFdvcmxk")]
public void ParseSSEMessageSuccessCases(string encodedMessage, string expectedMessage)
{
var buffer = Encoding.UTF8.GetBytes(encodedMessage);
var readableBuffer = new ReadOnlySequence<byte>(buffer);
var parser = new ServerSentEventsMessageParser();
var parseResult = parser.ParseMessage(readableBuffer, out var consumed, out var examined, out var message);
Assert.Equal(ServerSentEventsMessageParser.ParseResult.Completed, parseResult);
Assert.Equal(consumed, examined);
var result = Encoding.UTF8.GetString(message);
Assert.Equal(expectedMessage, result);
}
[Theory]
[InlineData("data: T\n", "Unexpected '\\n' in message. A '\\n' character can only be used as part of the newline sequence '\\r\\n'")]
[InlineData("data: T\r\ndata: Hello, World\r\r\n\n", "There was an error in the frame format")]
[InlineData("data: T\r\ndata: Hello, World\n\n", "Unexpected '\\n' in message. A '\\n' character can only be used as part of the newline sequence '\\r\\n'")]
[InlineData("data: T\r\nfoo: Hello, World\r\n\r\n", "Expected the message prefix 'data: '")]
[InlineData("foo: T\r\ndata: Hello, World\r\n\r\n", "Expected the message prefix 'data: '")]
[InlineData("food: T\r\ndata: Hello, World\r\n\r\n", "Expected the message prefix 'data: '")]
[InlineData("data: T\r\ndata: Hello, World\r\n\n", "There was an error in the frame format")]
[InlineData("data: T\r\ndata: Hello\n, World\r\n\r\n", "Unexpected '\\n' in message. A '\\n' character can only be used as part of the newline sequence '\\r\\n'")]
[InlineData("data: Hello, World\r\n\r\\", "Expected a \\r\\n frame ending")]
[InlineData("data: Major\r\ndata: Key\rndata: Alert\r\n\r\\", "Expected a \\r\\n frame ending")]
[InlineData("data: Major\r\ndata: Key\r\ndata: Alert\r\n\r\\", "Expected a \\r\\n frame ending")]
public void ParseSSEMessageFailureCases(string encodedMessage, string expectedExceptionMessage)
{
var buffer = Encoding.UTF8.GetBytes(encodedMessage);
var readableBuffer = new ReadOnlySequence<byte>(buffer);
var parser = new ServerSentEventsMessageParser();
var ex = Assert.Throws<FormatException>(() => { parser.ParseMessage(readableBuffer, out var consumed, out var examined, out var message); });
Assert.Equal(expectedExceptionMessage, ex.Message);
}
[Theory]
[InlineData("")]
[InlineData(":")]
[InlineData(":comment")]
[InlineData(":comment\r\n")]
[InlineData("data:")]
[InlineData("data: \r")]
[InlineData("data: T\r\nda")]
[InlineData("data: T\r\ndata:")]
[InlineData("data: T\r\ndata: Hello, World")]
[InlineData("data: T\r\ndata: Hello, World\r")]
[InlineData("data: T\r\ndata: Hello, World\r\n")]
[InlineData("data: T\r\ndata: Hello, World\r\n\r")]
[InlineData("data: B\r\ndata: SGVsbG8sIFd")]
[InlineData(":\r\ndata:")]
[InlineData("data: T\r\n:\r\n")]
[InlineData("data: T\r\n:\r\ndata:")]
[InlineData("data: T\r\ndata: Hello, World\r\n:comment")]
public void ParseSSEMessageIncompleteParseResult(string encodedMessage)
{
var buffer = Encoding.UTF8.GetBytes(encodedMessage);
var readableBuffer = new ReadOnlySequence<byte>(buffer);
var parser = new ServerSentEventsMessageParser();
var parseResult = parser.ParseMessage(readableBuffer, out var consumed, out var examined, out var message);
Assert.Equal(ServerSentEventsMessageParser.ParseResult.Incomplete, parseResult);
}
[Theory]
[InlineData(new[] { "d", "ata: Hello, World\r\n\r\n" }, "Hello, World")]
[InlineData(new[] { "da", "ta: Hello, World\r\n\r\n" }, "Hello, World")]
[InlineData(new[] { "dat", "a: Hello, World\r\n\r\n" }, "Hello, World")]
[InlineData(new[] { "data", ": Hello, World\r\n\r\n" }, "Hello, World")]
[InlineData(new[] { "data:", " Hello, World\r\n\r\n" }, "Hello, World")]
[InlineData(new[] { "data: Hello, World", "\r\n\r\n" }, "Hello, World")]
[InlineData(new[] { "data: Hello, World\r\n", "\r\n" }, "Hello, World")]
[InlineData(new[] { "data: ", "Hello, World\r\n\r\n" }, "Hello, World")]
[InlineData(new[] { ":", "comment", "\r\n", "d", "ata: Hello, World\r\n\r\n" }, "Hello, World")]
[InlineData(new[] { ":comment", "\r\n", "data: Hello, World", "\r\n\r\n" }, "Hello, World")]
[InlineData(new[] { "data: Hello, World\r\n", ":comment\r\n", "\r\n" }, "Hello, World")]
public async Task ParseMessageAcrossMultipleReadsSuccess(string[] messageParts, string expectedMessage)
{
var parser = new ServerSentEventsMessageParser();
var pipe = new Pipe();
byte[] message = null;
SequencePosition consumed = default, examined = default;
for (var i = 0; i < messageParts.Length; i++)
{
var messagePart = messageParts[i];
await pipe.Writer.WriteAsync(Encoding.UTF8.GetBytes(messagePart));
var result = await pipe.Reader.ReadAsync();
var parseResult = parser.ParseMessage(result.Buffer, out consumed, out examined, out message);
pipe.Reader.AdvanceTo(consumed, examined);
// parse result should be complete only after we parsed the last message part
var expectedResult =
i == messageParts.Length - 1
? ServerSentEventsMessageParser.ParseResult.Completed
: ServerSentEventsMessageParser.ParseResult.Incomplete;
Assert.Equal(expectedResult, parseResult);
}
Assert.Equal(consumed, examined);
var resultMessage = Encoding.UTF8.GetString(message);
Assert.Equal(expectedMessage, resultMessage);
}
[Theory]
[InlineData("data: T", "\n", "Unexpected '\\n' in message. A '\\n' character can only be used as part of the newline sequence '\\r\\n'")]
[InlineData("data: T\r\n", "data: Hello, World\r\r\n\n", "There was an error in the frame format")]
[InlineData("data: T\r\n", "data: Hello, World\n\n", "Unexpected '\\n' in message. A '\\n' character can only be used as part of the newline sequence '\\r\\n'")]
[InlineData("data: T\r\nf", "oo: Hello, World\r\n\r\n", "Expected the message prefix 'data: '")]
[InlineData("foo", ": T\r\ndata: Hello, World\r\n\r\n", "Expected the message prefix 'data: '")]
[InlineData("food:", " T\r\ndata: Hello, World\r\n\r\n", "Expected the message prefix 'data: '")]
[InlineData("data: T\r\ndata: Hello, W", "orld\r\n\n", "There was an error in the frame format")]
[InlineData("data: T\r\nda", "ta: Hello\n, World\r\n\r\n", "Unexpected '\\n' in message. A '\\n' character can only be used as part of the newline sequence '\\r\\n'")]
[InlineData("data: ", "T\r\ndata: Major\r\ndata: Key\r\ndata: Alert\r\n\r\\", "Expected a \\r\\n frame ending")]
[InlineData("data: B\r\ndata: SGVs", "bG8sIFdvcmxk\r\n\n\n", "There was an error in the frame format")]
public async Task ParseMessageAcrossMultipleReadsFailure(string encodedMessagePart1, string encodedMessagePart2, string expectedMessage)
{
var pipe = new Pipe();
// Read the first part of the message
await pipe.Writer.WriteAsync(Encoding.UTF8.GetBytes(encodedMessagePart1));
var result = await pipe.Reader.ReadAsync();
var parser = new ServerSentEventsMessageParser();
var parseResult = parser.ParseMessage(result.Buffer, out var consumed, out var examined, out var buffer);
Assert.Equal(ServerSentEventsMessageParser.ParseResult.Incomplete, parseResult);
pipe.Reader.AdvanceTo(consumed, examined);
// Send the rest of the data and parse the complete message
await pipe.Writer.WriteAsync(Encoding.UTF8.GetBytes(encodedMessagePart2));
result = await pipe.Reader.ReadAsync();
var ex = Assert.Throws<FormatException>(() => parser.ParseMessage(result.Buffer, out consumed, out examined, out buffer));
Assert.Equal(expectedMessage, ex.Message);
}
[Theory]
[InlineData("data: foo\r\n\r\n", "data: bar\r\n\r\n")]
public async Task ParseMultipleMessagesText(string message1, string message2)
{
var pipe = new Pipe();
// Read the first part of the message
await pipe.Writer.WriteAsync(Encoding.UTF8.GetBytes(message1 + message2));
var result = await pipe.Reader.ReadAsync();
var parser = new ServerSentEventsMessageParser();
var parseResult = parser.ParseMessage(result.Buffer, out var consumed, out var examined, out var message);
Assert.Equal(ServerSentEventsMessageParser.ParseResult.Completed, parseResult);
Assert.Equal("foo", Encoding.UTF8.GetString(message));
Assert.Equal(consumed, result.Buffer.GetPosition(message1.Length));
pipe.Reader.AdvanceTo(consumed, examined);
Assert.Equal(consumed, examined);
parser.Reset();
result = await pipe.Reader.ReadAsync();
parseResult = parser.ParseMessage(result.Buffer, out consumed, out examined, out message);
Assert.Equal(ServerSentEventsMessageParser.ParseResult.Completed, parseResult);
Assert.Equal("bar", Encoding.UTF8.GetString(message));
pipe.Reader.AdvanceTo(consumed, examined);
}
public static IEnumerable<object[]> MultilineMessages
{
get
{
yield return new object[] { "data: Shaolin\r\ndata: Fantastic\r\n\r\n", "Shaolin" + Environment.NewLine + " Fantastic" };
yield return new object[] { "data: The\r\ndata: Get\r\ndata: Down\r\n\r\n", "The" + Environment.NewLine + "Get" + Environment.NewLine + "Down" };
}
}
[Theory]
[MemberData(nameof(MultilineMessages))]
public void ParseMessagesWithMultipleDataLines(string encodedMessage, string expectedMessage)
{
var buffer = Encoding.UTF8.GetBytes(encodedMessage);
var readableBuffer = new ReadOnlySequence<byte>(buffer);
var parser = new ServerSentEventsMessageParser();
var parseResult = parser.ParseMessage(readableBuffer, out var consumed, out var examined, out var message);
Assert.Equal(ServerSentEventsMessageParser.ParseResult.Completed, parseResult);
Assert.Equal(consumed, examined);
var result = Encoding.UTF8.GetString(message);
Assert.Equal(expectedMessage, result);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic.Internal
{
public class List<T>
{
private T[] _items;
private int _size;
private int _version;
public List()
{
_items = Array.Empty<T>();
}
// Constructs a List with a given initial capacity. The list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required.
//
public List(int capacity)
{
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
_items = new T[capacity];
}
// Constructs a List, copying the contents of the given collection. The
// size and capacity of the new list will both be equal to the size of the
// given collection.
//
public List(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{
int count = c.Count;
if (count == 0)
{
_items = Array.Empty<T>();
}
else
{
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
else
{
_size = 0;
_items = Array.Empty<T>();
// This enumerable could be empty. Let Add allocate a new array, if needed.
// Note it will also go to _defaultCapacity first, not 1, then 2, etc.
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Add(en.Current);
}
}
}
}
// Gets and sets the capacity of this list. The capacity is the size of
// the internal array used to hold items. When set, the internal
// array of the list is reallocated to the given capacity.
//
public int Capacity
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _items.Length;
}
set
{
if (value < _size)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
}
Contract.EndContractBlock();
if (value != _items.Length)
{
if (value > 0)
{
var newArray = new T[value];
Array.Copy(_items, 0, newArray, 0, _size);
_items = newArray;
}
else
{
_items = Array.Empty<T>();
}
}
}
}
// Read-only property describing how many elements are in the List.
public int Count
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _size;
}
}
// Sets or Gets the element at the given index.
//
public T this[int index]
{
get
{
// Following trick can reduce the range check by one
if ((uint)index >= (uint)_size)
{
throw new ArgumentOutOfRangeException();
}
Contract.EndContractBlock();
return _items[index];
}
set
{
if ((uint)index >= (uint)_size)
{
throw new ArgumentOutOfRangeException();
}
Contract.EndContractBlock();
_items[index] = value;
_version++;
}
}
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
//
public void Add(T item)
{
if (_size == _items.Length)
{
EnsureCapacity(_size + 1);
}
_items[_size++] = item;
_version++;
}
// Clears the contents of List.
public void Clear()
{
if (_size > 0)
{
Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
}
_version++;
}
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// item.Equals().
//
public bool Contains(T item)
{
if ((Object)item == null)
{
for (int i = 0; i < _size; i++)
if ((Object)_items[i] == null)
return true;
return false;
}
else
{
EqualityComparer<T> c = EqualityComparer<T>.Default;
for (int i = 0; i < _size; i++)
{
if (c.Equals(_items[i], item)) return true;
}
return false;
}
}
public void CopyTo(T[] array)
{
CopyTo(array, 0);
}
// Copies a section of this list to the given array at the given index.
//
// The method uses the Array.Copy method to copy the elements.
//
public void CopyTo(int index, T[] array, int arrayIndex, int count)
{
if (_size - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
Contract.EndContractBlock();
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, index, array, arrayIndex, count);
}
public void CopyTo(T[] array, int arrayIndex)
{
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
// Ensures that the capacity of this list is at least the given minimum
// value. If the currect capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
private void EnsureCapacity(int min)
{
if (_items.Length < min)
{
int newCapacity = _items.Length == 0 ? 4 : _items.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
//if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
if (newCapacity < min)
{
newCapacity = min;
}
Capacity = newCapacity;
}
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards from beginning to end.
// The elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return Array.IndexOf(_items, item, 0, _size);
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and ending at count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index)
{
if (index > _size)
throw new ArgumentOutOfRangeException(nameof(index));
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, _size - index);
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and upto count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index, int count)
{
if (index > _size)
throw new ArgumentOutOfRangeException(nameof(index));
if (count < 0 || index > _size - count)
throw new ArgumentOutOfRangeException(nameof(count));
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, count);
}
// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
//
public void Insert(int index, T item)
{
// Note that insertions at the end are legal.
if ((uint)index > (uint)_size)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
if (_size == _items.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public void RemoveAt(int index)
{
if ((uint)index >= (uint)_size)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
_size--;
if (index < _size)
{
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
public T[] ToArray()
{
Contract.Ensures(Contract.Result<T[]>() != null);
Contract.Ensures(Contract.Result<T[]>().Length == Count);
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
public void TrimExcess()
{
int threshold = _items.Length * 9 / 10;
if (_size < threshold)
{
Capacity = _size;
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=GlyphInfoList.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: ThousandthOfEmRealPoints class
//
// History:
// 1/13/2005: Garyyang Created the file
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Windows;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace MS.Internal.TextFormatting
{
/// <summary>
/// This is a fixed-size implementation of IList<Point>. It is aimed to reduce the double values storage
/// while providing enough precision for glyph run operations. Current usage pattern suggests that there is no
/// need to support resizing functionality (i.e. Add(), Insert(), Remove(), RemoveAt()).
///
/// For each point being stored, it will store the X and Y coordinates of the point into two seperate ThousandthOfEmRealDoubles,
/// which scales double to 16-bit integer if possible.
///
/// </summary>
internal sealed class ThousandthOfEmRealPoints : IList<Point>
{
//----------------------------------
// Constructor
//----------------------------------
internal ThousandthOfEmRealPoints(
double emSize,
int capacity
)
{
Debug.Assert(capacity >= 0);
InitArrays(emSize, capacity);
}
internal ThousandthOfEmRealPoints(
double emSize,
IList<Point> pointValues
)
{
Debug.Assert(pointValues != null);
InitArrays(emSize, pointValues.Count);
// do the setting
for (int i = 0; i < Count; i++)
{
_xArray[i] = pointValues[i].X;
_yArray[i] = pointValues[i].Y;
}
}
//-------------------------------------
// Internal properties
//-------------------------------------
public int Count
{
get
{
return _xArray.Count;
}
}
public bool IsReadOnly
{
get { return false; }
}
public Point this[int index]
{
get
{
// underlying array does boundary check
return new Point(_xArray[index], _yArray[index]);
}
set
{
// underlying array does boundary check
_xArray[index] = value.X;
_yArray[index] = value.Y;
}
}
//------------------------------------
// internal methods
//------------------------------------
public int IndexOf(Point item)
{
// linear search
for (int i = 0; i < Count; i++)
{
if (_xArray[i] == item.X && _yArray[i] == item.Y)
{
return i;
}
}
return -1;
}
public void Clear()
{
_xArray.Clear();
_yArray.Clear();
}
public bool Contains(Point item)
{
return IndexOf(item) >= 0;
}
public void CopyTo(Point[] array, int arrayIndex)
{
// parameter validations
if (array == null)
{
throw new ArgumentNullException("array");
}
if (array.Rank != 1)
{
throw new ArgumentException(
SR.Get(SRID.Collection_CopyTo_ArrayCannotBeMultidimensional),
"array");
}
if (arrayIndex < 0)
{
throw new ArgumentOutOfRangeException("arrayIndex");
}
if (arrayIndex >= array.Length)
{
throw new ArgumentException(
SR.Get(
SRID.Collection_CopyTo_IndexGreaterThanOrEqualToArrayLength,
"arrayIndex",
"array"),
"arrayIndex");
}
if ((array.Length - Count - arrayIndex) < 0)
{
throw new ArgumentException(
SR.Get(
SRID.Collection_CopyTo_NumberOfElementsExceedsArrayLength,
"arrayIndex",
"array"));
}
// do the copying here
for (int i = 0; i < Count; i++)
{
array[arrayIndex + i] = this[i];
}
}
public IEnumerator<Point> GetEnumerator()
{
for (int i = 0; i < Count; i++)
{
yield return this[i];
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable<Point>)this).GetEnumerator();
}
public void Add(Point value)
{
// not supported, same as Point[]
throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize));
}
public void Insert(int index, Point item)
{
// not supported, same as Point[]
throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize));
}
public bool Remove(Point item)
{
// not supported, same as Point[]
throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize));
}
public void RemoveAt(int index)
{
// not supported, same as Point[]
throw new NotSupportedException(SR.Get(SRID.CollectionIsFixedSize));
}
//---------------------------------------------
// Private methods
//---------------------------------------------
private void InitArrays(double emSize, int capacity)
{
_xArray = new ThousandthOfEmRealDoubles(emSize, capacity);
_yArray = new ThousandthOfEmRealDoubles(emSize, capacity);
}
//----------------------------------------
// Private members
//----------------------------------------
private ThousandthOfEmRealDoubles _xArray; // scaled double array for X coordinates
private ThousandthOfEmRealDoubles _yArray; // scaled double array for Y coordinates
}
}
| |
#region Header
/*
* JsonWriter.cs
* Stream-like facility to output JSON text.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace LitJson
{
internal enum Condition
{
InArray,
InObject,
NotAProperty,
Property,
Value
}
internal class WriterContext
{
public int Count;
public bool InArray;
public bool InObject;
public bool ExpectingValue;
public int Padding;
}
public class JsonWriter
{
#region Fields
private static NumberFormatInfo number_format;
private WriterContext context;
private Stack<WriterContext> ctx_stack;
private bool has_reached_end;
private char[] hex_seq;
private int indentation;
private int indent_value;
private StringBuilder inst_string_builder;
private bool pretty_print;
private bool validate;
private TextWriter writer;
#endregion
#region Properties
public int IndentValue {
get { return indent_value; }
set {
indentation = (indentation / indent_value) * value;
indent_value = value;
}
}
public bool PrettyPrint {
get { return pretty_print; }
set { pretty_print = value; }
}
public TextWriter TextWriter {
get { return writer; }
}
public bool Validate {
get { return validate; }
set { validate = value; }
}
#endregion
#region Constructors
static JsonWriter ()
{
number_format = NumberFormatInfo.InvariantInfo;
}
public JsonWriter ()
{
inst_string_builder = new StringBuilder ();
writer = new StringWriter (inst_string_builder);
Init ();
}
public JsonWriter (StringBuilder sb) :
this (new StringWriter (sb))
{
}
public JsonWriter (TextWriter writer)
{
if (writer == null)
throw new ArgumentNullException ("writer");
this.writer = writer;
Init ();
}
#endregion
#region Private Methods
private void DoValidation (Condition cond)
{
if (! context.ExpectingValue)
context.Count++;
if (! validate)
return;
if (has_reached_end)
throw new JsonException (
"A complete JSON symbol has already been written");
switch (cond) {
case Condition.InArray:
if (! context.InArray)
throw new JsonException (
"Can't close an array here");
break;
case Condition.InObject:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't close an object here");
break;
case Condition.NotAProperty:
if (context.InObject && ! context.ExpectingValue)
throw new JsonException (
"Expected a property");
break;
case Condition.Property:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't add a property here");
break;
case Condition.Value:
if (! context.InArray &&
(! context.InObject || ! context.ExpectingValue))
throw new JsonException (
"Can't add a value here");
break;
}
}
private void Init ()
{
has_reached_end = false;
hex_seq = new char[4];
indentation = 0;
indent_value = 4;
pretty_print = false;
validate = true;
ctx_stack = new Stack<WriterContext> ();
context = new WriterContext ();
ctx_stack.Push (context);
}
private static void IntToHex (int n, char[] hex)
{
int num;
for (int i = 0; i < 4; i++) {
num = n % 16;
if (num < 10)
hex[3 - i] = (char) ('0' + num);
else
hex[3 - i] = (char) ('A' + (num - 10));
n >>= 4;
}
}
private void Indent ()
{
if (pretty_print)
indentation += indent_value;
}
private void Put (string str)
{
if (pretty_print && ! context.ExpectingValue)
for (int i = 0; i < indentation; i++)
writer.Write (' ');
writer.Write (str);
}
private void PutNewline ()
{
PutNewline (true);
}
private void PutNewline (bool add_comma)
{
if (add_comma && ! context.ExpectingValue &&
context.Count > 1)
writer.Write (',');
if (pretty_print && ! context.ExpectingValue)
writer.Write ('\n');
}
private void PutString (string str)
{
Put (String.Empty);
writer.Write ('"');
int n = str.Length;
for (int i = 0; i < n; i++) {
switch (str[i]) {
case '\n':
writer.Write ("\\n");
continue;
case '\r':
writer.Write ("\\r");
continue;
case '\t':
writer.Write ("\\t");
continue;
case '"':
case '\\':
writer.Write ('\\');
writer.Write (str[i]);
continue;
case '\f':
writer.Write ("\\f");
continue;
case '\b':
writer.Write ("\\b");
continue;
}
if ((int) str[i] >= 32 && (int) str[i] <= 126) {
writer.Write (str[i]);
continue;
}
// Default, turn into a \uXXXX sequence
IntToHex ((int) str[i], hex_seq);
writer.Write ("\\u");
writer.Write (hex_seq);
}
writer.Write ('"');
}
private void Unindent ()
{
if (pretty_print)
indentation -= indent_value;
}
#endregion
public override string ToString ()
{
if (inst_string_builder == null)
return String.Empty;
return inst_string_builder.ToString ();
}
public void Reset ()
{
has_reached_end = false;
ctx_stack.Clear ();
context = new WriterContext ();
ctx_stack.Push (context);
if (inst_string_builder != null)
inst_string_builder.Remove (0, inst_string_builder.Length);
}
public void Write (bool boolean)
{
DoValidation (Condition.Value);
PutNewline ();
Put (boolean ? "true" : "false");
context.ExpectingValue = false;
}
public void Write (decimal number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (double number)
{
DoValidation (Condition.Value);
PutNewline ();
string str = Convert.ToString (number, number_format);
Put (str);
if (str.IndexOf ('.') == -1 &&
str.IndexOf ('E') == -1 &&
!double.IsNaN(number))
writer.Write (".0");
context.ExpectingValue = false;
}
public void Write (int number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (long number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (string str)
{
DoValidation (Condition.Value);
PutNewline ();
if (str == null)
Put ("null");
else
PutString (str);
context.ExpectingValue = false;
}
public void Write (ulong number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void WriteArrayEnd ()
{
DoValidation (Condition.InArray);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("]");
}
public void WriteArrayStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("[");
context = new WriterContext ();
context.InArray = true;
ctx_stack.Push (context);
Indent ();
}
public void WriteObjectEnd ()
{
DoValidation (Condition.InObject);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("}");
}
public void WriteObjectStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("{");
context = new WriterContext ();
context.InObject = true;
ctx_stack.Push (context);
Indent ();
}
public void WritePropertyName (string property_name)
{
DoValidation (Condition.Property);
PutNewline ();
PutString (property_name);
if (pretty_print) {
if (property_name.Length > context.Padding)
context.Padding = property_name.Length;
for (int i = context.Padding - property_name.Length;
i >= 0; i--)
writer.Write (' ');
writer.Write (": ");
} else
writer.Write (':');
context.ExpectingValue = true;
}
}
}
| |
using System;
using UnityEditor;
using UnityEngine;
using Vexe.Runtime.Extensions;
using Vexe.Runtime.Types;
namespace Vexe.Editor.GUIs
{
public abstract partial class BaseGUI
{
public static readonly float kHeight = EditorGUIUtility.singleLineHeight;
public static readonly float kMiniHeight = kHeight - 3f;
public static readonly float kVSpacing = 1f;
public static readonly float kHSpacing = 3.5f;
public static readonly Rect kDummyRect = new Rect(0, 0, 1, 1);
public static readonly Layout kMultifieldOption = Layout.sHeight(kHeight * 3f);
public static readonly Layout kFoldoutOption = Layout.sWidth(kFoldoutWidth);
public static readonly Layout kDefaultMiniOption = Layout.sWidth(kDefaultMiniWidth).Height(kDefaultMiniHeight);
public const float kIndentAmount = 7.5f;
public const float kNumericLabelWidth = 21f;
public const float kDefaultMiniWidth = 20f;
public const float kDefaultMiniHeight = 16f;
public const float kFoldoutWidth = 10f;
public const MiniButtonStyle kDefaultMiniStyle = MiniButtonStyle.Mid;
public const MiniButtonStyle kDefaultModStyle = MiniButtonStyle.ModMid;
public abstract Rect LastRect { get; }
public ScrollViewBlock ScrollView { get; private set; }
private IndentBlock indentBlock;
private StateBlock stateBlock;
private GUIColorBlock colorBlock;
private ContentColorBlock contentColorBlock;
private LabelWidthBlock labelWidthBlock;
protected EditorRecord prefs;
public BaseGUI()
{
stateBlock = new StateBlock();
colorBlock = new GUIColorBlock();
labelWidthBlock = new LabelWidthBlock();
contentColorBlock = new ContentColorBlock();
indentBlock = new IndentBlock(this);
ScrollView = new ScrollViewBlock(this);
}
public void RequestResetIfRabbit()
{
var rabbit = this as RabbitGUI;
if (rabbit != null)
rabbit.RequestReset();
}
public VerticalBlock Vertical()
{
return Vertical(GUIStyle.none);
}
public VerticalBlock Vertical(GUIStyle style)
{
return BeginVertical(style);
}
public HorizontalBlock Horizontal()
{
return Horizontal(GUIStyle.none);
}
public HorizontalBlock Horizontal(GUIStyle style)
{
return BeginHorizontal(style);
}
protected abstract HorizontalBlock BeginHorizontal(GUIStyle style);
protected abstract VerticalBlock BeginVertical(GUIStyle style);
protected abstract void EndHorizontal();
protected abstract void EndVertical();
public abstract void OnGUI(Action guiCode, Vector4 padding, int targetId);
public virtual void OnEnable() { }
public virtual void OnDisable() { }
public abstract IDisposable If(bool condition, IDisposable body);
public void BeginCheck()
{
EditorGUI.BeginChangeCheck();
}
public bool HasChanged()
{
return EditorGUI.EndChangeCheck();
}
public LabelWidthBlock LabelWidth(float newWidth)
{
return labelWidthBlock.Begin(newWidth);
}
public IndentBlock Indent()
{
return Indent(GUIStyle.none);
}
public IndentBlock Indent(float amount)
{
return Indent(GUIStyle.none, amount);
}
public IndentBlock Indent(GUIStyle style, bool doIndent)
{
return Indent(style, doIndent ? kIndentAmount : 0f);
}
public IndentBlock Indent(GUIStyle style)
{
return Indent(style, kIndentAmount);
}
public IndentBlock Indent(GUIStyle style, float amount)
{
return indentBlock.Begin(style, amount);
}
public StateBlock State(bool newState)
{
return stateBlock.Begin(newState);
}
public bool BeginToggleGroup(string text, bool value)
{
return BeginToggleGroup(text, value, kIndentAmount);
}
public bool BeginToggleGroup(string text, bool value, float indentAmount)
{
value = ToggleLeft(text, value);
State(value);
Indent(indentAmount);
return value;
}
public void EndToggleGroup()
{
indentBlock.Dispose();
stateBlock.Dispose();
}
public GUIColorBlock ColorBlock(Color newColor)
{
return colorBlock.Begin(newColor);
}
public GUIColorBlock ColorBlock(Color? newColor)
{
return newColor.HasValue ? ColorBlock(newColor.Value) : null;
}
public ContentColorBlock ContentColor(Color color)
{
return contentColorBlock.Begin(color);
}
public ContentColorBlock ContentColor(Color? color)
{
return color.HasValue ? ContentColor(color.Value) : null;
}
public void Cursor(Rect rect, MouseCursor mouse)
{
EditorGUIUtility.AddCursorRect(rect, mouse);
}
public void LastCursor(MouseCursor mouse)
{
Cursor(LastRect, mouse);
}
public static BaseGUI Create(Type guiType)
{
return guiType.Instance<BaseGUI>();
}
public static GUIContent GetContent(string text)
{
return GetContent(text, string.Empty);
}
public static float GetHeight(ControlType control)
{
switch (control)
{
case ControlType.MiniButton: return kMiniHeight;
default: return kHeight;
}
}
public static float GetHSpacing(ControlType control)
{
switch (control)
{
case ControlType.MiniButton: return 0f;
default: return kVSpacing;
}
}
public static float GetVSpacing(ControlType controlType)
{
return kVSpacing;
}
public static GUIContent GetContent(string text, string tooltip)
{
// TODO: Pool
return new GUIContent(text, tooltip);
}
public void assert(bool expression, string msg)
{
if (!expression)
throw new Exception(string.Format("Assertion `{0}` failed", msg));
}
public struct ControlData
{
public GUIContent content;
public GUIStyle style;
public Layout option;
public ControlType type;
public ControlData(GUIContent content, GUIStyle style, Layout option, ControlType type)
{
this.content = content;
this.style = style;
this.option = option;
this.type = type;
}
}
public enum ControlType
{
Button,
Label,
PrefixLabel,
TextField,
ObjectField,
IntField,
Float,
Popup,
FlexibleSpace,
HorizontalBlock,
VerticalBlock,
MiniButton,
Vector3Field,
Toggle,
Space,
MaskField,
Slider,
Vector2Field,
HelpBox,
Foldout,
Box,
EnumPopup,
RectField,
Bounds,
TextArea,
ColorField,
CurveField,
GradientField,
TextFieldDropDown,
Double,
Long
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Diagnostics.CodeAnalysis;
using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.Swagger.Properties;
using AutoRest.Swagger.Validation;
using Newtonsoft.Json;
using static AutoRest.Core.Utilities.DependencyInjection;
using AutoRest.Swagger.Validation.Core;
namespace AutoRest.Swagger.Model
{
/// <summary>
/// Describes a single operation determining with this object is mandatory.
/// https://github.com/wordnik/swagger-spec/blob/master/versions/2.0.md#parameterObject
/// </summary>
[Rule(typeof(DefaultMustBeInEnum))]
public abstract class SwaggerObject : SwaggerBase
{
private string _description;
public virtual bool IsRequired { get; set; }
/// <summary>
/// The type of the parameter.
/// </summary>
public virtual DataType? Type { get; set; }
/// <summary>
/// The extending format for the previously mentioned type.
/// </summary>
[Rule(typeof(ValidFormats))]
public virtual string Format { get; set; }
/// <summary>
/// Returns the KnownFormat of the Format string (provided it matches a KnownFormat)
/// Otherwise, returns KnownFormat.none
/// </summary>
public KnownFormat KnownFormat => KnownFormatExtensions.Parse(Format);
/// <summary>
/// Describes the type of items in the array.
/// </summary>
public virtual Schema Items { get; set; }
[JsonProperty(PropertyName = "$ref")]
public string Reference { get; set; }
/// <summary>
/// Describes the type of additional properties in the data type.
/// </summary>
public virtual Schema AdditionalProperties { get; set; }
[Rule(typeof(DescriptiveDescriptionRequired))]
public virtual string Description
{
get { return _description; }
set { _description = value.StripControlCharacters(); }
}
/// <summary>
/// Determines the format of the array if type array is used.
/// </summary>
public virtual CollectionFormat CollectionFormat { get; set; }
/// <summary>
/// Sets a default value to the parameter.
/// </summary>
public virtual string Default { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual string MultipleOf { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual string Maximum { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual bool ExclusiveMaximum { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual string Minimum { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual bool ExclusiveMinimum { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual string MaxLength { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual string MinLength { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual string Pattern { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual string MaxItems { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual string MinItems { get; set; }
[Rule(typeof(InvalidConstraint))]
public virtual bool UniqueItems { get; set; }
public virtual IList<string> Enum { get; set; }
public ObjectBuilder GetBuilder(SwaggerModeler swaggerSpecBuilder)
{
if (this is SwaggerParameter)
{
return new ParameterBuilder(this as SwaggerParameter, swaggerSpecBuilder);
}
if (this is Schema)
{
return new SchemaBuilder(this as Schema, swaggerSpecBuilder);
}
return new ObjectBuilder(this, swaggerSpecBuilder);
}
/// <summary>
/// Returns the PrimaryType that the SwaggerObject maps to, given the Type and the KnownFormat.
///
/// Note: Since a given language still may interpret the value of the Format after this,
/// it is possible the final implemented type may not be the type given here.
///
/// This allows languages to not have a specific PrimaryType decided by the Modeler.
///
/// For example, if the Type is DataType.String, and the KnownFormat is 'char' the C# generator
/// will end up creating a char type in the generated code, but other languages will still
/// use string.
/// </summary>
/// <returns>
/// The PrimaryType that best represents this object.
/// </returns>
public PrimaryType ToType()
{
switch (Type)
{
case DataType.String:
switch (KnownFormat)
{
case KnownFormat.date:
return New<PrimaryType>(KnownPrimaryType.Date);
case KnownFormat.date_time:
return New<PrimaryType>(KnownPrimaryType.DateTime);
case KnownFormat.date_time_rfc1123:
return New<PrimaryType>(KnownPrimaryType.DateTimeRfc1123);
case KnownFormat.@byte:
return New<PrimaryType>(KnownPrimaryType.ByteArray);
case KnownFormat.duration:
return New<PrimaryType>(KnownPrimaryType.TimeSpan);
case KnownFormat.uuid:
return New<PrimaryType>(KnownPrimaryType.Uuid);
case KnownFormat.base64url:
return New<PrimaryType>(KnownPrimaryType.Base64Url);
default:
return New<PrimaryType>(KnownPrimaryType.String);
}
case DataType.Number:
switch (KnownFormat)
{
case KnownFormat.@decimal:
return New<PrimaryType>(KnownPrimaryType.Decimal);
default:
return New<PrimaryType>(KnownPrimaryType.Double);
}
case DataType.Integer:
switch (KnownFormat)
{
case KnownFormat.int64:
return New<PrimaryType>(KnownPrimaryType.Long);
case KnownFormat.unixtime:
return New<PrimaryType>(KnownPrimaryType.UnixTime);
default:
return New<PrimaryType>(KnownPrimaryType.Int);
}
case DataType.Boolean:
return New<PrimaryType>(KnownPrimaryType.Boolean);
case DataType.Object:
case DataType.Array:
case null:
return New<PrimaryType>(KnownPrimaryType.Object);
case DataType.File:
return New<PrimaryType>(KnownPrimaryType.Stream);
default:
throw new NotImplementedException(
string.Format(CultureInfo.InvariantCulture,
Resources.InvalidTypeInSwaggerSchema,
Type));
}
}
/// <summary>
/// Compare a modified document node (this) to a previous one and look for breaking as well as non-breaking changes.
/// </summary>
/// <param name="context">The modified document context.</param>
/// <param name="previous">The original document model.</param>
/// <returns>A list of messages from the comparison.</returns>
public override IEnumerable<ComparisonMessage> Compare(ComparisonContext context, SwaggerBase previous)
{
var prior = previous as SwaggerObject;
if (prior == null)
{
throw new ArgumentNullException("priorVersion");
}
if (context == null)
{
throw new ArgumentNullException("context");
}
base.Compare(context, previous);
if (Reference != null && !Reference.Equals(prior.Reference))
{
context.LogBreakingChange(ComparisonMessages.ReferenceRedirection);
}
if (IsRequired != prior.IsRequired)
{
if (context.Direction != DataDirection.Response)
{
if (IsRequired && !prior.IsRequired)
{
context.LogBreakingChange(ComparisonMessages.RequiredStatusChange);
}
else
{
context.LogInfo(ComparisonMessages.RequiredStatusChange);
}
}
}
// Are the types the same?
if (prior.Type.HasValue != Type.HasValue || (Type.HasValue && prior.Type.Value != Type.Value))
{
context.LogBreakingChange(ComparisonMessages.TypeChanged);
}
// What about the formats?
CompareFormats(context, prior);
CompareItems(context, prior);
if (Default != null && !Default.Equals(prior.Default) || (Default == null && !string.IsNullOrEmpty(prior.Default)))
{
context.LogBreakingChange(ComparisonMessages.DefaultValueChanged);
}
if (Type.HasValue && Type.Value == DataType.Array && prior.CollectionFormat != CollectionFormat)
{
context.LogBreakingChange(ComparisonMessages.ArrayCollectionFormatChanged);
}
CompareConstraints(context, prior);
CompareProperties(context, prior);
CompareEnums(context, prior);
return context.Messages;
}
private void CompareEnums(ComparisonContext context, SwaggerObject prior)
{
if (prior.Enum == null && this.Enum == null) return;
bool relaxes = (prior.Enum != null && this.Enum == null);
bool constrains = (prior.Enum == null && this.Enum != null);
if (!relaxes && !constrains)
{
// 1. Look for removed elements (constraining).
constrains = prior.Enum.Any(str => !this.Enum.Contains(str));
// 2. Look for added elements (relaxing).
relaxes = this.Enum.Any(str => !prior.Enum.Contains(str));
}
if (context.Direction == DataDirection.Request)
{
if (constrains)
{
context.LogBreakingChange(relaxes ? ComparisonMessages.ConstraintChanged : ComparisonMessages.ConstraintIsStronger, "enum");
return;
}
}
else if (context.Direction == DataDirection.Response)
{
if (relaxes)
{
context.LogBreakingChange(constrains ? ComparisonMessages.ConstraintChanged : ComparisonMessages.ConstraintIsWeaker, "enum");
return;
}
}
if (relaxes && constrains)
context.LogInfo(ComparisonMessages.ConstraintChanged, "enum");
else if (relaxes || constrains)
context.LogInfo(relaxes ? ComparisonMessages.ConstraintIsWeaker : ComparisonMessages.ConstraintIsStronger, "enum");
}
private void CompareProperties(ComparisonContext context, SwaggerObject prior)
{
// Additional properties
if (prior.AdditionalProperties == null && AdditionalProperties != null)
{
context.LogBreakingChange(ComparisonMessages.AddedAdditionalProperties);
}
else if (prior.AdditionalProperties != null && AdditionalProperties == null)
{
context.LogBreakingChange(ComparisonMessages.RemovedAdditionalProperties);
}
else if (AdditionalProperties != null)
{
context.PushProperty("additionalProperties");
AdditionalProperties.Compare(context, prior.AdditionalProperties);
context.Pop();
}
}
protected void CompareFormats(ComparisonContext context, SwaggerObject prior)
{
if (prior == null)
{
throw new ArgumentNullException("prior");
}
if (context == null)
{
throw new ArgumentNullException("context");
}
if (prior.Format == null && Format != null ||
prior.Format != null && Format == null ||
prior.Format != null && Format != null && !prior.Format.Equals(Format))
{
context.LogBreakingChange(ComparisonMessages.TypeFormatChanged);
}
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "It may look complex, but it really isn't.")]
protected void CompareConstraints(ComparisonContext context, SwaggerObject prior)
{
if (prior == null)
{
throw new ArgumentNullException("prior");
}
if (context == null)
{
throw new ArgumentNullException("context");
}
if ((prior.MultipleOf == null && MultipleOf != null) ||
(prior.MultipleOf != null && !prior.MultipleOf.Equals(MultipleOf)))
{
context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "multipleOf");
}
if ((prior.Maximum == null && Maximum != null) ||
(prior.Maximum != null && !prior.Maximum.Equals(Maximum)) ||
prior.ExclusiveMaximum != ExclusiveMaximum)
{
// Flag stricter constraints for requests and relaxed constraints for responses.
if (prior.ExclusiveMaximum != ExclusiveMaximum || context.Direction == DataDirection.None)
context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "maximum");
else if (context.Direction == DataDirection.Request && Narrows(prior.Maximum, Maximum, true))
context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "maximum");
else if (context.Direction == DataDirection.Response && Widens(prior.Maximum, Maximum, true))
context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "maximum");
else if (Narrows(prior.Maximum, Maximum, false))
context.LogInfo(ComparisonMessages.ConstraintIsStronger, "maximum");
else if (Widens(prior.Maximum, Maximum, false))
context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "maximum");
}
if ((prior.Minimum == null && Minimum != null) ||
(prior.Minimum != null && !prior.Minimum.Equals(Minimum)) ||
prior.ExclusiveMinimum != ExclusiveMinimum)
{
// Flag stricter constraints for requests and relaxed constraints for responses.
if (prior.ExclusiveMinimum != ExclusiveMinimum || context.Direction == DataDirection.None)
context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "minimum");
else if (context.Direction == DataDirection.Request && Narrows(prior.Minimum, Minimum, true))
context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "minimum");
else if (context.Direction == DataDirection.Response && Widens(prior.Minimum, Minimum, true))
context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "minimum");
else if (Narrows(prior.Minimum, Minimum, false))
context.LogInfo(ComparisonMessages.ConstraintIsStronger, "minimum");
else if (Widens(prior.Minimum, Minimum, false))
context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "minimum");
}
if ((prior.MaxLength == null && MaxLength != null) ||
(prior.MaxLength != null && !prior.MaxLength.Equals(MaxLength)))
{
// Flag stricter constraints for requests and relaxed constraints for responses.
if (context.Direction == DataDirection.None)
context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "maxLength");
else if (context.Direction == DataDirection.Request && Narrows(prior.MaxLength, MaxLength, false))
context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "maxLength");
else if (context.Direction == DataDirection.Response && Widens(prior.MaxLength, MaxLength, false))
context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "maxLength");
else if (Narrows(prior.MaxLength, MaxLength, false))
context.LogInfo(ComparisonMessages.ConstraintIsStronger, "maxLength");
else if (Widens(prior.MaxLength, MaxLength, false))
context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "maxLength");
}
if ((prior.MinLength == null && MinLength != null) ||
(prior.MinLength != null && !prior.MinLength.Equals(MinLength)))
{
// Flag stricter constraints for requests and relaxed constraints for responses.
if (context.Direction == DataDirection.None)
context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "minLength");
else if (context.Direction == DataDirection.Request && Narrows(prior.MinLength, MinLength, true))
context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "minimum");
else if (context.Direction == DataDirection.Response && Widens(prior.MinLength, MinLength, true))
context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "minimum");
else if (Narrows(prior.MinLength, MinLength, false))
context.LogInfo(ComparisonMessages.ConstraintIsStronger, "minLength");
else if (Widens(prior.MinLength, MinLength, false))
context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "minLength");
}
if ((prior.Pattern == null && Pattern != null) ||
(prior.Pattern != null && !prior.Pattern.Equals(Pattern)))
{
context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "pattern");
}
if ((prior.MaxItems == null && MaxItems != null) ||
(prior.MaxItems != null && !prior.MaxItems.Equals(MaxItems)))
{
// Flag stricter constraints for requests and relaxed constraints for responses.
if (context.Direction == DataDirection.None)
context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "maxItems");
else if (context.Direction == DataDirection.Request && Narrows(prior.MaxItems, MaxItems, false))
context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "maxItems");
else if (context.Direction == DataDirection.Response && Widens(prior.MaxItems, MaxItems, false))
context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "maxItems");
else if (Narrows(prior.MaxItems, MaxItems, false))
context.LogInfo(ComparisonMessages.ConstraintIsStronger, "maxItems");
else if (Widens(prior.MaxItems, MaxItems, false))
context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "maxItems");
}
if ((prior.MinItems == null && MinItems != null) ||
(prior.MinItems != null && !prior.MinItems.Equals(MinItems)))
{
// Flag stricter constraints for requests and relaxed constraints for responses.
if (context.Direction == DataDirection.None)
context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "minItems");
else if (context.Direction == DataDirection.Request && Narrows(prior.MinItems, MinItems, true))
context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "minItems");
else if (context.Direction == DataDirection.Response && Widens(prior.MinItems, MinItems, true))
context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "minItems");
else if (Narrows(prior.MinItems, MinItems, true))
context.LogInfo(ComparisonMessages.ConstraintIsStronger, "minItems");
else if (Widens(prior.MinItems, MinItems, true))
context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "minItems");
}
if (prior.UniqueItems != UniqueItems)
{
context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "uniqueItems");
}
}
private bool Narrows(string previous, string current, bool isLowerBound)
{
int p = 0;
int c = 0;
return int.TryParse(previous, out p) &&
int.TryParse(current, out c) &&
(isLowerBound ? (c > p) : (c < p));
}
private bool Widens(string previous, string current, bool isLowerBound)
{
int p = 0;
int c = 0;
return int.TryParse(previous, out p) &&
int.TryParse(current, out c) &&
(isLowerBound ? (c < p) : (c > p));
}
protected void CompareItems(ComparisonContext context, SwaggerObject prior)
{
if (prior == null)
{
throw new ArgumentNullException("prior");
}
if (context == null)
{
throw new ArgumentNullException("context");
}
if (prior.Items != null && Items != null)
{
context.PushProperty("items");
Items.Compare(context, prior.Items);
context.Pop();
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace QuantConnect.Securities.Positions
{
/// <summary>
/// Provides a collection type for <see cref="IPositionGroup"/>
/// </summary>
public class PositionGroupCollection : IReadOnlyCollection<IPositionGroup>
{
/// <summary>
/// Gets an empty instance of the <see cref="PositionGroupCollection"/> class
/// </summary>
public static PositionGroupCollection Empty { get; } = new PositionGroupCollection(
ImmutableDictionary<PositionGroupKey, IPositionGroup>.Empty,
ImmutableDictionary<Symbol, ImmutableHashSet<IPositionGroup>>.Empty
);
/// <summary>
/// Gets the number of positions in this group
/// </summary>
public int Count => _groups.Count;
/// <summary>
/// Gets whether or not this collection contains only default position groups
/// </summary>
public bool IsOnlyDefaultGroups
{
get
{
if (_hasNonDefaultGroups == null)
{
_hasNonDefaultGroups = _groups.Count == 0 || _groups.All(grp => grp.Key.IsDefaultGroup);
}
return _hasNonDefaultGroups.Value;
}
}
private bool? _hasNonDefaultGroups;
private readonly ImmutableDictionary<PositionGroupKey, IPositionGroup> _groups;
private readonly ImmutableDictionary<Symbol, ImmutableHashSet<IPositionGroup>> _groupsBySymbol;
/// <summary>
/// Initializes a new instance of the <see cref="PositionGroupCollection"/> class
/// </summary>
/// <param name="groups">The position groups keyed by their group key</param>
/// <param name="groupsBySymbol">The position groups keyed by the symbol of each position</param>
public PositionGroupCollection(
ImmutableDictionary<PositionGroupKey, IPositionGroup> groups,
ImmutableDictionary<Symbol, ImmutableHashSet<IPositionGroup>> groupsBySymbol
)
{
_groups = groups;
_groupsBySymbol = groupsBySymbol;
}
/// <summary>
/// Initializes a new instance of the <see cref="PositionGroupCollection"/> class
/// </summary>
/// <param name="groups">The position groups</param>
public PositionGroupCollection(IReadOnlyCollection<IPositionGroup> groups)
{
_groups = groups.ToImmutableDictionary(g => g.Key);
_groupsBySymbol = groups.SelectMany(group =>
group.Select(position => new {position.Symbol, group})
)
.GroupBy(item => item.Symbol)
.ToImmutableDictionary(
item => item.Key,
item => item.Select(x => x.group).ToImmutableHashSet()
);
}
/// <summary>
/// Creates a new <see cref="PositionGroupCollection"/> that contains all of the position groups
/// in this collection in addition to the specified <paramref name="group"/>. If a group with the
/// same key already exists then it is overwritten.
/// </summary>
public PositionGroupCollection Add(IPositionGroup group)
{
var bySymbol = _groupsBySymbol;
foreach (var position in group)
{
ImmutableHashSet<IPositionGroup> groups;
if (!_groupsBySymbol.TryGetValue(position.Symbol, out groups))
{
groups = ImmutableHashSet<IPositionGroup>.Empty;
}
bySymbol = _groupsBySymbol.SetItem(position.Symbol, groups.Add(group));
}
return new PositionGroupCollection(_groups.SetItem(group.Key, group), bySymbol);
}
/// <summary>
/// Determines whether or not a group with the specified key exists in this collection
/// </summary>
/// <param name="key">The group key to search for</param>
/// <returns>True if a group with the specified key was found, false otherwise</returns>
public bool Contains(PositionGroupKey key)
{
return _groups.ContainsKey(key);
}
/// <summary>
/// Gets the <see cref="IPositionGroup"/> matching the specified key. If one does not exist, then an empty
/// group is returned matching the unit quantities defined in the <paramref name="key"/>
/// </summary>
/// <param name="key">The position group key to search for</param>
/// <returns>The position group matching the specified key, or a new empty group if no matching group is found.</returns>
public IPositionGroup this[PositionGroupKey key]
{
get
{
IPositionGroup group;
if (!TryGetGroup(key, out group))
{
return new PositionGroup(key, key.CreateEmptyPositions());
}
return group;
}
}
/// <summary>
/// Attempts to retrieve the group with the specified key
/// </summary>
/// <param name="key">The group key to search for</param>
/// <param name="group">The position group</param>
/// <returns>True if group with key found, otherwise false</returns>
public bool TryGetGroup(PositionGroupKey key, out IPositionGroup group)
{
return _groups.TryGetValue(key, out group);
}
/// <summary>
/// Attempts to retrieve all groups that contain the provided symbol
/// </summary>
/// <param name="symbol">The symbol</param>
/// <param name="groups">The groups if any were found, otherwise null</param>
/// <returns>True if groups were found for the specified symbol, otherwise false</returns>
public bool TryGetGroups(Symbol symbol, out IReadOnlyCollection<IPositionGroup> groups)
{
ImmutableHashSet<IPositionGroup> list;
if (_groupsBySymbol.TryGetValue(symbol, out list) && list?.IsEmpty == false)
{
groups = list;
return true;
}
groups = null;
return false;
}
/// <summary>
/// Merges this position group collection with the provided <paramref name="other"/> collection.
/// </summary>
public PositionGroupCollection CombineWith(PositionGroupCollection other)
{
var result = this;
foreach (var positionGroup in other)
{
result = result.Add(positionGroup);
}
return result;
}
/// <summary>Returns an enumerator that iterates through the collection.</summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<IPositionGroup> GetEnumerator()
{
return _groups.Values.GetEnumerator();
}
/// <summary>Returns an enumerator that iterates through a collection.</summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| |
using System;
using System.Collections.Generic;
using Zenject;
using NUnit.Framework;
using System.Linq;
using ModestTree;
using Assert=ModestTree.Assert;
namespace Zenject.Tests.Bindings
{
[TestFixture]
public class TestTo : ZenjectUnitTestFixture
{
[Test]
public void TestSelfSingle()
{
Container.Bind<Foo>().AsSingle().NonLazy();
Container.Validate();
Assert.IsNotNull(Container.Resolve<Foo>());
Assert.IsEqual(Container.Resolve<Foo>(), Container.Resolve<Foo>());
}
[Test]
public void TestSelfSingleExplicit()
{
Container.Bind<Foo>().ToSelf().FromNew().AsSingle().NonLazy();
Container.Validate();
Assert.IsNotNull(Container.Resolve<Foo>());
Assert.IsEqual(Container.Resolve<Foo>(), Container.Resolve<Foo>());
}
[Test]
public void TestSelfTransient()
{
Container.Bind<Foo>().AsTransient().NonLazy();
Container.Validate();
Assert.IsNotNull(Container.Resolve<Foo>());
Assert.IsNotEqual(Container.Resolve<Foo>(), Container.Resolve<Foo>());
}
[Test]
public void TestSelfCached()
{
Container.Bind<Foo>().AsCached().NonLazy();
Container.Validate();
Assert.IsNotNull(Container.Resolve<Foo>());
Assert.IsEqual(Container.Resolve<Foo>(), Container.Resolve<Foo>());
}
[Test]
public void TestConcreteSingle()
{
Container.Bind<Foo>().AsSingle().NonLazy();
Container.Bind<IFoo>().To<Foo>().AsSingle().NonLazy();
Container.Validate();
Assert.IsNotNull(Container.Resolve<Foo>());
Assert.IsNotNull(Container.Resolve<IFoo>());
Assert.IsEqual(Container.Resolve<Foo>(), Container.Resolve<Foo>());
Assert.IsEqual(Container.Resolve<IFoo>(), Container.Resolve<Foo>());
Assert.IsEqual(Container.Resolve<IFoo>(), Container.Resolve<IFoo>());
}
[Test]
public void TestConcreteTransient()
{
Container.Bind<IFoo>().To<Foo>().AsTransient().NonLazy();
Container.Validate();
Assert.IsNotNull(Container.Resolve<IFoo>());
Assert.IsNotEqual(Container.Resolve<IFoo>(), Container.Resolve<IFoo>());
}
[Test]
public void TestConcreteTransient2()
{
Container.Bind<IFoo>().To<Foo>().NonLazy();
Container.Validate();
Assert.IsNotNull(Container.Resolve<IFoo>());
Assert.IsNotEqual(Container.Resolve<IFoo>(), Container.Resolve<IFoo>());
}
[Test]
public void TestConcreteCached()
{
Container.Bind<Foo>().AsCached().NonLazy();
Container.Bind<IFoo>().To<Foo>().AsCached().NonLazy();
Container.Validate();
Assert.IsNotNull(Container.Resolve<Foo>());
Assert.IsNotNull(Container.Resolve<IFoo>());
Assert.IsEqual(Container.Resolve<IFoo>(), Container.Resolve<IFoo>());
Assert.IsEqual(Container.Resolve<Foo>(), Container.Resolve<Foo>());
Assert.IsNotEqual(Container.Resolve<IFoo>(), Container.Resolve<Foo>());
}
[Test]
public void TestDuplicateBindingsFail()
{
Container.Bind<Foo>().AsSingle().NonLazy();
Container.Bind<Foo>().AsSingle().NonLazy();
Container.Validate();
Assert.Throws(
delegate { Container.Resolve<Foo>(); });
Assert.IsEqual(Container.ResolveAll<Foo>().Count, 2);
}
[Test]
public void TestConcreteMultipleTransient()
{
Container.Bind<IFoo>().To(typeof(Foo), typeof(Bar)).AsTransient().NonLazy();
Container.Validate();
var foos = Container.ResolveAll<IFoo>();
Assert.IsEqual(foos.Count, 2);
Assert.That(foos[0] is Foo);
Assert.That(foos[1] is Bar);
var foos2 = Container.ResolveAll<IFoo>();
Assert.IsNotEqual(foos[0], foos2[0]);
Assert.IsNotEqual(foos[1], foos2[1]);
}
[Test]
public void TestConcreteMultipleSingle()
{
Container.Bind<IFoo>().To(typeof(Foo), typeof(Bar)).AsSingle().NonLazy();
Container.Validate();
var foos = Container.ResolveAll<IFoo>();
Assert.IsEqual(foos.Count, 2);
Assert.That(foos[0] is Foo);
Assert.That(foos[1] is Bar);
var foos2 = Container.ResolveAll<IFoo>();
Assert.IsEqual(foos[0], foos2[0]);
Assert.IsEqual(foos[1], foos2[1]);
}
[Test]
[ExpectedException]
public void TestMultipleBindingsSingleFail1()
{
Container.Bind(typeof(IFoo), typeof(IBar)).AsSingle();
Container.Resolve<IFoo>();
}
[Test]
[ExpectedException]
public void TestMultipleBindingsSingleFail2()
{
Container.Bind(typeof(IFoo), typeof(IBar)).To<Qux>().AsSingle();
Container.Resolve<IFoo>();
}
[Test]
public void TestMultipleBindingsSingle()
{
Container.Bind(typeof(IFoo), typeof(IBar)).To<Foo>().AsSingle().NonLazy();
Container.Validate();
Assert.IsEqual(Container.Resolve<IFoo>(), Container.Resolve<IBar>());
Assert.That(Container.Resolve<IFoo>() is Foo);
}
[Test]
public void TestMultipleBindingsTransient()
{
Container.Bind(typeof(IFoo), typeof(IBar)).To<Foo>().AsTransient().NonLazy();
Container.Validate();
Assert.That(Container.Resolve<IFoo>() is Foo);
Assert.That(Container.Resolve<IBar>() is Foo);
Assert.IsNotEqual(Container.Resolve<IFoo>(), Container.Resolve<IFoo>());
Assert.IsNotEqual(Container.Resolve<IFoo>(), Container.Resolve<IBar>());
}
[Test]
public void TestMultipleBindingsCached()
{
Container.Bind(typeof(IFoo), typeof(IBar)).To<Foo>().AsCached().NonLazy();
Container.Validate();
Assert.IsEqual(Container.Resolve<IFoo>(), Container.Resolve<IFoo>());
Assert.IsEqual(Container.Resolve<IFoo>(), Container.Resolve<IBar>());
}
[Test]
public void TestMultipleBindingsConcreteMultipleSingle()
{
Container.Bind(typeof(IFoo), typeof(IBar)).To(new List<Type>() {typeof(Foo), typeof(Bar)}).AsSingle().NonLazy();
Container.Bind<Foo>().AsSingle().NonLazy();
Container.Bind<Bar>().AsSingle().NonLazy();
Container.Validate();
var foos = Container.ResolveAll<IFoo>();
var bars = Container.ResolveAll<IBar>();
Assert.IsEqual(foos.Count, 2);
Assert.IsEqual(bars.Count, 2);
Assert.That(foos[0] is Foo);
Assert.That(foos[1] is Bar);
Assert.IsEqual(foos[0], bars[0]);
Assert.IsEqual(foos[1], bars[1]);
Assert.IsEqual(foos[0], Container.Resolve<Foo>());
Assert.IsEqual(foos[1], Container.Resolve<Bar>());
}
[Test]
public void TestMultipleBindingsConcreteMultipleTransient()
{
Container.Bind(typeof(IFoo), typeof(IBar)).To(new List<Type>() {typeof(Foo), typeof(Bar)}).AsTransient().NonLazy();
Container.Validate();
var foos = Container.ResolveAll<IFoo>();
var bars = Container.ResolveAll<IBar>();
Assert.IsEqual(foos.Count, 2);
Assert.IsEqual(bars.Count, 2);
Assert.That(foos[0] is Foo);
Assert.That(foos[1] is Bar);
Assert.IsNotEqual(foos[0], bars[0]);
Assert.IsNotEqual(foos[1], bars[1]);
}
[Test]
public void TestMultipleBindingsConcreteMultipleCached()
{
Container.Bind(typeof(IFoo), typeof(IBar)).To(new List<Type>() {typeof(Foo), typeof(Bar)}).AsCached().NonLazy();
Container.Bind<Foo>().AsSingle().NonLazy();
Container.Bind<Bar>().AsSingle().NonLazy();
Container.Validate();
var foos = Container.ResolveAll<IFoo>();
var bars = Container.ResolveAll<IBar>();
Assert.IsEqual(foos.Count, 2);
Assert.IsEqual(bars.Count, 2);
Assert.That(foos[0] is Foo);
Assert.That(foos[1] is Bar);
Assert.IsEqual(foos[0], bars[0]);
Assert.IsEqual(foos[1], bars[1]);
Assert.IsNotEqual(foos[0], Container.Resolve<Foo>());
Assert.IsNotEqual(foos[1], Container.Resolve<Bar>());
}
[Test]
public void TestSingletonIdsSameIdsSameInstance()
{
Container.Bind<IBar>().To<Foo>().AsSingle("foo").NonLazy();
Container.Bind<IFoo>().To<Foo>().AsSingle("foo").NonLazy();
Container.Bind<Foo>().AsSingle("foo").NonLazy();
Container.Validate();
Assert.IsEqual(Container.Resolve<Foo>(), Container.Resolve<IFoo>());
Assert.IsEqual(Container.Resolve<Foo>(), Container.Resolve<IBar>());
}
[Test]
public void TestSingletonIdsDifferentIdsDifferentInstances()
{
Container.Bind<IFoo>().To<Foo>().AsSingle("foo").NonLazy();
Container.Bind<Foo>().AsSingle("bar").NonLazy();
Container.Validate();
Assert.IsNotEqual(Container.Resolve<Foo>(), Container.Resolve<IFoo>());
}
[Test]
public void TestSingletonIdsNoIdDifferentInstances()
{
Container.Bind<IFoo>().To<Foo>().AsSingle().NonLazy();
Container.Bind<Foo>().AsSingle("bar").NonLazy();
Container.Validate();
Assert.IsNotEqual(Container.Resolve<Foo>(), Container.Resolve<IFoo>());
}
[Test]
public void TestSingletonIdsManyInstances()
{
Container.Bind<IFoo>().To<Foo>().AsSingle("foo1").NonLazy();
Container.Bind<IFoo>().To<Foo>().AsSingle("foo2").NonLazy();
Container.Bind<IFoo>().To<Foo>().AsSingle("foo3").NonLazy();
Container.Bind<IFoo>().To<Foo>().AsSingle("foo4").NonLazy();
Container.Validate();
Assert.IsEqual(Container.ResolveAll<IFoo>().Count, 4);
}
interface IBar
{
}
interface IFoo
{
}
class Foo : IFoo, IBar
{
}
class Bar : IFoo, IBar
{
}
public class Qux
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using gView.Framework.UI;
using System.IO;
using gView.Interoperability.OGC.Dataset.GML;
using gView.Framework.Data;
using gView.Framework.system.UI;
namespace gView.Interoperability.OGC.UI.Dataset.GML
{
[gView.Framework.system.RegisterPlugIn("7FE05D6F-F480-4ee5-B592-934826A1C17A")]
public class GMLExplorerObject : ExplorerParentObject, IExplorerFileObject, IExplorerObjectDeletable
{
private string _filename = "";
internal gView.Interoperability.OGC.Dataset.GML.Dataset _dataset = null;
private GMLIcon _icon = new GMLIcon();
public GMLExplorerObject() : base(null, typeof(OGC.Dataset.GML.Dataset), 2) { }
public GMLExplorerObject(IExplorerObject parent, string filename)
: base(parent, typeof(OGC.Dataset.GML.Dataset),2)
{
_filename = filename;
_dataset = new gView.Interoperability.OGC.Dataset.GML.Dataset();
_dataset.ConnectionString = filename;
_dataset.Open();
}
internal GMLExplorerObject(IExplorerObject parent, GMLExplorerObject exObject)
: base(parent, typeof(OGC.Dataset.GML.Dataset), 2)
{
_filename = exObject._filename;
_dataset = exObject._dataset;
}
#region IExplorerFileObject Member
public string Filter
{
get { return "*.gml|*.xml"; }
}
public IExplorerFileObject CreateInstance(IExplorerObject parent, string filename)
{
GMLExplorerObject exObject = new GMLExplorerObject(null, filename);
if (exObject._dataset.State == DatasetState.opened)
return new GMLExplorerObject(null, exObject);
return null;
}
#endregion
#region IExplorerObject Member
public string Name
{
get
{
try
{
FileInfo fi = new FileInfo(_filename);
return fi.Name;
}
catch
{
return "???.GML";
}
}
}
public string FullName
{
get { return _filename; }
}
public string Type
{
get { return "OGC GML File"; }
}
public IExplorerIcon Icon
{
get { return _icon; }
}
public new object Object
{
get { return _dataset; }
}
#endregion
#region IDisposable Member
public void Dispose()
{
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
try
{
GMLExplorerObject exObject = new GMLExplorerObject();
exObject = exObject.CreateInstance(null, FullName) as GMLExplorerObject;
if (exObject != null)
{
cache.Append(exObject);
}
return exObject;
}
catch
{
return null;
}
}
#endregion
#region IExplorerParentObject Member
public override void Refresh()
{
base.Refresh();
if (_dataset == null) return;
foreach (IDatasetElement element in _dataset.Elements)
{
base.AddChildObject(new GMLFeatureClassExplorerObject(this, element.Title));
}
}
#endregion
#region IExplorerObjectDeletable Member
public event ExplorerObjectDeletedEvent ExplorerObjectDeleted;
public bool DeleteExplorerObject(ExplorerObjectEventArgs e)
{
if (_dataset != null)
{
if (_dataset.Delete())
{
if (ExplorerObjectDeleted != null) ExplorerObjectDeleted(this);
return true;
}
}
return false;
}
#endregion
}
public class GMLFeatureClassExplorerObject : ExplorerObjectCls, IExplorerSimpleObject
{
private string _fcName;
private GMLExplorerObject _parent;
private IFeatureClass _fc;
private GMLFeatureClassIcon _icon = new GMLFeatureClassIcon();
public GMLFeatureClassExplorerObject(GMLExplorerObject parent, string fcName)
: base(parent, typeof(IFeatureClass), 1)
{
_parent = parent;
_fcName = fcName;
if (this.Dataset != null)
{
IDatasetElement element = this.Dataset[fcName];
if (element != null) _fc = element.Class as IFeatureClass;
}
}
private gView.Interoperability.OGC.Dataset.GML.Dataset Dataset
{
get
{
if (_parent == null || !(_parent.Object is gView.Interoperability.OGC.Dataset.GML.Dataset))
return null;
return _parent.Object as gView.Interoperability.OGC.Dataset.GML.Dataset;
}
}
#region IExplorerObject Member
public string Name
{
get { return _fcName; }
}
public string FullName
{
get { return _parent.FullName + @"\" + Name; }
}
public string Type
{
get { return "GML Featureclass"; }
}
public IExplorerIcon Icon
{
get { return _icon; }
}
public new object Object
{
get { return _fc; }
}
#endregion
#region IDisposable Member
public void Dispose()
{
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
return null;
}
#endregion
}
class GMLIcon : IExplorerIcon
{
#region IExplorerIcon Member
public Guid GUID
{
get { return new Guid("920FAAC4-4181-4729-A64B-65B02DF2883B"); }
}
public System.Drawing.Image Image
{
get { return global::gView.Interoperability.OGC.UI.Properties.Resources.gml; }
}
#endregion
}
class GMLFeatureClassIcon : IExplorerIcon
{
#region IExplorerIcon Member
public Guid GUID
{
get { return new Guid("238B1043-F758-4c90-8539-9988D76AA5D0"); }
}
public System.Drawing.Image Image
{
get { return global::gView.Interoperability.OGC.UI.Properties.Resources.gml_layer; }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Antlr4.Runtime;
namespace AntlrDenter
{
public abstract class DenterHelper
{
private readonly int _dedentToken;
private readonly Queue<IToken> _dentsBuffer = new Queue<IToken>();
private readonly Deque<int> _indentations = new Deque<int>();
private readonly int _indentToken;
private readonly int _nlToken;
private IEofHandler _eofHandler;
private bool _reachedEof;
protected DenterHelper(int nlToken, int indentToken, int dedentToken)
{
_nlToken = nlToken;
_indentToken = indentToken;
_dedentToken = dedentToken;
_eofHandler = new StandardEofHandler(this);
}
public IToken NextToken()
{
InitIfFirstRun();
IToken t = _dentsBuffer.Count == 0
? PullToken()
: _dentsBuffer.Dequeue();
if (_reachedEof) return t;
IToken r;
if (t.Type == _nlToken)
r = HandleNewlineToken(t);
else if (t.Type == -1)
r = _eofHandler.Apply(t);
else
r = t;
return r;
}
public IDenterOptions GetOptions()
{
return new DenterOptionsImpl(this);
}
protected abstract IToken PullToken();
private void InitIfFirstRun()
{
if (_indentations.Count == 0)
{
_indentations.AddFront(0);
// First invocation. Look for the first non-NL. Enqueue it, and possibly an indentation if that non-NL
// token doesn't start at char 0.
IToken firstRealToken;
do
{
firstRealToken = PullToken();
} while (firstRealToken.Type == _nlToken);
if (firstRealToken.Column > 0)
{
_indentations.AddFront(firstRealToken.Column);
_dentsBuffer.Enqueue(CreateToken(_indentToken, firstRealToken));
}
_dentsBuffer.Enqueue(firstRealToken);
}
}
private IToken HandleNewlineToken(IToken t)
{
// fast-forward to the next non-NL
IToken nextNext = PullToken();
while (nextNext.Type == _nlToken)
{
t = nextNext;
nextNext = PullToken();
}
if (nextNext.Type == -1) return _eofHandler.Apply(nextNext);
// nextNext is now a non-NL token; we'll queue it up after any possible dents
string nlText = t.Text;
int indent = nlText.Length - 1; // every NL has one \n char, so shorten the length to account for it
if (indent > 0 && nlText[0] == '\r')
--indent; // If the NL also has a \r char, we should account for that as well
int prevIndent = _indentations.Get(0);
IToken r;
if (indent == prevIndent)
{
r = t; // just a newline
}
else if (indent > prevIndent)
{
r = CreateToken(_indentToken, t);
_indentations.AddFront(indent);
}
else
{
r = UnwindTo(indent, t);
}
_dentsBuffer.Enqueue(nextNext);
return r;
}
private IToken CreateToken(int tokenType, IToken copyFrom)
{
string tokenTypeStr;
if (tokenType == _nlToken)
tokenTypeStr = "newline";
else if (tokenType == _indentToken)
tokenTypeStr = "indent";
else if (tokenType == _dedentToken)
tokenTypeStr = "dedent";
else
tokenTypeStr = null;
CommonToken r = new InjectedToken(copyFrom, tokenTypeStr);
r.Type = tokenType;
return r;
}
/**
* Returns a DEDENT token, and also queues up additional DEDENTS as necessary.
* @param targetIndent the "size" of the indentation (number of spaces) by the end
* @param copyFrom the triggering token
* @return a DEDENT token
*/
private IToken UnwindTo(int targetIndent, IToken copyFrom)
{
//assert _dentsBuffer.isEmpty() : _dentsBuffer;
_dentsBuffer.Enqueue(CreateToken(_nlToken, copyFrom));
// To make things easier, we'll queue up ALL of the dedents, and then pop off the first one.
// For example, here's how some text is analyzed:
//
// Text : Indentation : Action : Indents Deque
// [ baseline ] : 0 : nothing : [0]
// [ foo ] : 2 : INDENT : [0, 2]
// [ bar ] : 3 : INDENT : [0, 2, 3]
// [ baz ] : 0 : DEDENT x2 : [0]
while (true)
{
int prevIndent = _indentations.RemoveFront();
if (prevIndent == targetIndent) break;
if (targetIndent > prevIndent)
{
// "weird" condition above
_indentations.AddFront(prevIndent); // restore previous indentation, since we've indented from it
_dentsBuffer.Enqueue(CreateToken(_indentToken, copyFrom));
break;
}
_dentsBuffer.Enqueue(CreateToken(_dedentToken, copyFrom));
}
_indentations.AddFront(targetIndent);
return _dentsBuffer.Dequeue();
}
public static IBuilder0 Builder()
{
return new BuilderImpl();
}
private class StandardEofHandler : IEofHandler
{
private readonly DenterHelper _helper;
public StandardEofHandler(DenterHelper helper)
{
_helper = helper;
}
public IToken Apply(IToken t)
{
IToken r;
// when we reach EOF, unwind all indentations. If there aren't any, insert a NL. This lets the grammar treat
// un-indented expressions as just being NL-terminated, rather than NL|EOF.
if (_helper._indentations.Count == 0)
{
r = _helper.CreateToken(_helper._nlToken, t);
_helper._dentsBuffer.Enqueue(t);
}
else
{
r = _helper.UnwindTo(0, t);
_helper._dentsBuffer.Enqueue(t);
}
_helper._reachedEof = true;
return r;
}
}
private interface IEofHandler
{
IToken Apply(IToken t);
}
private class DenterOptionsImpl : IDenterOptions
{
private readonly DenterHelper _helper;
public DenterOptionsImpl(DenterHelper helper)
{
_helper = helper;
}
public void IgnoreEof()
{
_helper._eofHandler = new EofHandler(_helper);
}
private class EofHandler : IEofHandler
{
private readonly DenterHelper _helper;
public EofHandler(DenterHelper helper)
{
_helper = helper;
}
public IToken Apply(IToken t)
{
_helper._reachedEof = true;
return t;
}
}
}
private class InjectedToken : CommonToken
{
private readonly string _type;
public InjectedToken(IToken oldToken, string type) : base(oldToken)
{
_type = type;
}
public string GetText()
{
if (_type != null) Text = _type;
return Text;
}
}
public interface IBuilder0
{
IBuilder1 Nl(int nl);
}
public interface IBuilder1
{
IBuilder2 Indent(int indent);
}
public interface IBuilder2
{
IBuilder3 Dedent(int dedent);
}
public interface IBuilder3
{
DenterHelper PullToken(Func<IToken> puller);
}
private class BuilderImpl : IBuilder0, IBuilder1, IBuilder2, IBuilder3
{
private int _dedent;
private int _indent;
private int _nl;
public IBuilder1 Nl(int nl)
{
_nl = nl;
return this;
}
public IBuilder2 Indent(int indent)
{
_indent = indent;
return this;
}
public IBuilder3 Dedent(int dedent)
{
_dedent = dedent;
return this;
}
public DenterHelper PullToken(Func<IToken> puller)
{
return new DenterHelperImpl(_nl, _indent, _dedent, puller);
}
private class DenterHelperImpl : DenterHelper
{
private readonly Func<IToken> _puller;
public DenterHelperImpl(int nlToken, int indentToken, int dedentToken, Func<IToken> puller) : base(
nlToken, indentToken, dedentToken)
{
_puller = puller;
}
protected override IToken PullToken()
{
return _puller();
}
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="Converter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Objects.DataClasses;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Som = System.Data.EntityModel.SchemaObjectModel;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Helper Class for converting SOM objects to metadata objects
/// This class should go away once we have completely integrated SOM and metadata
/// </summary>
internal static class Converter
{
#region Constructor
/// <summary>
/// Static constructor for creating FacetDescription objects that we use
/// </summary>
static Converter()
{
Debug.Assert(Enum.GetUnderlyingType(typeof(ConcurrencyMode)) == typeof(int), "Please update underlying type below accordingly.");
// Create the enum types that we will need
EnumType concurrencyModeType = new EnumType(EdmProviderManifest.ConcurrencyModeFacetName,
EdmConstants.EdmNamespace,
underlyingType: PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32),
isFlags: false,
dataSpace: DataSpace.CSpace);
foreach (string name in Enum.GetNames(typeof(ConcurrencyMode)))
{
concurrencyModeType.AddMember(
new EnumMember(
name,
(int)Enum.Parse(typeof(ConcurrencyMode), name, false)));
}
Debug.Assert(Enum.GetUnderlyingType(typeof(StoreGeneratedPattern)) == typeof(int), "Please update underlying type below accordingly.");
EnumType storeGeneratedPatternType = new EnumType(EdmProviderManifest.StoreGeneratedPatternFacetName,
EdmConstants.EdmNamespace,
underlyingType: PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32),
isFlags: false,
dataSpace: DataSpace.CSpace);
foreach (string name in Enum.GetNames(typeof(StoreGeneratedPattern)))
{
storeGeneratedPatternType.AddMember(
new EnumMember(
name,
(int)Enum.Parse(typeof(StoreGeneratedPattern), name, false)));
}
// Now create the facet description objects
ConcurrencyModeFacet = new FacetDescription(EdmProviderManifest.ConcurrencyModeFacetName,
concurrencyModeType,
null,
null,
ConcurrencyMode.None);
StoreGeneratedPatternFacet = new FacetDescription(EdmProviderManifest.StoreGeneratedPatternFacetName,
storeGeneratedPatternType,
null,
null,
StoreGeneratedPattern.None);
CollationFacet = new FacetDescription(EdmProviderManifest.CollationFacetName,
MetadataItem.EdmProviderManifest.GetPrimitiveType(PrimitiveTypeKind.String),
null,
null,
string.Empty);
}
#endregion
#region Fields
internal static readonly FacetDescription ConcurrencyModeFacet;
internal static readonly FacetDescription StoreGeneratedPatternFacet;
internal static readonly FacetDescription CollationFacet;
#endregion
#region Methods
/// <summary>
/// Converts a schema from SOM into Metadata
/// </summary>
/// <param name="somSchema">The SOM schema to convert</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="itemCollection">The item collection for currently existing metadata objects</param>
internal static IEnumerable<GlobalItem> ConvertSchema(Som.Schema somSchema,
DbProviderManifest providerManifest,
ItemCollection itemCollection)
{
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems = new Dictionary<Som.SchemaElement, GlobalItem>();
ConvertSchema(somSchema, providerManifest, new ConversionCache(itemCollection), newGlobalItems);
return newGlobalItems.Values;
}
internal static IEnumerable<GlobalItem> ConvertSchema(IList<Som.Schema> somSchemas,
DbProviderManifest providerManifest,
ItemCollection itemCollection)
{
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems = new Dictionary<Som.SchemaElement, GlobalItem>();
ConversionCache conversionCache = new ConversionCache(itemCollection);
foreach (Som.Schema somSchema in somSchemas)
{
ConvertSchema(somSchema, providerManifest, conversionCache, newGlobalItems);
}
return newGlobalItems.Values;
}
private static void ConvertSchema(Som.Schema somSchema, DbProviderManifest providerManifest,
ConversionCache convertedItemCache, Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
List<Som.Function> funcsWithUnresolvedTypes = new List<Som.Function>();
foreach (Som.SchemaType element in somSchema.SchemaTypes)
{
if (null == LoadSchemaElement(element, providerManifest, convertedItemCache, newGlobalItems))
{
if (element is Som.Function)
{
funcsWithUnresolvedTypes.Add(element as Som.Function);
}
}
}
foreach (Som.SchemaEntityType element in somSchema.SchemaTypes.OfType<Som.SchemaEntityType>())
{
LoadEntityTypePhase2(element, providerManifest, convertedItemCache, newGlobalItems);
}
foreach (var function in funcsWithUnresolvedTypes)
{
if (null == LoadSchemaElement(function, providerManifest, convertedItemCache, newGlobalItems))
{
Debug.Fail("Could not load model function definition"); //this should never happen.
}
}
if (convertedItemCache.ItemCollection.DataSpace == DataSpace.CSpace)
{
EdmItemCollection edmCollection = (EdmItemCollection)convertedItemCache.ItemCollection;
edmCollection.EdmVersion = somSchema.SchemaVersion;
}
else
{
Debug.Assert(convertedItemCache.ItemCollection.DataSpace == DataSpace.SSpace, "Did you add a new space?");
// when converting the ProviderManifest, the DataSpace is SSpace, but the ItemCollection is EmptyItemCollection,
// not StoreItemCollection
StoreItemCollection storeCollection = convertedItemCache.ItemCollection as StoreItemCollection;
if (storeCollection != null)
{
storeCollection.StoreSchemaVersion = somSchema.SchemaVersion;
}
}
}
/// <summary>
/// Loads a schema element
/// </summary>
/// <param name="element">The SOM element to process</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <returns>The item resulting from the load</returns>
internal static MetadataItem LoadSchemaElement(Som.SchemaType element,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
Debug.Assert(providerManifest != null, "This will make the dataspace to be default SSpace");
// Try to fetch from the collection first
GlobalItem item;
Debug.Assert(!convertedItemCache.ItemCollection.TryGetValue(element.FQName, false, out item), "Som should have checked for duplicate items");
// Try to fetch in our collection of new GlobalItems
if (newGlobalItems.TryGetValue(element, out item))
{
return item;
}
Som.EntityContainer entityContainer = element as Som.EntityContainer;
// Perform different conversion depending on the type of the SOM object
if (entityContainer != null)
{
item = ConvertToEntityContainer(entityContainer,
providerManifest,
convertedItemCache,
newGlobalItems);
}
else if (element is Som.SchemaEntityType)
{
item = ConvertToEntityType((Som.SchemaEntityType)element,
providerManifest,
convertedItemCache,
newGlobalItems);
}
else if (element is Som.Relationship)
{
item = ConvertToAssociationType((Som.Relationship)element,
providerManifest,
convertedItemCache,
newGlobalItems);
}
else if (element is Som.SchemaComplexType)
{
item = ConvertToComplexType((Som.SchemaComplexType)element,
providerManifest,
convertedItemCache,
newGlobalItems);
}
else if (element is Som.Function)
{
item = ConvertToFunction((Som.Function)element, providerManifest,
convertedItemCache, null, newGlobalItems);
}
else if (element is Som.SchemaEnumType)
{
item = ConvertToEnumType((Som.SchemaEnumType)element, newGlobalItems);
}
else
{
// the only type we don't handle is the ProviderManifest TypeElement
// if it is anything else, it is probably a mistake
Debug.Assert(element is Som.TypeElement &&
element.Schema.DataModel == Som.SchemaDataModelOption.ProviderManifestModel,
"Unknown Type in somschema");
return null;
}
return item;
}
/// <summary>
/// Converts an entity container from SOM to metadata
/// </summary>
/// <param name="element">The SOM element to process</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <returns>The entity container object resulting from the convert</returns>
private static EntityContainer ConvertToEntityContainer(Som.EntityContainer element,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
// Creating a new entity container object and populate with converted entity set objects
EntityContainer entityContainer = new EntityContainer(element.Name, GetDataSpace(providerManifest));
newGlobalItems.Add(element, entityContainer);
foreach (Som.EntityContainerEntitySet entitySet in element.EntitySets)
{
entityContainer.AddEntitySetBase(ConvertToEntitySet(entitySet,
entityContainer.Name,
providerManifest,
convertedItemCache,
newGlobalItems));
}
// Populate with converted relationship set objects
foreach (Som.EntityContainerRelationshipSet relationshipSet in element.RelationshipSets)
{
Debug.Assert(relationshipSet.Relationship.RelationshipKind == RelationshipKind.Association,
"We do not support containment set");
entityContainer.AddEntitySetBase(ConvertToAssociationSet(relationshipSet,
providerManifest,
convertedItemCache,
entityContainer,
newGlobalItems));
}
// Populate with converted function imports
foreach (Som.Function functionImport in element.FunctionImports)
{
entityContainer.AddFunctionImport(ConvertToFunction(functionImport,
providerManifest, convertedItemCache, entityContainer, newGlobalItems));
}
// Extract the optional Documentation
if (element.Documentation != null)
{
entityContainer.Documentation = ConvertToDocumentation(element.Documentation);
}
AddOtherContent(element, entityContainer);
return entityContainer;
}
/// <summary>
/// Converts an entity type from SOM to metadata
///
/// This method should only build the internally contained and vertical part of the EntityType (keys, properties, and base types) but not
/// sideways parts (NavigationProperties) that go between types or we risk trying to access and EntityTypes keys, from the referential constraint,
/// before the base type, which has the keys, is setup yet.
/// </summary>
/// <param name="element">The SOM element to process</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <returns>The entity type object resulting from the convert</returns>
private static EntityType ConvertToEntityType(Som.SchemaEntityType element,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
string[] keyMembers = null;
// Check if this type has keys
if (element.DeclaredKeyProperties.Count != 0)
{
keyMembers = new string[element.DeclaredKeyProperties.Count];
for (int i = 0; i < keyMembers.Length; i++)
{
//Add the name of the key property to the list of
//key properties
keyMembers[i] = (element.DeclaredKeyProperties[i].Property.Name);
}
}
EdmProperty[] properties = new EdmProperty[element.Properties.Count];
int index = 0;
foreach (Som.StructuredProperty somProperty in element.Properties)
{
properties[index++] = ConvertToProperty(somProperty,
providerManifest,
convertedItemCache,
newGlobalItems);
}
EntityType entityType = new EntityType(element.Name,
element.Namespace,
GetDataSpace(providerManifest),
keyMembers,
properties);
if (element.BaseType != null)
{
entityType.BaseType = (EdmType)(LoadSchemaElement(element.BaseType,
providerManifest,
convertedItemCache,
newGlobalItems));
}
// set the abstract and sealed type values for the entity type
entityType.Abstract = element.IsAbstract;
// Extract the optional Documentation
if (element.Documentation != null)
{
entityType.Documentation = ConvertToDocumentation(element.Documentation);
}
AddOtherContent(element, entityType);
newGlobalItems.Add(element, entityType);
return entityType;
}
private static void LoadEntityTypePhase2(Som.SchemaEntityType element,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
EntityType entityType = (EntityType)newGlobalItems[element];
// Since Navigation properties are internal and not part of member collection, we
// need to initialize the base class first before we start adding the navigation property
// this will ensure that all the base navigation properties are initialized
foreach (Som.NavigationProperty somNavigationProperty in element.NavigationProperties)
{
entityType.AddMember(ConvertToNavigationProperty(entityType,
somNavigationProperty,
providerManifest,
convertedItemCache,
newGlobalItems));
}
}
/// <summary>
/// Converts an complex type from SOM to metadata
/// </summary>
/// <param name="element">The SOM element to process</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <returns>The complex type object resulting from the convert</returns>
private static ComplexType ConvertToComplexType(Som.SchemaComplexType element,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
ComplexType complexType = new ComplexType(element.Name,
element.Namespace,
GetDataSpace(providerManifest));
newGlobalItems.Add(element, complexType);
foreach (Som.StructuredProperty somProperty in element.Properties)
{
complexType.AddMember(ConvertToProperty(somProperty,
providerManifest,
convertedItemCache,
newGlobalItems));
}
// set the abstract and sealed type values for the entity type
complexType.Abstract = element.IsAbstract;
if (element.BaseType != null)
{
complexType.BaseType = (EdmType)(LoadSchemaElement(element.BaseType,
providerManifest,
convertedItemCache,
newGlobalItems));
}
// Extract the optional Documentation
if (element.Documentation != null)
{
complexType.Documentation = ConvertToDocumentation(element.Documentation);
}
AddOtherContent(element, complexType);
return complexType;
}
/// <summary>
/// Converts an association type from SOM to metadata
/// </summary>
/// <param name="element">The SOM element to process</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <returns>The association type object resulting from the convert</returns>
private static AssociationType ConvertToAssociationType(Som.Relationship element,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
Debug.Assert(element.RelationshipKind == RelationshipKind.Association);
AssociationType associationType = new AssociationType(element.Name,
element.Namespace,
element.IsForeignKey,
GetDataSpace(providerManifest));
newGlobalItems.Add(element, associationType);
foreach (Som.RelationshipEnd end in element.Ends)
{
Som.SchemaType entityTypeElement = end.Type;
EntityType endEntityType = (EntityType)LoadSchemaElement(entityTypeElement,
providerManifest,
convertedItemCache,
newGlobalItems);
AssociationEndMember endMember = InitializeAssociationEndMember(associationType, end, endEntityType);
AddOtherContent(end, endMember);
// Loop through and convert the operations
foreach (Som.OnOperation operation in end.Operations)
{
// Process only the ones that we recognize
if (operation.Operation != Som.Operation.Delete)
{
continue;
}
// Determine the action for this operation
OperationAction action = OperationAction.None;
switch (operation.Action)
{
case Som.Action.Cascade:
action = OperationAction.Cascade;
break;
case Som.Action.None:
action = OperationAction.None;
break;
default:
Debug.Fail("Operation action not supported.");
break;
}
endMember.DeleteBehavior = action;
}
// Extract optional Documentation from the end element
if (end.Documentation != null)
{
endMember.Documentation = ConvertToDocumentation(end.Documentation);
}
}
Debug.Assert(associationType.ReferentialConstraints.Count == 0, "This must never have been initialized");
for (int i = 0; i < element.Constraints.Count; i++)
{
Som.ReferentialConstraint constraint = element.Constraints[i];
AssociationEndMember fromMember = (AssociationEndMember)associationType.Members[constraint.PrincipalRole.Name];
AssociationEndMember toMember = (AssociationEndMember)associationType.Members[constraint.DependentRole.Name];
EntityTypeBase fromEntityType = ((RefType)fromMember.TypeUsage.EdmType).ElementType;
EntityTypeBase toEntityType = ((RefType)toMember.TypeUsage.EdmType).ElementType;
ReferentialConstraint referentialConstraint = new ReferentialConstraint(fromMember, toMember,
GetProperties(fromEntityType, constraint.PrincipalRole.RoleProperties),
GetProperties(toEntityType, constraint.DependentRole.RoleProperties));
// Attach the optional Documentation
if (constraint.Documentation != null)
referentialConstraint.Documentation = ConvertToDocumentation(constraint.Documentation);
if (constraint.PrincipalRole.Documentation != null)
referentialConstraint.FromRole.Documentation = ConvertToDocumentation(constraint.PrincipalRole.Documentation);
if (constraint.DependentRole.Documentation != null)
referentialConstraint.ToRole.Documentation = ConvertToDocumentation(constraint.DependentRole.Documentation);
associationType.AddReferentialConstraint(referentialConstraint);
AddOtherContent(element.Constraints[i], referentialConstraint);
}
// Extract the optional Documentation
if (element.Documentation != null)
{
associationType.Documentation = ConvertToDocumentation(element.Documentation);
}
AddOtherContent(element, associationType);
return associationType;
}
/// <summary>
/// Initialize the end member if its not initialized already
/// </summary>
/// <param name="associationType"></param>
/// <param name="end"></param>
/// <param name="endMemberType"></param>
private static AssociationEndMember InitializeAssociationEndMember(AssociationType associationType, Som.IRelationshipEnd end,
EntityType endMemberType)
{
AssociationEndMember associationEnd;
EdmMember member;
// make sure that the end is not initialized as of yet
if (!associationType.Members.TryGetValue(end.Name, false/*ignoreCase*/, out member))
{
// Create the end member and add the operations
associationEnd = new AssociationEndMember(end.Name,
endMemberType.GetReferenceType(),
end.Multiplicity.Value);
associationType.AddKeyMember(associationEnd);
}
else
{
associationEnd = (AssociationEndMember)member;
}
//Extract the optional Documentation
Som.RelationshipEnd relationshipEnd = end as Som.RelationshipEnd;
if (relationshipEnd != null && (relationshipEnd.Documentation != null))
{
associationEnd.Documentation = ConvertToDocumentation(relationshipEnd.Documentation);
}
return associationEnd;
}
private static EdmProperty[] GetProperties(EntityTypeBase entityType, IList<Som.PropertyRefElement> properties)
{
Debug.Assert(properties.Count != 0);
EdmProperty[] result = new EdmProperty[properties.Count];
for (int i = 0; i < properties.Count; i++)
{
result[i] = (EdmProperty)entityType.Members[properties[i].Name];
}
return result;
}
private static void AddOtherContent(Som.SchemaElement element, MetadataItem item)
{
if (element.OtherContent.Count > 0)
{
item.AddMetadataProperties(element.OtherContent);
}
}
/// <summary>
/// Converts an entity set from SOM to metadata
/// </summary>
/// <param name="set">The SOM element to process</param>
/// <param name="containerName">the name of the container this will be added to</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <returns>The entity set object resulting from the convert</returns>
private static EntitySet ConvertToEntitySet(Som.EntityContainerEntitySet set,
string containerName,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
EntitySet entitySet = new EntitySet(set.Name, set.DbSchema, set.Table, set.DefiningQuery,
(EntityType)LoadSchemaElement(set.EntityType,
providerManifest,
convertedItemCache,
newGlobalItems));
// Extract the optional Documentation
if (set.Documentation != null)
{
entitySet.Documentation = ConvertToDocumentation(set.Documentation);
}
AddOtherContent(set, entitySet);
return entitySet;
}
/// <summary>
/// Converts an entity set from SOM to metadata
/// </summary>
/// <param name="set">The SOM element to process</param>
/// <param name="container"></param>
/// <returns>The entity set object resulting from the convert</returns>
private static EntitySet GetEntitySet(Som.EntityContainerEntitySet set, EntityContainer container)
{
return container.GetEntitySetByName(set.Name, false);
}
/// <summary>
/// Converts an association set from SOM to metadata
/// </summary>
/// <param name="relationshipSet">The SOM element to process</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <param name="container"></param>
/// <returns>The association set object resulting from the convert</returns>
private static AssociationSet ConvertToAssociationSet(Som.EntityContainerRelationshipSet relationshipSet,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
EntityContainer container,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
Debug.Assert(relationshipSet.Relationship.RelationshipKind == RelationshipKind.Association);
AssociationType associationType = (AssociationType)LoadSchemaElement((Som.SchemaType)relationshipSet.Relationship,
providerManifest,
convertedItemCache,
newGlobalItems);
AssociationSet associationSet = new AssociationSet(relationshipSet.Name, associationType);
foreach (Som.EntityContainerRelationshipSetEnd end in relationshipSet.Ends)
{
//-- need the EntityType for the end
EntityType endEntityType = (EntityType)LoadSchemaElement(end.EntitySet.EntityType,
providerManifest,
convertedItemCache,
newGlobalItems);
//-- need to get the end member
AssociationEndMember endMember = (AssociationEndMember)associationType.Members[end.Name];
//-- create the end
AssociationSetEnd associationSetEnd = new AssociationSetEnd(GetEntitySet(end.EntitySet, container),
associationSet,
endMember);
AddOtherContent(end, associationSetEnd);
associationSet.AddAssociationSetEnd(associationSetEnd);
// Extract optional Documentation from the end element
if (end.Documentation != null)
{
associationSetEnd.Documentation = ConvertToDocumentation(end.Documentation);
}
}
// Extract the optional Documentation
if (relationshipSet.Documentation != null)
{
associationSet.Documentation = ConvertToDocumentation(relationshipSet.Documentation);
}
AddOtherContent(relationshipSet, associationSet);
return associationSet;
}
/// <summary>
/// Converts a property from SOM to metadata
/// </summary>
/// <param name="somProperty">The SOM element to process</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <returns>The property object resulting from the convert</returns>
private static EdmProperty ConvertToProperty(Som.StructuredProperty somProperty,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
EdmProperty property;
// Get the appropriate type object for this type, for primitive and enum types, get the facet values for the type
// property as a type usage object as well
TypeUsage typeUsage = null;
Som.ScalarType scalarType = somProperty.Type as Som.ScalarType;
if (scalarType != null && somProperty.Schema.DataModel != Som.SchemaDataModelOption.EntityDataModel)
{
// parsing ssdl
typeUsage = somProperty.TypeUsage;
UpdateSentinelValuesInFacets(ref typeUsage);
}
else
{
EdmType propertyType;
if (scalarType != null)
{
Debug.Assert(somProperty.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);
// try to get the instance of the primitive type from the item collection so that it back pointer is set.
propertyType = convertedItemCache.ItemCollection.GetItem<PrimitiveType>(somProperty.TypeUsage.EdmType.FullName);
}
else
{
propertyType = (EdmType)LoadSchemaElement(somProperty.Type, providerManifest, convertedItemCache, newGlobalItems);
}
if (somProperty.CollectionKind != CollectionKind.None)
{
typeUsage = TypeUsage.Create(new CollectionType(propertyType));
}
else
{
Som.SchemaEnumType enumType = scalarType == null ? somProperty.Type as Som.SchemaEnumType : null;
typeUsage = TypeUsage.Create(propertyType);
if (enumType != null)
{
somProperty.EnsureEnumTypeFacets(convertedItemCache, newGlobalItems);
}
if (somProperty.TypeUsage != null)
{
ApplyTypePropertyFacets(somProperty.TypeUsage, ref typeUsage);
}
}
}
PopulateGeneralFacets(somProperty, providerManifest, ref typeUsage);
property = new EdmProperty(somProperty.Name, typeUsage);
// Extract the optional Documentation
if (somProperty.Documentation != null)
{
property.Documentation = ConvertToDocumentation(somProperty.Documentation);
}
AddOtherContent(somProperty, property);
return property;
}
/// <summary>
/// Converts a navigation property from SOM to metadata
/// </summary>
/// <param name="declaringEntityType">entity type on which this navigation property was declared</param>
/// <param name="somNavigationProperty">The SOM element to process</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <returns>The property object resulting from the convert</returns>
private static NavigationProperty ConvertToNavigationProperty(EntityType declaringEntityType,
Som.NavigationProperty somNavigationProperty,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
// Navigation properties cannot be primitive types, so we can ignore the possibility of having primitive type
// facets
EntityType toEndEntityType = (EntityType)LoadSchemaElement(somNavigationProperty.Type,
providerManifest,
convertedItemCache,
newGlobalItems);
EdmType edmType = toEndEntityType;
// Also load the relationship Type that this navigation property represents
AssociationType relationshipType = (AssociationType)LoadSchemaElement((Som.Relationship)somNavigationProperty.Relationship,
providerManifest, convertedItemCache, newGlobalItems);
Som.IRelationshipEnd somRelationshipEnd = null;
somNavigationProperty.Relationship.TryGetEnd(somNavigationProperty.ToEnd.Name, out somRelationshipEnd);
if (somRelationshipEnd.Multiplicity == RelationshipMultiplicity.Many)
{
edmType = toEndEntityType.GetCollectionType();
}
else
{
Debug.Assert(somRelationshipEnd.Multiplicity != RelationshipMultiplicity.Many);
edmType = toEndEntityType;
}
TypeUsage typeUsage;
if (somRelationshipEnd.Multiplicity == RelationshipMultiplicity.One)
{
typeUsage = TypeUsage.Create(edmType,
new FacetValues { Nullable = false });
}
else
{
typeUsage = TypeUsage.Create(edmType);
}
// We need to make sure that both the ends of the relationtype are initialized. If there are not, then we should
// initialize them here
InitializeAssociationEndMember(relationshipType, somNavigationProperty.ToEnd, toEndEntityType);
InitializeAssociationEndMember(relationshipType, somNavigationProperty.FromEnd, declaringEntityType);
// The type of the navigation property must be a ref or collection depending on which end they belong to
NavigationProperty navigationProperty = new NavigationProperty(somNavigationProperty.Name, typeUsage);
navigationProperty.RelationshipType = relationshipType;
navigationProperty.ToEndMember = (RelationshipEndMember)relationshipType.Members[somNavigationProperty.ToEnd.Name];
navigationProperty.FromEndMember = (RelationshipEndMember)relationshipType.Members[somNavigationProperty.FromEnd.Name];
// Extract the optional Documentation
if (somNavigationProperty.Documentation != null)
{
navigationProperty.Documentation = ConvertToDocumentation(somNavigationProperty.Documentation);
}
AddOtherContent(somNavigationProperty, navigationProperty);
return navigationProperty;
}
/// <summary>
/// Converts a function from SOM to metadata
/// </summary>
/// <param name="somFunction">The SOM element to process</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="functionImportEntityContainer">For function imports, the entity container including the function declaration</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <returns>The function object resulting from the convert</returns>
private static EdmFunction ConvertToFunction(Som.Function somFunction,
DbProviderManifest providerManifest,
ConversionCache convertedItemCache,
EntityContainer functionImportEntityContainer,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
// If we already have it, don't bother converting
GlobalItem globalItem = null;
// if we are converted the function import, we need not check the global items collection,
// since the function imports are local to the entity container
if (!somFunction.IsFunctionImport && newGlobalItems.TryGetValue(somFunction, out globalItem))
{
return (EdmFunction)globalItem;
}
bool areConvertingForProviderManifest = somFunction.Schema.DataModel == Som.SchemaDataModelOption.ProviderManifestModel;
List<FunctionParameter> returnParameters = new List<FunctionParameter>();
if (somFunction.ReturnTypeList != null)
{
int i = 0;
foreach (Som.ReturnType somReturnType in somFunction.ReturnTypeList)
{
TypeUsage returnType = GetFunctionTypeUsage(somFunction is Som.ModelFunction,
somFunction,
somReturnType,
providerManifest,
areConvertingForProviderManifest,
somReturnType.Type,
somReturnType.CollectionKind,
somReturnType.IsRefType /*isRefType*/,
somFunction,
convertedItemCache,
newGlobalItems);
if (null != returnType)
{
// Create the return parameter object, need to set the declaring type explicitly on the return parameter
// because we aren't adding it to the members collection
string modifier = i == 0 ? string.Empty : i.ToString(System.Globalization.CultureInfo.InvariantCulture);
i++;
FunctionParameter returnParameter = new FunctionParameter(EdmConstants.ReturnType + modifier, returnType, ParameterMode.ReturnValue);
AddOtherContent(somReturnType, returnParameter);
returnParameters.Add(returnParameter);
}
else
{
return null;
}
}
}
// this case must be second to avoid calling somFunction.Type when returnTypeList has more than one element.
else if (somFunction.Type != null)
{
TypeUsage returnType = GetFunctionTypeUsage(somFunction is Som.ModelFunction,
somFunction,
null,
providerManifest,
areConvertingForProviderManifest,
somFunction.Type,
somFunction.CollectionKind,
somFunction.IsReturnAttributeReftype /*isRefType*/,
somFunction,
convertedItemCache,
newGlobalItems);
if (null != returnType)
{
// Create the return parameter object, need to set the declaring type explicitly on the return parameter
// because we aren't adding it to the members collection
returnParameters.Add(new FunctionParameter(EdmConstants.ReturnType, returnType, ParameterMode.ReturnValue));
}
else
{
//Return type was specified but we could not find a type usage
return null;
}
}
string functionNamespace;
EntitySet[] entitySets = null;
if (somFunction.IsFunctionImport)
{
var somFunctionImport = (Som.FunctionImportElement)somFunction;
functionNamespace = somFunctionImport.Container.Name;
if (null != somFunctionImport.EntitySet)
{
EntityContainer entityContainer;
Debug.Assert(somFunctionImport.ReturnTypeList == null || somFunctionImport.ReturnTypeList.Count == 1,
"EntitySet cannot be specified on a FunctionImport if there are multiple ReturnType children");
Debug.Assert(functionImportEntityContainer != null, "functionImportEntityContainer must be specified during function import conversion");
entityContainer = functionImportEntityContainer;
entitySets = new EntitySet[] { GetEntitySet(somFunctionImport.EntitySet, entityContainer) };
}
else if (null != somFunctionImport.ReturnTypeList)
{
Debug.Assert(functionImportEntityContainer != null, "functionImportEntityContainer must be specified during function import conversion");
EntityContainer entityContainer = functionImportEntityContainer;
entitySets = somFunctionImport.ReturnTypeList
.Select(returnType => null != returnType.EntitySet
? GetEntitySet(returnType.EntitySet, functionImportEntityContainer)
: null)
.ToArray();
}
}
else
{
functionNamespace = somFunction.Namespace;
}
List<FunctionParameter> parameters = new List<FunctionParameter>();
foreach (Som.Parameter somParameter in somFunction.Parameters)
{
TypeUsage parameterType = GetFunctionTypeUsage(somFunction is Som.ModelFunction,
somFunction,
somParameter,
providerManifest,
areConvertingForProviderManifest,
somParameter.Type,
somParameter.CollectionKind,
somParameter.IsRefType,
somParameter,
convertedItemCache,
newGlobalItems);
if (parameterType == null)
{
return null;
}
FunctionParameter parameter = new FunctionParameter(somParameter.Name,
parameterType,
GetParameterMode(somParameter.ParameterDirection));
AddOtherContent(somParameter, parameter);
if (somParameter.Documentation != null)
{
parameter.Documentation = ConvertToDocumentation(somParameter.Documentation);
}
parameters.Add(parameter);
}
EdmFunction function = new EdmFunction(somFunction.Name,
functionNamespace,
GetDataSpace(providerManifest),
new EdmFunctionPayload
{
Schema = somFunction.DbSchema,
StoreFunctionName = somFunction.StoreFunctionName,
CommandText = somFunction.CommandText,
EntitySets = entitySets,
IsAggregate = somFunction.IsAggregate,
IsBuiltIn = somFunction.IsBuiltIn,
IsNiladic = somFunction.IsNiladicFunction,
IsComposable = somFunction.IsComposable,
IsFromProviderManifest = areConvertingForProviderManifest,
IsFunctionImport = somFunction.IsFunctionImport,
ReturnParameters = returnParameters.ToArray(),
Parameters = parameters.ToArray(),
ParameterTypeSemantics = somFunction.ParameterTypeSemantics,
});
// Add this function to new global items, only if it is not a function import
if (!somFunction.IsFunctionImport)
{
newGlobalItems.Add(somFunction, function);
}
//Check if we already converted functions since we are loading it from
//ssdl we could see functions many times.
GlobalItem returnFunction = null;
Debug.Assert(!convertedItemCache.ItemCollection.TryGetValue(function.Identity, false, out returnFunction),
"Function duplicates must be checked by som");
// Extract the optional Documentation
if (somFunction.Documentation != null)
{
function.Documentation = ConvertToDocumentation(somFunction.Documentation);
}
AddOtherContent(somFunction, function);
return function;
}
/// <summary>
/// Converts SchemaEnumType instance to Metadata EnumType.
/// </summary>
/// <param name="somEnumType">SchemaEnumType to be covnerted.</param>
/// <param name="newGlobalItems">Global item objects where newly created Metadata EnumType will be added.</param>
/// <returns></returns>
private static EnumType ConvertToEnumType(Som.SchemaEnumType somEnumType, Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
Debug.Assert(somEnumType != null, "somEnumType != null");
Debug.Assert(newGlobalItems != null, "newGlobalItems != null");
Debug.Assert(somEnumType.UnderlyingType is Som.ScalarType, "At this point the underlying type should have already been validated and should be ScalarType");
Som.ScalarType enumUnderlyingType = (Som.ScalarType)somEnumType.UnderlyingType;
// note that enums don't live in SSpace so there is no need to GetDataSpace() for it.
EnumType enumType = new EnumType(somEnumType.Name,
somEnumType.Namespace,
enumUnderlyingType.Type,
somEnumType.IsFlags,
DataSpace.CSpace);
Type clrEnumUnderlyingType = enumUnderlyingType.Type.ClrEquivalentType;
foreach (var somEnumMember in somEnumType.EnumMembers)
{
Debug.Assert(somEnumMember.Value != null, "value must not be null at this point");
var enumMember = new EnumMember(somEnumMember.Name, Convert.ChangeType(somEnumMember.Value, clrEnumUnderlyingType, CultureInfo.InvariantCulture));
if (somEnumMember.Documentation != null)
{
enumMember.Documentation = ConvertToDocumentation(somEnumMember.Documentation);
}
AddOtherContent(somEnumMember, enumMember);
enumType.AddMember(enumMember);
}
if (somEnumType.Documentation != null)
{
enumType.Documentation = ConvertToDocumentation(somEnumType.Documentation);
}
AddOtherContent(somEnumType, enumType);
newGlobalItems.Add(somEnumType, enumType);
return enumType;
}
/// <summary>
/// Converts an SOM Documentation node to a metadata Documentation construct
/// </summary>
/// <param name="element">The SOM element to process</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
/// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
/// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
/// <returns>The Documentation object resulting from the convert operation</returns>
private static Documentation ConvertToDocumentation(Som.DocumentationElement element)
{
Debug.Assert(null != element, "ConvertToDocumentation cannot be invoked with a null Som.Documentation element");
return element.MetadataDocumentation;
}
private static TypeUsage GetFunctionTypeUsage(bool isModelFunction,
Som.Function somFunction,
Som.FacetEnabledSchemaElement somParameter,
DbProviderManifest providerManifest,
bool areConvertingForProviderManifest,
Som.SchemaType type,
CollectionKind collectionKind,
bool isRefType,
Som.SchemaElement schemaElement,
ConversionCache convertedItemCache,
Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
{
if (null != somParameter && areConvertingForProviderManifest
&& somParameter.HasUserDefinedFacets)
{
return somParameter.TypeUsage;
}
if (null == type)
{
if (isModelFunction && somParameter != null && somParameter is Som.Parameter)
{
((Som.Parameter)somParameter).ResolveNestedTypeNames(convertedItemCache, newGlobalItems);
return somParameter.TypeUsage;
}
else if (somParameter != null && somParameter is Som.ReturnType)
{
((Som.ReturnType)somParameter).ResolveNestedTypeNames(convertedItemCache, newGlobalItems);
return somParameter.TypeUsage;
}
else
{
return null;
}
}
EdmType edmType;
if (!areConvertingForProviderManifest)
{
// SOM verifies the type is either scalar, row, or entity
Som.ScalarType scalarType = type as Som.ScalarType;
if (null != scalarType)
{
if (isModelFunction && somParameter != null)
{
if (somParameter.TypeUsage == null)
{
somParameter.ValidateAndSetTypeUsage(scalarType);
}
return somParameter.TypeUsage;
}
else if (isModelFunction)
{
Som.ModelFunction modelFunction = somFunction as Som.ModelFunction;
if (modelFunction.TypeUsage == null)
{
modelFunction.ValidateAndSetTypeUsage(scalarType);
}
return modelFunction.TypeUsage;
}
else if (somParameter != null && somParameter.HasUserDefinedFacets && somFunction.Schema.DataModel == System.Data.EntityModel.SchemaObjectModel.SchemaDataModelOption.ProviderDataModel)
{
somParameter.ValidateAndSetTypeUsage(scalarType);
return somParameter.TypeUsage;
}
else
{
edmType = GetPrimitiveType(scalarType, providerManifest);
}
}
else
{
edmType = (EdmType)LoadSchemaElement(type,
providerManifest,
convertedItemCache,
newGlobalItems);
// Neither FunctionImport nor its Parameters can have facets when defined in CSDL so for enums,
// since they are only a CSpace concept, we need to process facets only on model functions
if (isModelFunction && type is Som.SchemaEnumType)
{
Debug.Assert(somFunction.Schema.DataModel == Som.SchemaDataModelOption.EntityDataModel, "Enums live only in CSpace");
if (somParameter != null)
{
somParameter.ValidateAndSetTypeUsage(edmType);
return somParameter.TypeUsage;
}
else if (somFunction != null)
{
var modelFunction = ((Som.ModelFunction)somFunction);
modelFunction.ValidateAndSetTypeUsage(edmType);
return modelFunction.TypeUsage;
}
else
{
Debug.Fail("Should never get here.");
}
}
}
}
else if (type is Som.TypeElement)
{
Som.TypeElement typeElement = type as Som.TypeElement;
edmType = typeElement.PrimitiveType;
}
else
{
Som.ScalarType typeElement = type as Som.ScalarType;
edmType = typeElement.Type;
}
//Construct type usage
TypeUsage usage;
if (collectionKind != CollectionKind.None)
{
usage = convertedItemCache.GetCollectionTypeUsageWithNullFacets(edmType);
}
else
{
if (edmType is EntityType && isRefType)
{
usage = TypeUsage.Create(new RefType(edmType as EntityType));
}
else
{
usage = convertedItemCache.GetTypeUsageWithNullFacets(edmType);
}
}
return usage;
}
/// <summary>
/// Converts the ParameterDirection into a ParameterMode
/// </summary>
/// <param name="parameterDirection">The ParameterDirection to convert</param>
/// <returns>ParameterMode</returns>
private static ParameterMode GetParameterMode(ParameterDirection parameterDirection)
{
Debug.Assert(
parameterDirection == ParameterDirection.Input
|| parameterDirection == ParameterDirection.InputOutput
|| parameterDirection == ParameterDirection.Output,
"Inconsistent metadata error");
switch (parameterDirection)
{
case ParameterDirection.Input:
return ParameterMode.In;
case ParameterDirection.Output:
return ParameterMode.Out;
case ParameterDirection.InputOutput:
default:
return ParameterMode.InOut;
}
}
/// <summary>
/// Apply the facet values
/// </summary>
/// <param name="sourceType">The source TypeUsage</param>
/// <param name="targetType">The primitive or enum type of the target</param>
private static void ApplyTypePropertyFacets(TypeUsage sourceType, ref TypeUsage targetType)
{
Dictionary<string, Facet> newFacets = targetType.Facets.ToDictionary(f => f.Name);
bool madeChange = false;
foreach (Facet sourceFacet in sourceType.Facets)
{
Facet targetFacet;
if (newFacets.TryGetValue(sourceFacet.Name, out targetFacet))
{
if (!targetFacet.Description.IsConstant)
{
madeChange = true;
newFacets[targetFacet.Name] = Facet.Create(targetFacet.Description, sourceFacet.Value);
}
}
else
{
madeChange = true;
newFacets.Add(sourceFacet.Name, sourceFacet);
}
}
if (madeChange)
{
targetType = TypeUsage.Create(targetType.EdmType, newFacets.Values);
}
}
/// <summary>
/// Populate the facets on the TypeUsage object for a property
/// </summary>
/// <param name="somProperty">The property containing the information</param>
/// <param name="propertyTypeUsage">The type usage object where to populate facet</param>
/// <param name="providerManifest">The provider manifest to be used for conversion</param>
private static void PopulateGeneralFacets(Som.StructuredProperty somProperty,
DbProviderManifest providerManifest,
ref TypeUsage propertyTypeUsage)
{
bool madeChanges = false;
Dictionary<string, Facet> facets = propertyTypeUsage.Facets.ToDictionary(f => f.Name);
if (!somProperty.Nullable)
{
facets[DbProviderManifest.NullableFacetName] = Facet.Create(MetadataItem.NullableFacetDescription, false);
madeChanges = true;
}
if (somProperty.Default != null)
{
facets[DbProviderManifest.DefaultValueFacetName] = Facet.Create(MetadataItem.DefaultValueFacetDescription, somProperty.DefaultAsObject);
madeChanges = true;
}
//This is not really a general facet
//If we are dealing with a 1.1 Schema, Add a facet for CollectionKind
if (somProperty.Schema.SchemaVersion == XmlConstants.EdmVersionForV1_1)
{
Facet newFacet = Facet.Create(MetadataItem.CollectionKindFacetDescription, somProperty.CollectionKind);
facets.Add(newFacet.Name, newFacet);
madeChanges = true;
}
if (madeChanges)
{
propertyTypeUsage = TypeUsage.Create(propertyTypeUsage.EdmType, facets.Values);
}
}
private static DataSpace GetDataSpace(DbProviderManifest providerManifest)
{
Debug.Assert(providerManifest != null, "null provider manifest will be consider as SSpace");
// Target attributes is for types and sets in target space.
if (providerManifest is EdmProviderManifest)
{
return DataSpace.CSpace;
}
else
{
return DataSpace.SSpace;
}
}
/// <summary>
/// Get a primitive type when converting a CSDL schema
/// </summary>
/// <param name="scalarType">The schema type representing the primitive type</param>
/// <param name="providerManifest">The provider manifest for retrieving the store types</param>
private static PrimitiveType GetPrimitiveType(Som.ScalarType scalarType,
DbProviderManifest providerManifest)
{
PrimitiveType returnValue = null;
string scalarTypeName = scalarType.Name;
foreach (PrimitiveType primitiveType in providerManifest.GetStoreTypes())
{
if (primitiveType.Name == scalarTypeName)
{
returnValue = primitiveType;
break;
}
}
Debug.Assert(scalarType != null, "Som scalar type should always resolve to a primitive type");
return returnValue;
}
// This will update the sentinel values in the facets if required
private static void UpdateSentinelValuesInFacets(ref TypeUsage typeUsage)
{
// For string and decimal types, replace the sentinel by the max possible value
PrimitiveType primitiveType = (PrimitiveType)typeUsage.EdmType;
if (primitiveType.PrimitiveTypeKind == PrimitiveTypeKind.String ||
primitiveType.PrimitiveTypeKind == PrimitiveTypeKind.Binary)
{
Facet maxLengthFacet = typeUsage.Facets[EdmProviderManifest.MaxLengthFacetName];
if (Helper.IsUnboundedFacetValue(maxLengthFacet))
{
typeUsage = typeUsage.ShallowCopy(
new FacetValues
{
MaxLength = Helper.GetFacet(primitiveType.FacetDescriptions,
EdmProviderManifest.MaxLengthFacetName).MaxValue
});
}
}
}
#endregion
#region Nested types
/// <summary>
/// Cache containing item collection and type usages to support looking up and generating
/// metadata types.
/// </summary>
internal class ConversionCache
{
#region Fields
internal readonly ItemCollection ItemCollection;
private readonly Dictionary<EdmType, TypeUsage> _nullFacetsTypeUsage;
private readonly Dictionary<EdmType, TypeUsage> _nullFacetsCollectionTypeUsage;
#endregion
#region Constructors
internal ConversionCache(ItemCollection itemCollection)
{
this.ItemCollection = itemCollection;
this._nullFacetsTypeUsage = new Dictionary<EdmType, TypeUsage>();
this._nullFacetsCollectionTypeUsage = new Dictionary<EdmType, TypeUsage>();
}
#endregion
#region Methods
/// <summary>
/// Gets type usage for the given type with null facet values. Caches usage to avoid creating
/// redundant type usages.
/// </summary>
internal TypeUsage GetTypeUsageWithNullFacets(EdmType edmType)
{
// check for cached result
TypeUsage result;
if (_nullFacetsTypeUsage.TryGetValue(edmType, out result))
{
return result;
}
// construct result
result = TypeUsage.Create(edmType, FacetValues.NullFacetValues);
// cache result
_nullFacetsTypeUsage.Add(edmType, result);
return result;
}
/// <summary>
/// Gets collection type usage for the given type with null facet values. Caches usage to avoid creating
/// redundant type usages.
/// </summary>
internal TypeUsage GetCollectionTypeUsageWithNullFacets(EdmType edmType)
{
// check for cached result
TypeUsage result;
if (_nullFacetsCollectionTypeUsage.TryGetValue(edmType, out result))
{
return result;
}
// construct collection type from cached element type
TypeUsage elementTypeUsage = GetTypeUsageWithNullFacets(edmType);
result = TypeUsage.Create(new CollectionType(elementTypeUsage), FacetValues.NullFacetValues);
// cache result
_nullFacetsCollectionTypeUsage.Add(edmType, result);
return result;
}
#endregion
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.ComponentModel.DataAnnotations.Tests
{
public class RangeAttributeTests : ValidationAttributeTestBase
{
protected override IEnumerable<TestCase> ValidValues()
{
RangeAttribute intRange = new RangeAttribute(1, 3);
yield return new TestCase(intRange, null);
yield return new TestCase(intRange, string.Empty);
yield return new TestCase(intRange, 1);
yield return new TestCase(intRange, 2);
yield return new TestCase(intRange, 3);
yield return new TestCase(new RangeAttribute(1, 1), 1);
RangeAttribute doubleRange = new RangeAttribute(1.0, 3.0);
yield return new TestCase(doubleRange, null);
yield return new TestCase(doubleRange, string.Empty);
yield return new TestCase(doubleRange, 1.0);
yield return new TestCase(doubleRange, 2.0);
yield return new TestCase(doubleRange, 3.0);
yield return new TestCase(new RangeAttribute(1.0, 1.0), 1);
RangeAttribute stringIntRange = new RangeAttribute(typeof(int), "1", "3");
yield return new TestCase(stringIntRange, null);
yield return new TestCase(stringIntRange, string.Empty);
yield return new TestCase(stringIntRange, 1);
yield return new TestCase(stringIntRange, "1");
yield return new TestCase(stringIntRange, 2);
yield return new TestCase(stringIntRange, "2");
yield return new TestCase(stringIntRange, 3);
yield return new TestCase(stringIntRange, "3");
RangeAttribute stringDoubleRange = new RangeAttribute(typeof(double), (1.0).ToString("F1"), (3.0).ToString("F1"));
yield return new TestCase(stringDoubleRange, null);
yield return new TestCase(stringDoubleRange, string.Empty);
yield return new TestCase(stringDoubleRange, 1.0);
yield return new TestCase(stringDoubleRange, (1.0).ToString("F1"));
yield return new TestCase(stringDoubleRange, 2.0);
yield return new TestCase(stringDoubleRange, (2.0).ToString("F1"));
yield return new TestCase(stringDoubleRange, 3.0);
yield return new TestCase(stringDoubleRange, (3.0).ToString("F1"));
}
protected override IEnumerable<TestCase> InvalidValues()
{
RangeAttribute intRange = new RangeAttribute(1, 3);
yield return new TestCase(intRange, 0);
yield return new TestCase(intRange, 4);
yield return new TestCase(intRange, "abc");
yield return new TestCase(intRange, new object());
// Implements IConvertible (throws NotSupportedException - is caught)
yield return new TestCase(intRange, new IConvertibleImplementor() { IntThrow = new NotSupportedException() });
RangeAttribute doubleRange = new RangeAttribute(1.0, 3.0);
yield return new TestCase(doubleRange, 0.9999999);
yield return new TestCase(doubleRange, 3.0000001);
yield return new TestCase(doubleRange, "abc");
yield return new TestCase(doubleRange, new object());
// Implements IConvertible (throws NotSupportedException - is caught)
yield return new TestCase(doubleRange, new IConvertibleImplementor() { DoubleThrow = new NotSupportedException() });
RangeAttribute stringIntRange = new RangeAttribute(typeof(int), "1", "3");
yield return new TestCase(stringIntRange, 0);
yield return new TestCase(stringIntRange, "0");
yield return new TestCase(stringIntRange, 4);
yield return new TestCase(stringIntRange, "4");
yield return new TestCase(stringIntRange, new object());
// Implements IConvertible (throws NotSupportedException - is caught)
yield return new TestCase(stringIntRange, new IConvertibleImplementor() { IntThrow = new NotSupportedException() });
RangeAttribute stringDoubleRange = new RangeAttribute(typeof(double), (1.0).ToString("F1"), (3.0).ToString("F1"));
yield return new TestCase(stringDoubleRange, 0.9999999);
yield return new TestCase(stringDoubleRange, (0.9999999).ToString());
yield return new TestCase(stringDoubleRange, 3.0000001);
yield return new TestCase(stringDoubleRange, (3.0000001).ToString());
yield return new TestCase(stringDoubleRange, new object());
// Implements IConvertible (throws NotSupportedException - is caught)
yield return new TestCase(stringDoubleRange, new IConvertibleImplementor() { DoubleThrow = new NotSupportedException() });
}
[Theory]
[InlineData(typeof(int), "1", "3")]
[InlineData(typeof(double), "1", "3")]
public static void Validate_CantConvertValueToTargetType_ThrowsException(Type type, string minimum, string maximum)
{
var attribute = new RangeAttribute(type, minimum, maximum);
AssertExtensions.Throws<ArgumentException, Exception>(() => attribute.Validate("abc", new ValidationContext(new object())));
AssertExtensions.Throws<ArgumentException, Exception>(() => attribute.IsValid("abc"));
}
[Fact]
public static void Ctor_Int_Int()
{
var attribute = new RangeAttribute(1, 3);
Assert.Equal(1, attribute.Minimum);
Assert.Equal(3, attribute.Maximum);
Assert.Equal(typeof(int), attribute.OperandType);
}
[Fact]
public static void Ctor_Double_Double()
{
var attribute = new RangeAttribute(1.0, 3.0);
Assert.Equal(1.0, attribute.Minimum);
Assert.Equal(3.0, attribute.Maximum);
Assert.Equal(typeof(double), attribute.OperandType);
}
[Theory]
[InlineData(null)]
[InlineData(typeof(object))]
public static void Ctor_Type_String_String(Type type)
{
var attribute = new RangeAttribute(type, "SomeMinimum", "SomeMaximum");
Assert.Equal("SomeMinimum", attribute.Minimum);
Assert.Equal("SomeMaximum", attribute.Maximum);
Assert.Equal(type, attribute.OperandType);
}
[Theory]
[InlineData(null)]
[InlineData(typeof(object))]
public static void Validate_InvalidOperandType_ThrowsInvalidOperationException(Type type)
{
var attribute = new RangeAttribute(type, "someMinimum", "someMaximum");
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
}
[Fact]
public static void Validate_MinimumGreaterThanMaximum_ThrowsInvalidOperationException()
{
var attribute = new RangeAttribute(3, 1);
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
attribute = new RangeAttribute(3.0, 1.0);
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
attribute = new RangeAttribute(typeof(int), "3", "1");
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
attribute = new RangeAttribute(typeof(double), (3.0).ToString("F1"), (1.0).ToString("F1"));
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
attribute = new RangeAttribute(typeof(string), "z", "a");
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
}
[Theory]
[InlineData(null, "3")]
[InlineData("3", null)]
public static void Validate_MinimumOrMaximumNull_ThrowsInvalidOperationException(string minimum, string maximum)
{
RangeAttribute attribute = new RangeAttribute(typeof(int), minimum, maximum);
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
}
[Theory]
[InlineData(typeof(int), "Cannot Convert", "3")]
[InlineData(typeof(int), "1", "Cannot Convert")]
[InlineData(typeof(double), "Cannot Convert", "3")]
[InlineData(typeof(double), "1", "Cannot Convert")]
public static void Validate_MinimumOrMaximumCantBeConvertedToIntegralType_ThrowsException(Type type, string minimum, string maximum)
{
RangeAttribute attribute = new RangeAttribute(type, minimum, maximum);
AssertExtensions.Throws<ArgumentException, Exception>(() => attribute.Validate("Any", new ValidationContext(new object())));
}
[Theory]
[InlineData(typeof(DateTime), "Cannot Convert", "2014-03-19")]
[InlineData(typeof(DateTime), "2014-03-19", "Cannot Convert")]
public static void Validate_MinimumOrMaximumCantBeConvertedToDateTime_ThrowsFormatException(Type type, string minimum, string maximum)
{
RangeAttribute attribute = new RangeAttribute(type, minimum, maximum);
Assert.Throws<FormatException>(() => attribute.Validate("Any", new ValidationContext(new object())));
}
[Theory]
[InlineData(1, 2, "2147483648")]
[InlineData(1, 2, "-2147483649")]
public static void Validate_IntConversionOverflows_ThrowsOverflowException(int minimum, int maximum, object value)
{
RangeAttribute attribute = new RangeAttribute(minimum, maximum);
Assert.Throws<OverflowException>(() => attribute.Validate(value, new ValidationContext(new object())));
}
[Theory]
[InlineData(1.0, 2.0, "2E+308")]
[InlineData(1.0, 2.0, "-2E+308")]
public static void Validate_DoubleConversionOverflows_ThrowsOverflowException(double minimum, double maximum, object value)
{
RangeAttribute attribute = new RangeAttribute(minimum, maximum);
Assert.Throws<OverflowException>(() => attribute.Validate(value, new ValidationContext(new object())));
}
[Fact]
public static void Validate_IConvertibleThrowsCustomException_IsNotCaught()
{
RangeAttribute attribute = new RangeAttribute(typeof(int), "1", "1");
Assert.Throws<ValidationException>(() => attribute.Validate(new IConvertibleImplementor() { IntThrow = new ArithmeticException() }, new ValidationContext(new object())));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using Avalonia.Collections;
using Avalonia.Data;
using Avalonia.Logging;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Metadata;
using Avalonia.Rendering;
using Avalonia.Utilities;
using Avalonia.VisualTree;
#nullable enable
namespace Avalonia
{
/// <summary>
/// Base class for controls that provides rendering and related visual properties.
/// </summary>
/// <remarks>
/// The <see cref="Visual"/> class represents elements that have a visual on-screen
/// representation and stores all the information needed for an
/// <see cref="IRenderer"/> to render the control. To traverse the visual tree, use the
/// extension methods defined in <see cref="VisualExtensions"/>.
/// </remarks>
[UsableDuringInitialization]
public class Visual : StyledElement, IVisual
{
/// <summary>
/// Defines the <see cref="Bounds"/> property.
/// </summary>
public static readonly DirectProperty<Visual, Rect> BoundsProperty =
AvaloniaProperty.RegisterDirect<Visual, Rect>(nameof(Bounds), o => o.Bounds);
public static readonly DirectProperty<Visual, TransformedBounds?> TransformedBoundsProperty =
AvaloniaProperty.RegisterDirect<Visual, TransformedBounds?>(
nameof(TransformedBounds),
o => o.TransformedBounds);
/// <summary>
/// Defines the <see cref="ClipToBounds"/> property.
/// </summary>
public static readonly StyledProperty<bool> ClipToBoundsProperty =
AvaloniaProperty.Register<Visual, bool>(nameof(ClipToBounds));
/// <summary>
/// Defines the <see cref="Clip"/> property.
/// </summary>
public static readonly StyledProperty<Geometry?> ClipProperty =
AvaloniaProperty.Register<Visual, Geometry?>(nameof(Clip));
/// <summary>
/// Defines the <see cref="IsVisibleProperty"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsVisibleProperty =
AvaloniaProperty.Register<Visual, bool>(nameof(IsVisible), true);
/// <summary>
/// Defines the <see cref="Opacity"/> property.
/// </summary>
public static readonly StyledProperty<double> OpacityProperty =
AvaloniaProperty.Register<Visual, double>(nameof(Opacity), 1);
/// <summary>
/// Defines the <see cref="OpacityMask"/> property.
/// </summary>
public static readonly StyledProperty<IBrush?> OpacityMaskProperty =
AvaloniaProperty.Register<Visual, IBrush?>(nameof(OpacityMask));
/// <summary>
/// Defines the <see cref="RenderTransform"/> property.
/// </summary>
public static readonly StyledProperty<ITransform?> RenderTransformProperty =
AvaloniaProperty.Register<Visual, ITransform?>(nameof(RenderTransform));
/// <summary>
/// Defines the <see cref="RenderTransformOrigin"/> property.
/// </summary>
public static readonly StyledProperty<RelativePoint> RenderTransformOriginProperty =
AvaloniaProperty.Register<Visual, RelativePoint>(nameof(RenderTransformOrigin), defaultValue: RelativePoint.Center);
/// <summary>
/// Defines the <see cref="IVisual.VisualParent"/> property.
/// </summary>
public static readonly DirectProperty<Visual, IVisual?> VisualParentProperty =
AvaloniaProperty.RegisterDirect<Visual, IVisual?>(nameof(IVisual.VisualParent), o => o._visualParent);
/// <summary>
/// Defines the <see cref="ZIndex"/> property.
/// </summary>
public static readonly StyledProperty<int> ZIndexProperty =
AvaloniaProperty.Register<Visual, int>(nameof(ZIndex));
private Rect _bounds;
private TransformedBounds? _transformedBounds;
private IRenderRoot? _visualRoot;
private IVisual? _visualParent;
/// <summary>
/// Initializes static members of the <see cref="Visual"/> class.
/// </summary>
static Visual()
{
AffectsRender<Visual>(
BoundsProperty,
ClipProperty,
ClipToBoundsProperty,
IsVisibleProperty,
OpacityProperty);
RenderTransformProperty.Changed.Subscribe(RenderTransformChanged);
ZIndexProperty.Changed.Subscribe(ZIndexChanged);
}
/// <summary>
/// Initializes a new instance of the <see cref="Visual"/> class.
/// </summary>
public Visual()
{
// Disable transitions until we're added to the visual tree.
DisableTransitions();
var visualChildren = new AvaloniaList<IVisual>();
visualChildren.ResetBehavior = ResetBehavior.Remove;
visualChildren.Validate = visual => ValidateVisualChild(visual);
visualChildren.CollectionChanged += VisualChildrenChanged;
VisualChildren = visualChildren;
}
/// <summary>
/// Raised when the control is attached to a rooted visual tree.
/// </summary>
public event EventHandler<VisualTreeAttachmentEventArgs>? AttachedToVisualTree;
/// <summary>
/// Raised when the control is detached from a rooted visual tree.
/// </summary>
public event EventHandler<VisualTreeAttachmentEventArgs>? DetachedFromVisualTree;
/// <summary>
/// Gets the bounds of the control relative to its parent.
/// </summary>
public Rect Bounds
{
get { return _bounds; }
protected set { SetAndRaise(BoundsProperty, ref _bounds, value); }
}
/// <summary>
/// Gets the bounds of the control relative to the window, accounting for rendering transforms.
/// </summary>
public TransformedBounds? TransformedBounds => _transformedBounds;
/// <summary>
/// Gets or sets a value indicating whether the control should be clipped to its bounds.
/// </summary>
public bool ClipToBounds
{
get { return GetValue(ClipToBoundsProperty); }
set { SetValue(ClipToBoundsProperty, value); }
}
/// <summary>
/// Gets or sets the geometry clip for this visual.
/// </summary>
public Geometry? Clip
{
get { return GetValue(ClipProperty); }
set { SetValue(ClipProperty, value); }
}
/// <summary>
/// Gets a value indicating whether this control and all its parents are visible.
/// </summary>
public bool IsEffectivelyVisible
{
get
{
IVisual? node = this;
while (node != null)
{
if (!node.IsVisible)
{
return false;
}
node = node.VisualParent;
}
return true;
}
}
/// <summary>
/// Gets or sets a value indicating whether this control is visible.
/// </summary>
public bool IsVisible
{
get { return GetValue(IsVisibleProperty); }
set { SetValue(IsVisibleProperty, value); }
}
/// <summary>
/// Gets or sets the opacity of the control.
/// </summary>
public double Opacity
{
get { return GetValue(OpacityProperty); }
set { SetValue(OpacityProperty, value); }
}
/// <summary>
/// Gets or sets the opacity mask of the control.
/// </summary>
public IBrush? OpacityMask
{
get { return GetValue(OpacityMaskProperty); }
set { SetValue(OpacityMaskProperty, value); }
}
/// <summary>
/// Gets or sets the render transform of the control.
/// </summary>
public ITransform? RenderTransform
{
get { return GetValue(RenderTransformProperty); }
set { SetValue(RenderTransformProperty, value); }
}
/// <summary>
/// Gets or sets the transform origin of the control.
/// </summary>
public RelativePoint RenderTransformOrigin
{
get { return GetValue(RenderTransformOriginProperty); }
set { SetValue(RenderTransformOriginProperty, value); }
}
/// <summary>
/// Gets or sets the Z index of the control.
/// </summary>
/// <remarks>
/// Controls with a higher <see cref="ZIndex"/> will appear in front of controls with
/// a lower ZIndex. If two controls have the same ZIndex then the control that appears
/// later in the containing element's children collection will appear on top.
/// </remarks>
public int ZIndex
{
get { return GetValue(ZIndexProperty); }
set { SetValue(ZIndexProperty, value); }
}
/// <summary>
/// Gets the control's child visuals.
/// </summary>
protected IAvaloniaList<IVisual> VisualChildren
{
get;
private set;
}
/// <summary>
/// Gets the root of the visual tree, if the control is attached to a visual tree.
/// </summary>
protected IRenderRoot? VisualRoot => _visualRoot ?? (this as IRenderRoot);
/// <summary>
/// Gets a value indicating whether this control is attached to a visual root.
/// </summary>
bool IVisual.IsAttachedToVisualTree => VisualRoot != null;
/// <summary>
/// Gets the control's child controls.
/// </summary>
IAvaloniaReadOnlyList<IVisual> IVisual.VisualChildren => VisualChildren;
/// <summary>
/// Gets the control's parent visual.
/// </summary>
IVisual? IVisual.VisualParent => _visualParent;
/// <summary>
/// Gets the root of the visual tree, if the control is attached to a visual tree.
/// </summary>
IRenderRoot? IVisual.VisualRoot => VisualRoot;
TransformedBounds? IVisual.TransformedBounds
{
get { return _transformedBounds; }
set { SetAndRaise(TransformedBoundsProperty, ref _transformedBounds, value); }
}
/// <summary>
/// Invalidates the visual and queues a repaint.
/// </summary>
public void InvalidateVisual()
{
VisualRoot?.Renderer?.AddDirty(this);
}
/// <summary>
/// Renders the visual to a <see cref="DrawingContext"/>.
/// </summary>
/// <param name="context">The drawing context.</param>
public virtual void Render(DrawingContext context)
{
Contract.Requires<ArgumentNullException>(context != null);
}
/// <summary>
/// Indicates that a property change should cause <see cref="InvalidateVisual"/> to be
/// called.
/// </summary>
/// <param name="properties">The properties.</param>
/// <remarks>
/// This method should be called in a control's static constructor with each property
/// on the control which when changed should cause a redraw. This is similar to WPF's
/// FrameworkPropertyMetadata.AffectsRender flag.
/// </remarks>
[Obsolete("Use AffectsRender<T> and specify the control type.")]
protected static void AffectsRender(params AvaloniaProperty[] properties)
{
AffectsRender<Visual>(properties);
}
/// <summary>
/// Indicates that a property change should cause <see cref="InvalidateVisual"/> to be
/// called.
/// </summary>
/// <typeparam name="T">The control which the property affects.</typeparam>
/// <param name="properties">The properties.</param>
/// <remarks>
/// This method should be called in a control's static constructor with each property
/// on the control which when changed should cause a redraw. This is similar to WPF's
/// FrameworkPropertyMetadata.AffectsRender flag.
/// </remarks>
protected static void AffectsRender<T>(params AvaloniaProperty[] properties)
where T : Visual
{
static void Invalidate(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is T sender)
{
sender.InvalidateVisual();
}
}
static void InvalidateAndSubscribe(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is T sender)
{
if (e.OldValue is IAffectsRender oldValue)
{
WeakEventHandlerManager.Unsubscribe<EventArgs, T>(oldValue, nameof(oldValue.Invalidated), sender.AffectsRenderInvalidated);
}
if (e.NewValue is IAffectsRender newValue)
{
WeakEventHandlerManager.Subscribe<IAffectsRender, EventArgs, T>(newValue, nameof(newValue.Invalidated), sender.AffectsRenderInvalidated);
}
sender.InvalidateVisual();
}
}
foreach (var property in properties)
{
if (property.CanValueAffectRender())
{
property.Changed.Subscribe(e => InvalidateAndSubscribe(e));
}
else
{
property.Changed.Subscribe(e => Invalidate(e));
}
}
}
protected override void LogicalChildrenCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
base.LogicalChildrenCollectionChanged(sender, e);
VisualRoot?.Renderer?.RecalculateChildren(this);
}
/// <summary>
/// Calls the <see cref="OnAttachedToVisualTree(VisualTreeAttachmentEventArgs)"/> method
/// for this control and all of its visual descendants.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
Logger.TryGet(LogEventLevel.Verbose, LogArea.Visual)?.Log(this, "Attached to visual tree");
_visualRoot = e.Root;
if (RenderTransform is IMutableTransform mutableTransform)
{
mutableTransform.Changed += RenderTransformChanged;
}
EnableTransitions();
OnAttachedToVisualTree(e);
AttachedToVisualTree?.Invoke(this, e);
InvalidateVisual();
var visualChildren = VisualChildren;
if (visualChildren != null)
{
var visualChildrenCount = visualChildren.Count;
for (var i = 0; i < visualChildrenCount; i++)
{
if (visualChildren[i] is Visual child)
{
child.OnAttachedToVisualTreeCore(e);
}
}
}
}
/// <summary>
/// Calls the <see cref="OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs)"/> method
/// for this control and all of its visual descendants.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
Logger.TryGet(LogEventLevel.Verbose, LogArea.Visual)?.Log(this, "Detached from visual tree");
_visualRoot = null;
if (RenderTransform is IMutableTransform mutableTransform)
{
mutableTransform.Changed -= RenderTransformChanged;
}
DisableTransitions();
OnDetachedFromVisualTree(e);
DetachedFromVisualTree?.Invoke(this, e);
e.Root?.Renderer?.AddDirty(this);
var visualChildren = VisualChildren;
if (visualChildren != null)
{
var visualChildrenCount = visualChildren.Count;
for (var i = 0; i < visualChildrenCount; i++)
{
if (visualChildren[i] is Visual child)
{
child.OnDetachedFromVisualTreeCore(e);
}
}
}
}
/// <summary>
/// Called when the control is added to a rooted visual tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
}
/// <summary>
/// Called when the control is removed from a rooted visual tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
}
/// <summary>
/// Called when the control's visual parent changes.
/// </summary>
/// <param name="oldParent">The old visual parent.</param>
/// <param name="newParent">The new visual parent.</param>
protected virtual void OnVisualParentChanged(IVisual? oldParent, IVisual? newParent)
{
RaisePropertyChanged(
VisualParentProperty,
new Optional<IVisual?>(oldParent),
new BindingValue<IVisual?>(newParent),
BindingPriority.LocalValue);
}
protected internal sealed override void LogBindingError(AvaloniaProperty property, Exception e)
{
// Don't log a binding error unless the control is attached to a logical tree.
if (((ILogical)this).IsAttachedToLogicalTree)
{
if (e is BindingChainException b &&
string.IsNullOrEmpty(b.ExpressionErrorPoint) &&
DataContext == null)
{
// The error occurred at the root of the binding chain and DataContext is null;
// don't log this - the DataContext probably hasn't been set up yet.
return;
}
Logger.TryGet(LogEventLevel.Warning, LogArea.Binding)?.Log(
this,
"Error in binding to {Target}.{Property}: {Message}",
this,
property,
e.Message);
}
}
/// <summary>
/// Called when a visual's <see cref="RenderTransform"/> changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void RenderTransformChanged(AvaloniaPropertyChangedEventArgs e)
{
var sender = e.Sender as Visual;
if (sender?.VisualRoot != null)
{
var oldValue = e.OldValue as Transform;
var newValue = e.NewValue as Transform;
if (oldValue != null)
{
oldValue.Changed -= sender.RenderTransformChanged;
}
if (newValue != null)
{
newValue.Changed += sender.RenderTransformChanged;
}
sender.InvalidateVisual();
}
}
/// <summary>
/// Ensures a visual child is not null and not already parented.
/// </summary>
/// <param name="c">The visual child.</param>
private static void ValidateVisualChild(IVisual c)
{
if (c == null)
{
throw new ArgumentNullException(nameof(c), "Cannot add null to VisualChildren.");
}
if (c.VisualParent != null)
{
throw new InvalidOperationException("The control already has a visual parent.");
}
}
/// <summary>
/// Called when the <see cref="ZIndex"/> property changes on any control.
/// </summary>
/// <param name="e">The event args.</param>
private static void ZIndexChanged(AvaloniaPropertyChangedEventArgs e)
{
var sender = e.Sender as IVisual;
var parent = sender?.VisualParent;
sender?.InvalidateVisual();
parent?.VisualRoot?.Renderer?.RecalculateChildren(parent);
}
/// <summary>
/// Called when the <see cref="RenderTransform"/>'s <see cref="Transform.Changed"/> event
/// is fired.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event args.</param>
private void RenderTransformChanged(object sender, EventArgs e)
{
InvalidateVisual();
}
/// <summary>
/// Sets the visual parent of the Visual.
/// </summary>
/// <param name="value">The visual parent.</param>
private void SetVisualParent(Visual? value)
{
if (_visualParent == value)
{
return;
}
var old = _visualParent;
_visualParent = value;
if (_visualRoot != null)
{
var e = new VisualTreeAttachmentEventArgs(old, VisualRoot);
OnDetachedFromVisualTreeCore(e);
}
if (_visualParent is IRenderRoot || _visualParent?.IsAttachedToVisualTree == true)
{
var root = this.FindAncestorOfType<IRenderRoot>();
var e = new VisualTreeAttachmentEventArgs(_visualParent, root);
OnAttachedToVisualTreeCore(e);
}
OnVisualParentChanged(old, value);
}
private void AffectsRenderInvalidated(object sender, EventArgs e) => InvalidateVisual();
/// <summary>
/// Called when the <see cref="VisualChildren"/> collection changes.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event args.</param>
private void VisualChildrenChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
SetVisualParent(e.NewItems, this);
break;
case NotifyCollectionChangedAction.Remove:
SetVisualParent(e.OldItems, null);
break;
case NotifyCollectionChangedAction.Replace:
SetVisualParent(e.OldItems, null);
SetVisualParent(e.NewItems, this);
break;
}
}
private static void SetVisualParent(IList children, Visual? parent)
{
var count = children.Count;
for (var i = 0; i < count; i++)
{
var visual = (Visual) children[i];
visual.SetVisualParent(parent);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using FarseerGames.FarseerPhysics.Collisions;
using FarseerGames.FarseerPhysics.Interfaces;
#if (XNA)
using Microsoft.Xna.Framework;
#else
using FarseerGames.FarseerPhysics.Mathematics;
#endif
namespace FarseerGames.FarseerPhysics.Controllers
{
/// <summary>
/// FluidDragController applies fluid physics to the bodies within it. Things like fluid drag and fluid density
/// can be adjusted to give semi-realistic motion for bodies in fluid.
///
/// The FluidDragController does nothing to define or control the MOTION of the fluid itself. It simply knows
/// how to apply fluid forces to the bodies it contains.
///
/// In order for the FluidDragController to know when to apply forces and when not to apply forces, it needs to know
/// when a body enters it. This is done by supplying the FluidDragController with an <see cref="IFluidContainer"/> object.
///
/// <see cref="IFluidContainer"/> has two simple methods that need to be implemented. Intersect(AABB aabb), returns true if a given
/// AABB object intersects it, false otherwise. Contains(ref Vector2 vector) returns true if a given point is inside the
/// fluid container, false otherwise.
///
/// For a very simple example of a very simple fluid container. See the <see cref="AABBFluidContainer"/>. This represents a fluid container
/// in the shape of an AABB.
///
/// More complex fluid containers are where things get interesting. The <see cref="WaveController"/> object is an example of a complex
/// fluid container. The <see cref="WaveController"/> simulates wave motion. It's driven by an algorithm (not physics) which dynamically
/// alters a polygonal shape to mimic waves. Where it gets interesting is the <see cref="WaveController"/> also implements <see cref="IFluidContainer"/>. This allows
/// it to be used in conjunction with the FluidDragController. Anything that falls into the dynamically changing fluid container
/// defined by the <see cref="WaveController"/> will have fluid physics applied to it.
///
/// </summary>
public sealed class FluidDragController : Controller
{
#region Delegates
public delegate void EntryEventHandler(Geom geom, Vertices verts);
#endregion
private float _area;
private Vector2 _axis = Vector2.Zero;
private Vector2 _buoyancyForce = Vector2.Zero;
private Vector2 _centroid = Vector2.Zero;
private Vector2 _centroidVelocity;
private float _dragArea;
private IFluidContainer _fluidContainer;
private Dictionary<Geom, bool> _geomInFluidList;
private List<Geom> _geomList;
private Vector2 _gravity = Vector2.Zero;
private Vector2 _linearDragForce = Vector2.Zero;
private float _max;
private float _min;
private float _partialMass;
private float _rotationalDragTorque;
private float _totalArea;
private Vector2 _totalForce;
private Vector2 _vert;
private Vertices _vertices;
public EntryEventHandler Entry;
public FluidDragController()
{
_geomList = new List<Geom>();
_geomInFluidList = new Dictionary<Geom, bool>();
}
/// <summary>
/// Density of the fluid. Higher values will make things more buoyant, lower values will cause things to sink.
/// </summary>
public float Density { get; set; }
/// <summary>
/// Controls the linear drag that the fluid exerts on the bodies within it. Use higher values will simulate thick fluid, like honey, lower values to
/// simulate water-like fluids.
/// </summary>
public float LinearDragCoefficient { get; set; }
/// <summary>
/// Controls the rotational drag that the fluid exerts on the bodies within it. Use higher values will simulate thick fluid, like honey, lower values to
/// simulate water-like fluids.
/// </summary>
public float RotationalDragCoefficient { get; set; }
/// <summary>
/// Initializes the fluid drag controller
/// </summary>
/// <param name="fluidContainer">An object that implements <see cref="IFluidContainer"/></param>
/// <param name="density">Density of the fluid</param>
/// <param name="linearDragCoefficient">Linear drag coefficient of the fluid</param>
/// <param name="rotationalDragCoefficient">Rotational drag coefficient of the fluid</param>
/// <param name="gravity">The direction gravity acts. Buoyancy force will act in opposite direction of gravity.</param>
public void Initialize(IFluidContainer fluidContainer, float density, float linearDragCoefficient,
float rotationalDragCoefficient, Vector2 gravity)
{
_fluidContainer = fluidContainer;
Density = density;
LinearDragCoefficient = linearDragCoefficient;
RotationalDragCoefficient = rotationalDragCoefficient;
_gravity = gravity;
_vertices = new Vertices();
}
/// <summary>
/// Add a geom to be controlled by the fluid drag controller. The geom does not need to already be in
/// the fluid to add it to the controller. By calling this method you are telling the fluid drag controller
/// to watch this geom and it if enters my fluid container, apply the fluid physics.
/// </summary>
/// <param name="geom">The geom to be added.</param>
public void AddGeom(Geom geom)
{
_geomList.Add(geom);
_geomInFluidList.Add(geom, false);
}
/// <summary>
/// Removes a geometry from the fluid drag controller.
/// </summary>
/// <param name="geom">The geom.</param>
public void RemoveGeom(Geom geom)
{
_geomList.Remove(geom);
_geomInFluidList.Remove(geom);
}
public override void Validate()
{
//do nothing
}
/// <summary>
/// Resets the fluid drag controller
/// </summary>
public void Reset()
{
_geomInFluidList.Clear();
for (int i = 0; i < _geomList.Count; i++)
{
_geomInFluidList.Add(_geomList[i], false);
}
}
public override void Update(float dt, float dtReal)
{
for (int i = 0; i < _geomList.Count; i++)
{
_totalArea = _geomList[i].localVertices.GetArea();
//If the AABB of the geometry does not intersect the fluidcontainer
//continue to the next geometry
if (!_fluidContainer.Intersect(_geomList[i].AABB))
continue;
//Find the vertices contained in the fluidcontainer
FindVerticesInFluid(_geomList[i]);
//The geometry is not in the fluid, up til a certain point.
if (_vertices.Count < _geomList[i].LocalVertices.Count * 0.15f)
_geomInFluidList[_geomList[i]] = false;
_area = _vertices.GetArea();
if (_area < .000001)
continue;
_centroid = _vertices.GetCentroid(_area);
//Calculate buoyancy force
_buoyancyForce = -_gravity * _area * Density;
//Calculate linear and rotational drag
CalculateDrag(_geomList[i]);
//Add the buoyancy force and lienar drag force
Vector2.Add(ref _buoyancyForce, ref _linearDragForce, out _totalForce);
//Apply total force to the body
_geomList[i].body.ApplyForceAtWorldPoint(ref _totalForce, ref _centroid);
//Apply rotational drag
_geomList[i].body.ApplyTorque(_rotationalDragTorque);
if (_geomInFluidList[_geomList[i]] == false)
{
//The geometry is now in the water. Fire the Entry event
_geomInFluidList[_geomList[i]] = true;
if (Entry != null)
{
Entry(_geomList[i], _vertices);
}
}
}
}
/// <summary>
/// Finds what vertices of the geometry that is inside the fluidcontainer
/// </summary>
/// <param name="geom">The geometry to check against</param>
private void FindVerticesInFluid(Geom geom)
{
_vertices.Clear();
for (int i = 0; i < geom.worldVertices.Count; i++)
{
_vert = geom.worldVertices[i];
if (_fluidContainer.Contains(ref _vert))
{
_vertices.Add(_vert);
}
}
}
/// <summary>
/// Calculates the linear and rotational drag of the geometry
/// </summary>
/// <param name="geom">The geometry</param>
private void CalculateDrag(Geom geom)
{
//localCentroid = geom.body.GetLocalPosition(_centroid);
geom.body.GetVelocityAtWorldPoint(ref _centroid, out _centroidVelocity);
_axis.X = -_centroidVelocity.Y;
_axis.Y = _centroidVelocity.X;
//can't normalize a zero length vector
if (_axis.X != 0 || _axis.Y != 0)
_axis.Normalize();
_vertices.ProjectToAxis(ref _axis, out _min, out _max);
_dragArea = Math.Abs(_max - _min);
_partialMass = geom.body.mass * (_area / _totalArea);
_linearDragForce = -.5f * Density * _dragArea * LinearDragCoefficient * _partialMass * _centroidVelocity;
_rotationalDragTorque = -geom.body.AngularVelocity * RotationalDragCoefficient * _partialMass;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Interfaces;
namespace OpenSim.Region.CoreModules.World.Terrain.PaintBrushes
{
/// <summary>
/// Thermal Weathering Paint Brush
/// </summary>
public class WeatherSphere : ITerrainPaintableEffect
{
private const double talus = 0.2;
private const NeighbourSystem type = NeighbourSystem.Moore;
#region Supporting Functions
private static int[] Neighbours(NeighbourSystem neighbourType, int index)
{
int[] coord = new int[2];
index++;
switch (neighbourType)
{
case NeighbourSystem.Moore:
switch (index)
{
case 1:
coord[0] = -1;
coord[1] = -1;
break;
case 2:
coord[0] = -0;
coord[1] = -1;
break;
case 3:
coord[0] = +1;
coord[1] = -1;
break;
case 4:
coord[0] = -1;
coord[1] = -0;
break;
case 5:
coord[0] = -0;
coord[1] = -0;
break;
case 6:
coord[0] = +1;
coord[1] = -0;
break;
case 7:
coord[0] = -1;
coord[1] = +1;
break;
case 8:
coord[0] = -0;
coord[1] = +1;
break;
case 9:
coord[0] = +1;
coord[1] = +1;
break;
default:
break;
}
break;
case NeighbourSystem.VonNeumann:
switch (index)
{
case 1:
coord[0] = 0;
coord[1] = -1;
break;
case 2:
coord[0] = -1;
coord[1] = 0;
break;
case 3:
coord[0] = +1;
coord[1] = 0;
break;
case 4:
coord[0] = 0;
coord[1] = +1;
break;
case 5:
coord[0] = -0;
coord[1] = -0;
break;
default:
break;
}
break;
}
return coord;
}
private enum NeighbourSystem
{
Moore,
VonNeumann
} ;
#endregion
#region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, UUID userID, float rx, float ry, float rz, float strength,
float duration, float BrushSize, Scene scene)
{
strength = TerrainUtil.MetersToSphericalStrength(strength);
int x;
for (x = 0; x < map.Width; x++)
{
int y;
for (y = 0; y < map.Height; y++)
{
if (!scene.Permissions.CanTerraformLand(userID, new Vector3(x, y, 0)))
continue;
double z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength);
if (z > 0) // add in non-zero amount
{
const int NEIGHBOUR_ME = 4;
const int NEIGHBOUR_MAX = 9;
for (int j = 0; j < NEIGHBOUR_MAX; j++)
{
if (j != NEIGHBOUR_ME)
{
int[] coords = Neighbours(type, j);
coords[0] += x;
coords[1] += y;
if (coords[0] > map.Width - 1)
continue;
if (coords[1] > map.Height - 1)
continue;
if (coords[0] < 0)
continue;
if (coords[1] < 0)
continue;
double heightF = map[x, y];
double target = map[coords[0], coords[1]];
if (target > heightF + talus)
{
double calc = duration * ((target - heightF) - talus) * z;
heightF += calc;
target -= calc;
}
map[x, y] = heightF;
map[coords[0], coords[1]] = target;
}
}
}
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Abstract base class for all Streams. Provides
** default implementations of asynchronous reads & writes, in
** terms of the synchronous reads & writes (and vice versa).
**
**
===========================================================*/
using System;
using System.Buffers;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Diagnostics;
using System.Reflection;
namespace System.IO
{
public abstract class Stream : MarshalByRefObject, IDisposable
{
public static readonly Stream Null = new NullStream();
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
private const int _DefaultCopyBufferSize = 81920;
// To implement Async IO operations on streams that don't support async IO
private ReadWriteTask _activeReadWriteTask;
private SemaphoreSlim _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
public abstract bool CanRead
{
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek
{
get;
}
public virtual bool CanTimeout
{
get
{
return false;
}
}
public abstract bool CanWrite
{
get;
}
public abstract long Length
{
get;
}
public abstract long Position
{
get;
set;
}
public virtual int ReadTimeout
{
get
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public virtual int WriteTimeout
{
get
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public Task CopyToAsync(Stream destination)
{
int bufferSize = GetCopyBufferSize();
return CopyToAsync(destination, bufferSize);
}
public Task CopyToAsync(Stream destination, Int32 bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
public Task CopyToAsync(Stream destination, CancellationToken cancellationToken)
{
int bufferSize = GetCopyBufferSize();
return CopyToAsync(destination, bufferSize, cancellationToken);
}
public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
Debug.Assert(destination != null);
Debug.Assert(bufferSize > 0);
Debug.Assert(CanRead);
Debug.Assert(destination.CanWrite);
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine
try
{
while (true)
{
int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
if (bytesRead == 0) break;
if (bytesRead > bufferSize) bufferSize = bytesRead;
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
}
}
finally
{
Array.Clear(buffer, 0, bufferSize); // clear only the most we used
ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
}
}
// Reads the bytes from the current stream and writes the bytes to
// the destination stream until all bytes are read, starting at
// the current position.
public void CopyTo(Stream destination)
{
int bufferSize = GetCopyBufferSize();
CopyTo(destination, bufferSize);
}
public virtual void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
int highwaterMark = 0;
try
{
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
{
if (read > highwaterMark) highwaterMark = read;
destination.Write(buffer, 0, read);
}
}
finally
{
Array.Clear(buffer, 0, highwaterMark); // clear only the most we used
ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
}
}
private int GetCopyBufferSize()
{
int bufferSize = _DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// There are no bytes left in the stream to copy.
// However, because CopyTo{Async} is virtual, we need to
// ensure that any override is still invoked to provide its
// own validation, so we use the smallest legal buffer size here.
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0)
{
// In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
}
return bufferSize;
}
// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable. However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern. We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup starting in V2.
public virtual void Close()
{
// Ideally we would assert CanRead == CanWrite == CanSeek = false,
// but we'd have to fix PipeStream & NetworkStream very carefully.
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
// Ideally we would assert CanRead == CanWrite == CanSeek = false,
// but we'd have to fix PipeStream & NetworkStream very carefully.
Close();
}
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
public abstract void Flush();
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
protected virtual WaitHandle CreateWaitHandle()
{
return new ManualResetEvent(false);
}
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
internal IAsyncResult BeginReadInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
if (!CanRead) __Error.ReadNotSupported();
// To avoid a race with a stream's position pointer & generating race conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync();
}
else
{
semaphore.Wait();
}
// Create the task to asynchronously do a Read. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Read.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Read and return the number of bytes read
return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count);
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
public virtual int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
var readTask = _activeReadWriteTask;
if (readTask == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (readTask != asyncResult)
{
throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (!readTask._isRead)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
try
{
return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
}
finally
{
FinishTrackingAsyncOperation();
}
}
public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled<int>(cancellationToken)
: BeginEndReadAsync(buffer, offset, count);
}
public virtual ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
{
if (destination.TryGetArray(out ArraySegment<byte> array))
{
return new ValueTask<int>(ReadAsync(array.Array, array.Offset, array.Count, cancellationToken));
}
else
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(destination.Length);
return FinishReadAsync(ReadAsync(buffer, 0, destination.Length, cancellationToken), buffer, destination);
async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination)
{
try
{
int result = await readTask.ConfigureAwait(false);
new Span<byte>(localBuffer, 0, result).CopyTo(localDestination.Span);
return result;
}
finally
{
ArrayPool<byte>.Shared.Return(localBuffer);
}
}
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndRead();
private Task<Int32> BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count)
{
if (!HasOverriddenBeginEndRead())
{
// If the Stream does not override Begin/EndRead, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task<Int32>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<Int32>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler
}
private struct ReadWriteParameters // struct for arguments to Read and Write calls
{
internal byte[] Buffer;
internal int Offset;
internal int Count;
}
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
internal IAsyncResult BeginWriteInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
if (!CanWrite) __Error.WriteNotSupported();
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block
}
else
{
semaphore.Wait(); // synchronously wait here
}
// Create the task to asynchronously do a Write. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Write.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Write
thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
return 0; // not used, but signature requires a value be returned
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
Debug.Assert(readWriteTask != null);
Debug.Assert(asyncWaiter != null);
// If the wait has already completed, run the task.
if (asyncWaiter.IsCompleted)
{
Debug.Assert(asyncWaiter.IsCompletedSuccessfully, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
}
else // Otherwise, wait for our turn, and then run the task.
{
asyncWaiter.ContinueWith((t, state) =>
{
Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state;
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
}, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
private void RunReadWriteTask(ReadWriteTask readWriteTask)
{
Debug.Assert(readWriteTask != null);
Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
// Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
// Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
// two interlocked operations. However, if ReadWriteTask is ever changed to use
// a cancellation token, this should be changed to use Start.
_activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one
readWriteTask.m_taskScheduler = TaskScheduler.Default;
readWriteTask.ScheduleAndStart(needsProtection: false);
}
private void FinishTrackingAsyncOperation()
{
_activeReadWriteTask = null;
Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
public virtual void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
var writeTask = _activeReadWriteTask;
if (writeTask == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask != asyncResult)
{
throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask._isRead)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
}
finally
{
FinishTrackingAsyncOperation();
}
}
// Task used by BeginRead / BeginWrite to do Read / Write asynchronously.
// A single instance of this task serves four purposes:
// 1. The work item scheduled to run the Read / Write operation
// 2. The state holding the arguments to be passed to Read / Write
// 3. The IAsyncResult returned from BeginRead / BeginWrite
// 4. The completion action that runs to invoke the user-provided callback.
// This last item is a bit tricky. Before the AsyncCallback is invoked, the
// IAsyncResult must have completed, so we can't just invoke the handler
// from within the task, since it is the IAsyncResult, and thus it's not
// yet completed. Instead, we use AddCompletionAction to install this
// task as its own completion handler. That saves the need to allocate
// a separate completion handler, it guarantees that the task will
// have completed by the time the handler is invoked, and it allows
// the handler to be invoked synchronously upon the completion of the
// task. This all enables BeginRead / BeginWrite to be implemented
// with a single allocation.
private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
{
internal readonly bool _isRead;
internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync
internal Stream _stream;
internal byte[] _buffer;
internal readonly int _offset;
internal readonly int _count;
private AsyncCallback _callback;
private ExecutionContext _context;
internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC
{
_stream = null;
_buffer = null;
}
public ReadWriteTask(
bool isRead,
bool apm,
Func<object, int> function, object state,
Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) :
base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
{
Debug.Assert(function != null);
Debug.Assert(stream != null);
Debug.Assert(buffer != null);
// Store the arguments
_isRead = isRead;
_apm = apm;
_stream = stream;
_buffer = buffer;
_offset = offset;
_count = count;
// If a callback was provided, we need to:
// - Store the user-provided handler
// - Capture an ExecutionContext under which to invoke the handler
// - Add this task as its own completion handler so that the Invoke method
// will run the callback when this task completes.
if (callback != null)
{
_callback = callback;
_context = ExecutionContext.Capture();
base.AddCompletionAction(this);
}
}
private static void InvokeAsyncCallback(object completedTask)
{
var rwc = (ReadWriteTask)completedTask;
var callback = rwc._callback;
rwc._callback = null;
callback(rwc);
}
private static ContextCallback s_invokeAsyncCallback;
void ITaskCompletionAction.Invoke(Task completingTask)
{
// Get the ExecutionContext. If there is none, just run the callback
// directly, passing in the completed task as the IAsyncResult.
// If there is one, process it with ExecutionContext.Run.
var context = _context;
if (context == null)
{
var callback = _callback;
_callback = null;
callback(completingTask);
}
else
{
_context = null;
var invokeAsyncCallback = s_invokeAsyncCallback;
if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
ExecutionContext.Run(context, invokeAsyncCallback, this);
}
}
bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } }
}
public Task WriteAsync(Byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: BeginEndWriteAsync(buffer, offset, count);
}
public virtual Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
{
if (source.DangerousTryGetArray(out ArraySegment<byte> array))
{
return WriteAsync(array.Array, array.Offset, array.Count, cancellationToken);
}
else
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(source.Length);
source.Span.CopyTo(buffer);
return FinishWriteAsync(WriteAsync(buffer, 0, source.Length, cancellationToken), buffer);
async Task FinishWriteAsync(Task writeTask, byte[] localBuffer)
{
try
{
await writeTask.ConfigureAwait(false);
}
finally
{
ArrayPool<byte>.Shared.Return(localBuffer);
}
}
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndWrite();
private Task BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count)
{
if (!HasOverriddenBeginEndWrite())
{
// If the Stream does not override Begin/EndWrite, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<VoidTaskResult>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => // cached by compiler
{
stream.EndWrite(asyncResult);
return default(VoidTaskResult);
});
}
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read([In, Out] byte[] buffer, int offset, int count);
public virtual int Read(Span<byte> destination)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(destination.Length);
try
{
int numRead = Read(buffer, 0, destination.Length);
if ((uint)numRead > destination.Length)
{
throw new IOException(SR.IO_StreamTooLong);
}
new Span<byte>(buffer, 0, numRead).CopyTo(destination);
return numRead;
}
finally { ArrayPool<byte>.Shared.Return(buffer); }
}
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r == 0)
return -1;
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
public virtual void Write(ReadOnlySpan<byte> source)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(source.Length);
try
{
source.CopyTo(buffer);
Write(buffer, 0, source.Length);
}
finally { ArrayPool<byte>.Shared.Return(buffer); }
}
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
public static Stream Synchronized(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (stream is SyncStream)
return stream;
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
protected virtual void ObjectInvariant()
{
}
internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
// To avoid a race with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try
{
int numRead = Read(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(numRead, state);
}
catch (IOException ex)
{
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
}
if (callback != null)
{
callback(asyncResult);
}
return asyncResult;
}
internal static int BlockingEndRead(IAsyncResult asyncResult)
{
return SynchronousAsyncResult.EndRead(asyncResult);
}
internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try
{
Write(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(state);
}
catch (IOException ex)
{
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
}
if (callback != null)
{
callback(asyncResult);
}
return asyncResult;
}
internal static void BlockingEndWrite(IAsyncResult asyncResult)
{
SynchronousAsyncResult.EndWrite(asyncResult);
}
private sealed class NullStream : Stream
{
internal NullStream() { }
public override bool CanRead
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override long Length
{
get { return 0; }
}
public override long Position
{
get { return 0; }
set { }
}
public override void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// After we validate arguments this is a nop.
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments here for compat, since previously this method
// was inherited from Stream (which did check its arguments).
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
// Do nothing - we don't want NullStream singleton (static) to be closable
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanRead) __Error.ReadNotSupported();
return BlockingBeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
return BlockingEndRead(asyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanWrite) __Error.WriteNotSupported();
return BlockingBeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
BlockingEndWrite(asyncResult);
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
return 0;
}
public override int Read(Span<byte> destination)
{
return 0;
}
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return AsyncTaskMethodBuilder<int>.s_defaultResultTask;
}
public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
{
return new ValueTask<int>(0);
}
public override int ReadByte()
{
return -1;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
public override void Write(ReadOnlySpan<byte> source)
{
}
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override void WriteByte(byte value)
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
public override void SetLength(long length)
{
}
}
/// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary>
internal sealed class SynchronousAsyncResult : IAsyncResult
{
private readonly Object _stateObject;
private readonly bool _isWrite;
private ManualResetEvent _waitHandle;
private ExceptionDispatchInfo _exceptionInfo;
private bool _endXxxCalled;
private Int32 _bytesRead;
internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject)
{
_bytesRead = bytesRead;
_stateObject = asyncStateObject;
//_isWrite = false;
}
internal SynchronousAsyncResult(Object asyncStateObject)
{
_stateObject = asyncStateObject;
_isWrite = true;
}
internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite)
{
_exceptionInfo = ExceptionDispatchInfo.Capture(ex);
_stateObject = asyncStateObject;
_isWrite = isWrite;
}
public bool IsCompleted
{
// We never hand out objects of this type to the user before the synchronous IO completed:
get { return true; }
}
public WaitHandle AsyncWaitHandle
{
get
{
return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
}
}
public Object AsyncState
{
get { return _stateObject; }
}
public bool CompletedSynchronously
{
get { return true; }
}
internal void ThrowIfError()
{
if (_exceptionInfo != null)
_exceptionInfo.Throw();
}
internal static Int32 EndRead(IAsyncResult asyncResult)
{
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || ar._isWrite)
__Error.WrongAsyncResult();
if (ar._endXxxCalled)
__Error.EndReadCalledTwice();
ar._endXxxCalled = true;
ar.ThrowIfError();
return ar._bytesRead;
}
internal static void EndWrite(IAsyncResult asyncResult)
{
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || !ar._isWrite)
__Error.WrongAsyncResult();
if (ar._endXxxCalled)
__Error.EndWriteCalledTwice();
ar._endXxxCalled = true;
ar.ThrowIfError();
}
} // class SynchronousAsyncResult
// SyncStream is a wrapper around a stream that takes
// a lock for every operation making it thread safe.
internal sealed class SyncStream : Stream, IDisposable
{
private Stream _stream;
internal SyncStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
_stream = stream;
}
public override bool CanRead
{
get { return _stream.CanRead; }
}
public override bool CanWrite
{
get { return _stream.CanWrite; }
}
public override bool CanSeek
{
get { return _stream.CanSeek; }
}
public override bool CanTimeout
{
get
{
return _stream.CanTimeout;
}
}
public override long Length
{
get
{
lock (_stream)
{
return _stream.Length;
}
}
}
public override long Position
{
get
{
lock (_stream)
{
return _stream.Position;
}
}
set
{
lock (_stream)
{
_stream.Position = value;
}
}
}
public override int ReadTimeout
{
get
{
return _stream.ReadTimeout;
}
set
{
_stream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return _stream.WriteTimeout;
}
set
{
_stream.WriteTimeout = value;
}
}
// In the off chance that some wrapped stream has different
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
lock (_stream)
{
try
{
_stream.Close();
}
finally
{
base.Dispose(true);
}
}
}
protected override void Dispose(bool disposing)
{
lock (_stream)
{
try
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
finally
{
base.Dispose(disposing);
}
}
}
public override void Flush()
{
lock (_stream)
_stream.Flush();
}
public override int Read([In, Out]byte[] bytes, int offset, int count)
{
lock (_stream)
return _stream.Read(bytes, offset, count);
}
public override int Read(Span<byte> destination)
{
lock (_stream)
return _stream.Read(destination);
}
public override int ReadByte()
{
lock (_stream)
return _stream.ReadByte();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
lock (_stream)
{
// If the Stream does have its own BeginRead implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginRead ?
_stream.BeginRead(buffer, offset, count, callback, state) :
_stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
lock (_stream)
return _stream.EndRead(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
lock (_stream)
return _stream.Seek(offset, origin);
}
public override void SetLength(long length)
{
lock (_stream)
_stream.SetLength(length);
}
public override void Write(byte[] bytes, int offset, int count)
{
lock (_stream)
_stream.Write(bytes, offset, count);
}
public override void Write(ReadOnlySpan<byte> source)
{
lock (_stream)
_stream.Write(source);
}
public override void WriteByte(byte b)
{
lock (_stream)
_stream.WriteByte(b);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
lock (_stream)
{
// If the Stream does have its own BeginWrite implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginWrite ?
_stream.BeginWrite(buffer, offset, count, callback, state) :
_stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
lock (_stream)
_stream.EndWrite(asyncResult);
}
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.LayoutRenderers;
using NLog.Targets;
using Xunit.Extensions;
namespace NLog.UnitTests.Config
{
using System;
using System.Globalization;
using System.Threading;
using Xunit;
using NLog.Config;
public class CultureInfoTests : NLogTestBase
{
[Fact]
public void WhenInvariantCultureDefinedThenDefaultCultureIsInvariantCulture()
{
var configuration = CreateConfigurationFromString("<nlog useInvariantCulture='true'></nlog>");
Assert.Equal(CultureInfo.InvariantCulture, configuration.DefaultCultureInfo);
}
[Fact]
public void DifferentConfigurations_UseDifferentDefaultCulture()
{
var currentCulture = CultureInfo.CurrentCulture;
try
{
// set the current thread culture to be definitely different from the InvariantCulture
Thread.CurrentThread.CurrentCulture = GetCultureInfo("de-DE");
var configurationTemplate = @"<nlog useInvariantCulture='{0}'>
<targets>
<target name='debug' type='Debug' layout='${{message}}' />
</targets>
<rules>
<logger name='*' writeTo='debug'/>
</rules>
</nlog>";
// configuration with current culture
var configuration1 = CreateConfigurationFromString(string.Format(configurationTemplate, false));
Assert.Equal(null, configuration1.DefaultCultureInfo);
// configuration with invariant culture
var configuration2 = CreateConfigurationFromString(string.Format(configurationTemplate, true));
Assert.Equal(CultureInfo.InvariantCulture, configuration2.DefaultCultureInfo);
Assert.NotEqual(configuration1.DefaultCultureInfo, configuration2.DefaultCultureInfo);
var testNumber = 3.14;
var testDate = DateTime.Now;
const string formatString = "{0},{1:d}";
AssertMessageFormattedWithCulture(configuration1, CultureInfo.CurrentCulture, formatString, testNumber, testDate);
AssertMessageFormattedWithCulture(configuration2, CultureInfo.InvariantCulture, formatString, testNumber, testDate);
}
finally
{
// restore current thread culture
Thread.CurrentThread.CurrentCulture = currentCulture;
}
}
private void AssertMessageFormattedWithCulture(LoggingConfiguration configuration, CultureInfo culture, string formatString, params object[] parameters)
{
var expected = string.Format(culture, formatString, parameters);
using (var logFactory = new LogFactory(configuration))
{
var logger = logFactory.GetLogger("test");
logger.Debug(formatString, parameters);
Assert.Equal(expected, GetDebugLastMessage("debug", configuration));
}
}
[Fact]
public void EventPropRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
var renderer = new EventPropertiesLayoutRenderer();
renderer.Item = "ADouble";
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
[Fact]
public void EventContextRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
#pragma warning disable 618
var renderer = new EventContextLayoutRenderer();
#pragma warning restore 618
renderer.Item = "ADouble";
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
#if !MONO
[Fact]
public void ProcessInfoLayoutRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "."; // dot as date separator (01.10.2008)
var logEventInfo = CreateLogEventInfo(cultureName);
var renderer = new ProcessInfoLayoutRenderer();
renderer.Property = ProcessInfoProperty.StartTime;
renderer.Format = "d";
string output = renderer.Render(logEventInfo);
Assert.Contains(expected, output);
Assert.DoesNotContain("/", output);
Assert.DoesNotContain("-", output);
var renderer2 = new ProcessInfoLayoutRenderer();
renderer2.Property = ProcessInfoProperty.BasePriority;
renderer2.Format = "d";
output = renderer2.Render(logEventInfo);
Assert.True(output.Length >= 1);
Assert.True("012345678".IndexOf(output[0]) > 0);
}
#endif
[Fact]
public void AllEventPropRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "ADouble=1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
var renderer = new AllEventPropertiesLayoutRenderer();
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
[Theory]
[InlineData(typeof(TimeLayoutRenderer))]
[InlineData(typeof(ProcessTimeLayoutRenderer))]
public void DateTimeCultureTest(Type rendererType)
{
string cultureName = "de-DE";
string expected = ","; // decimal comma as separator for ticks
var logEventInfo = CreateLogEventInfo(cultureName);
var renderer = Activator.CreateInstance(rendererType) as LayoutRenderer;
Assert.NotNull(renderer);
string output = renderer.Render(logEventInfo);
Assert.Contains(expected, output);
Assert.DoesNotContain(".", output);
}
private static LogEventInfo CreateLogEventInfo(string cultureName)
{
var logEventInfo = new LogEventInfo(
LogLevel.Info,
"SomeName",
CultureInfo.GetCultureInfo(cultureName),
"SomeMessage",
null);
return logEventInfo;
}
/// <summary>
/// expected: exactly the same exception message + stack trace regardless of the CurrentUICulture
/// </summary>
[Fact]
public void ExceptionTest()
{
var target = new MemoryTarget { Layout = @"${exception:format=tostring}" };
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetCurrentClassLogger();
try
{
throw new InvalidOperationException();
}
catch (Exception ex)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US", false);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
logger.Error(ex, "");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE", false);
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE", false);
logger.Error(ex, "");
Assert.Equal(2, target.Logs.Count);
Assert.NotNull(target.Logs[0]);
Assert.NotNull(target.Logs[1]);
Assert.Equal(target.Logs[0], target.Logs[1]);
}
}
}
}
| |
/* Gavaghan.Geodesy by Mike Gavaghan
*
* http://www.gavaghan.org/blog/free-source-code/geodesy-library-vincentys-formula/
*
* This code may be freely used and modified on any personal or professional
* project. It comes with no warranty.
*
* BitCoin tips graciously accepted at 1FB63FYQMy7hpC2ANVhZ5mSgAZEtY1aVLf
*/
using System;
namespace Gavaghan.Geodesy
{
/// <summary>
/// Implementation of Thaddeus Vincenty's algorithms to solve the direct and
/// inverse geodetic problems. For more information, see Vincent's original
/// publication on the NOAA website:
///
/// See http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
/// </summary>
public class GeodeticCalculator
{
private const double TwoPi = 2.0 * Math.PI;
/// <summary>
/// Calculate the destination and final bearing after traveling a specified
/// distance, and a specified starting bearing, for an initial location.
/// This is the solution to the direct geodetic problem.
/// </summary>
/// <param name="ellipsoid">reference ellipsoid to use</param>
/// <param name="start">starting location</param>
/// <param name="startBearing">starting bearing (degrees)</param>
/// <param name="distance">distance to travel (meters)</param>
/// <param name="endBearing">bearing at destination (degrees)</param>
/// <returns></returns>
public GlobalCoordinates CalculateEndingGlobalCoordinates(Ellipsoid ellipsoid, GlobalCoordinates start, Angle startBearing, double distance, out Angle endBearing )
{
double a = ellipsoid.SemiMajorAxis;
double b = ellipsoid.SemiMinorAxis;
double aSquared = a * a;
double bSquared = b * b;
double f = ellipsoid.Flattening;
double phi1 = start.Latitude.Radians;
double alpha1 = startBearing.Radians;
double cosAlpha1 = Math.Cos(alpha1);
double sinAlpha1 = Math.Sin(alpha1);
double s = distance;
double tanU1 = (1.0 - f) * Math.Tan(phi1);
double cosU1 = 1.0 / Math.Sqrt( 1.0 + tanU1 * tanU1 );
double sinU1 = tanU1 * cosU1;
// eq. 1
double sigma1 = Math.Atan2(tanU1, cosAlpha1);
// eq. 2
double sinAlpha = cosU1 * sinAlpha1;
double sin2Alpha = sinAlpha * sinAlpha;
double cos2Alpha = 1 - sin2Alpha;
double uSquared = cos2Alpha * (aSquared - bSquared) / bSquared;
// eq. 3
double A = 1 + (uSquared / 16384) * (4096 + uSquared * (-768 + uSquared * (320 - 175 * uSquared)));
// eq. 4
double B = (uSquared / 1024) * (256 + uSquared * (-128 + uSquared * (74 - 47 * uSquared)));
// iterate until there is a negligible change in sigma
double deltaSigma;
double sOverbA = s / (b * A);
double sigma = sOverbA;
double sinSigma;
double prevSigma = sOverbA;
double sigmaM2;
double cosSigmaM2;
double cos2SigmaM2;
for (;;)
{
// eq. 5
sigmaM2 = 2.0*sigma1 + sigma;
cosSigmaM2 = Math.Cos(sigmaM2);
cos2SigmaM2 = cosSigmaM2 * cosSigmaM2;
sinSigma = Math.Sin(sigma);
double cosSignma = Math.Cos(sigma);
// eq. 6
deltaSigma = B * sinSigma * (cosSigmaM2 + (B / 4.0) * (cosSignma * (-1 + 2 * cos2SigmaM2)
- (B / 6.0) * cosSigmaM2 * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM2)));
// eq. 7
sigma = sOverbA + deltaSigma;
// break after converging to tolerance
if (Math.Abs(sigma - prevSigma) < 0.0000000000001) break;
prevSigma = sigma;
}
sigmaM2 = 2.0*sigma1 + sigma;
cosSigmaM2 = Math.Cos(sigmaM2);
cos2SigmaM2 = cosSigmaM2 * cosSigmaM2;
double cosSigma = Math.Cos(sigma);
sinSigma = Math.Sin(sigma);
// eq. 8
double phi2 = Math.Atan2( sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
(1.0-f) * Math.Sqrt( sin2Alpha + Math.Pow(sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1, 2.0)));
// eq. 9
// This fixes the pole crossing defect spotted by Matt Feemster. When a path
// passes a pole and essentially crosses a line of latitude twice - once in
// each direction - the longitude calculation got messed up. Using Atan2
// instead of Atan fixes the defect. The change is in the next 3 lines.
//double tanLambda = sinSigma * sinAlpha1 / (cosU1 * cosSigma - sinU1*sinSigma*cosAlpha1);
//double lambda = Math.Atan(tanLambda);
double lambda = Math.Atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1);
// eq. 10
double C = (f / 16) * cos2Alpha * (4 + f * (4 - 3 * cos2Alpha));
// eq. 11
double L = lambda - (1 - C) * f * sinAlpha * (sigma + C * sinSigma * (cosSigmaM2 + C * cosSigma * (-1 + 2 * cos2SigmaM2)));
// eq. 12
double alpha2 = Math.Atan2(sinAlpha, -sinU1 * sinSigma + cosU1 * cosSigma * cosAlpha1);
// build result
Angle latitude = new Angle();
Angle longitude = new Angle();
latitude.Radians = phi2;
longitude.Radians = start.Longitude.Radians + L;
endBearing = new Angle();
endBearing.Radians = alpha2;
return new GlobalCoordinates(latitude, longitude);
}
/// <summary>
/// Calculate the destination after traveling a specified distance, and a
/// specified starting bearing, for an initial location. This is the
/// solution to the direct geodetic problem.
/// </summary>
/// <param name="ellipsoid">reference ellipsoid to use</param>
/// <param name="start">starting location</param>
/// <param name="startBearing">starting bearing (degrees)</param>
/// <param name="distance">distance to travel (meters)</param>
/// <returns></returns>
public GlobalCoordinates CalculateEndingGlobalCoordinates(Ellipsoid ellipsoid, GlobalCoordinates start, Angle startBearing, double distance)
{
Angle endBearing = new Angle();
return CalculateEndingGlobalCoordinates(ellipsoid, start, startBearing, distance, out endBearing);
}
/// <summary>
/// Calculate the geodetic curve between two points on a specified reference ellipsoid.
/// This is the solution to the inverse geodetic problem.
/// </summary>
/// <param name="ellipsoid">reference ellipsoid to use</param>
/// <param name="start">starting coordinates</param>
/// <param name="end">ending coordinates </param>
/// <returns></returns>
public GeodeticCurve CalculateGeodeticCurve(Ellipsoid ellipsoid, GlobalCoordinates start, GlobalCoordinates end)
{
//
// All equation numbers refer back to Vincenty's publication:
// See http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
//
// get constants
double a = ellipsoid.SemiMajorAxis;
double b = ellipsoid.SemiMinorAxis;
double f = ellipsoid.Flattening;
// get parameters as radians
double phi1 = start.Latitude.Radians;
double lambda1 = start.Longitude.Radians;
double phi2 = end.Latitude.Radians;
double lambda2 = end.Longitude.Radians;
// calculations
double a2 = a * a;
double b2 = b * b;
double a2b2b2 = (a2 - b2) / b2;
double omega = lambda2 - lambda1;
double tanphi1 = Math.Tan(phi1);
double tanU1 = (1.0 - f) * tanphi1;
double U1 = Math.Atan(tanU1);
double sinU1 = Math.Sin(U1);
double cosU1 = Math.Cos(U1);
double tanphi2 = Math.Tan(phi2);
double tanU2 = (1.0 - f) * tanphi2;
double U2 = Math.Atan(tanU2);
double sinU2 = Math.Sin(U2);
double cosU2 = Math.Cos(U2);
double sinU1sinU2 = sinU1 * sinU2;
double cosU1sinU2 = cosU1 * sinU2;
double sinU1cosU2 = sinU1 * cosU2;
double cosU1cosU2 = cosU1 * cosU2;
// eq. 13
double lambda = omega;
// intermediates we'll need to compute 's'
double A = 0.0;
double B = 0.0;
double sigma = 0.0;
double deltasigma = 0.0;
double lambda0;
bool converged = false;
for (int i = 0; i < 20; i++)
{
lambda0 = lambda;
double sinlambda = Math.Sin(lambda);
double coslambda = Math.Cos(lambda);
// eq. 14
double sin2sigma = (cosU2 * sinlambda * cosU2 * sinlambda) + Math.Pow(cosU1sinU2 - sinU1cosU2 * coslambda, 2.0);
double sinsigma = Math.Sqrt(sin2sigma);
// eq. 15
double cossigma = sinU1sinU2 + (cosU1cosU2 * coslambda);
// eq. 16
sigma = Math.Atan2(sinsigma, cossigma);
// eq. 17 Careful! sin2sigma might be almost 0!
double sinalpha = (sin2sigma == 0) ? 0.0 : cosU1cosU2 * sinlambda / sinsigma;
double alpha = Math.Asin(sinalpha);
double cosalpha = Math.Cos(alpha);
double cos2alpha = cosalpha * cosalpha;
// eq. 18 Careful! cos2alpha might be almost 0!
double cos2sigmam = cos2alpha == 0.0 ? 0.0 : cossigma - 2 * sinU1sinU2 / cos2alpha;
double u2 = cos2alpha * a2b2b2;
double cos2sigmam2 = cos2sigmam * cos2sigmam;
// eq. 3
A = 1.0 + u2 / 16384 * (4096 + u2 * (-768 + u2 * (320 - 175 * u2)));
// eq. 4
B = u2 / 1024 * (256 + u2 * (-128 + u2 * (74 - 47 * u2)));
// eq. 6
deltasigma = B * sinsigma * (cos2sigmam + B / 4 * (cossigma * (-1 + 2 * cos2sigmam2) - B / 6 * cos2sigmam * (-3 + 4 * sin2sigma) * (-3 + 4 * cos2sigmam2)));
// eq. 10
double C = f / 16 * cos2alpha * (4 + f * (4 - 3 * cos2alpha));
// eq. 11 (modified)
lambda = omega + (1 - C) * f * sinalpha * (sigma + C * sinsigma * (cos2sigmam + C * cossigma * (-1 + 2 * cos2sigmam2)));
// see how much improvement we got
double change = Math.Abs((lambda - lambda0) / lambda);
if ((i > 1) && (change < 0.0000000000001))
{
converged = true;
break;
}
}
// eq. 19
double s = b * A * (sigma - deltasigma);
Angle alpha1;
Angle alpha2;
// didn't converge? must be N/S
if (!converged)
{
if (phi1 > phi2)
{
alpha1 = Angle.Angle180;
alpha2 = Angle.Zero;
}
else if (phi1 < phi2)
{
alpha1 = Angle.Zero;
alpha2 = Angle.Angle180;
}
else
{
alpha1 = new Angle(Double.NaN);
alpha2 = new Angle(Double.NaN);
}
}
// else, it converged, so do the math
else
{
double radians;
alpha1 = new Angle();
alpha2 = new Angle();
// eq. 20
radians = Math.Atan2(cosU2 * Math.Sin(lambda), (cosU1sinU2 - sinU1cosU2 * Math.Cos(lambda)));
if (radians < 0.0) radians += TwoPi;
alpha1.Radians = radians;
// eq. 21
radians = Math.Atan2(cosU1 * Math.Sin(lambda), (-sinU1cosU2 + cosU1sinU2 * Math.Cos(lambda))) + Math.PI;
if (radians < 0.0) radians += TwoPi;
alpha2.Radians = radians;
}
if (alpha1 >= 360.0) alpha1 -= 360.0;
if (alpha2 >= 360.0) alpha2 -= 360.0;
return new GeodeticCurve(s, alpha1, alpha2);
}
/// <summary>
/// Calculate the three dimensional geodetic measurement between two positions
/// measured in reference to a specified ellipsoid.
///
/// This calculation is performed by first computing a new ellipsoid by expanding or contracting
/// the reference ellipsoid such that the new ellipsoid passes through the average elevation
/// of the two positions. A geodetic curve across the new ellisoid is calculated. The
/// point-to-point distance is calculated as the hypotenuse of a right triangle where the length
/// of one side is the ellipsoidal distance and the other is the difference in elevation.
/// </summary>
/// <param name="refEllipsoid">reference ellipsoid to use</param>
/// <param name="start">starting position</param>
/// <param name="end">ending position</param>
/// <returns></returns>
public GeodeticMeasurement CalculateGeodeticMeasurement(Ellipsoid refEllipsoid, GlobalPosition start, GlobalPosition end)
{
// get the coordinates
GlobalCoordinates startCoords = start.Coordinates;
GlobalCoordinates endCoords = end.Coordinates;
// calculate elevation differences
double elev1 = start.Elevation;
double elev2 = end.Elevation;
double elev12 = (elev1 + elev2) / 2.0;
// calculate latitude differences
double phi1 = startCoords.Latitude.Radians;
double phi2 = endCoords.Latitude.Radians;
double phi12 = (phi1 + phi2) / 2.0;
// calculate a new ellipsoid to accommodate average elevation
double refA = refEllipsoid.SemiMajorAxis;
double f = refEllipsoid.Flattening;
double a = refA + elev12 * (1.0 + f * Math.Sin(phi12));
Ellipsoid ellipsoid = Ellipsoid.FromAAndF(a, f);
// calculate the curve at the average elevation
GeodeticCurve averageCurve = CalculateGeodeticCurve(ellipsoid, startCoords, endCoords);
// return the measurement
return new GeodeticMeasurement(averageCurve, elev2 - elev1);
}
}
}
| |
// QuickGraph Library
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// QuickGraph Library HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
namespace QuickGraph.Algorithms.Search
{
using System;
using System.Collections;
using System.Collections.Specialized;
using QuickGraph.Collections;
using QuickGraph.Concepts;
using QuickGraph.Concepts.Algorithms;
using QuickGraph.Concepts.Traversals;
using QuickGraph.Concepts.Visitors;
/// <summary>
/// The DepthFirstSearchAlgorithm performs a depth-first traversal of the
/// vertices in a directed graph.
/// </summary>
/// <remarks>
/// <para>
/// When possible, a depth-first traversal chooses a vertex adjacent to
/// the current vertex to visit next. If all adjacent vertices have
/// already been discovered, or there are no adjacent vertices,
/// then the algorithm backtracks to the last vertex that had undiscovered
/// neighbors. Once all reachable vertices have been visited, the algorithm
/// selects from any remaining undiscovered vertices and continues the
/// traversal. The algorithm finishes when all vertices have been visited.
/// </para>
/// <para>
/// Depth-first search is useful for categorizing edges in a graph,
/// and for imposing an ordering on the vertices.
/// </para>
/// <para>
/// Similar to the <seealso cref="BreadthFirstSearchAlgorithm"/>, color
/// markers are used to keep track of which vertices have been discovered.
/// White marks vertices that have yet to be discovered,
/// gray marks a vertex that is discovered but still has vertices adjacent
/// to it that are undiscovered. A black vertex is discovered vertex that
/// is not adjacent to any white vertices.
/// </para>
/// <para>The main loop pseudo-code is as follows:
/// <code>
/// IVertexListGraph g;
/// DFS(IVertex s)
/// {
/// // initialize vertex colors
/// foreach(IVertex v in g.Vertices)
/// {
/// Colors[v] = White;
/// InitializeVertex(v); // event
/// }
///
/// // if there is a starting vertex, visit it
/// if (s != null)
/// {
/// StartVertex(s); // event
/// Visit(s);
/// }
///
/// // visit all vertices, if not previously visited
/// foreach(IVertex v in g.Vertices)
/// {
/// if (Colors[v] != White)
/// {
/// StartVertex(v); // event
/// Visit(v);
/// }
/// }
/// }
/// </code>
/// </para>
/// <para>The Visit method pseudo-code is as follows:
/// <code>
/// Visit(IVertexListGraph g, IVertex u)
/// {
/// Colors[u] = Gray;
/// OnDiscoverVertex(u); // event
///
/// // examine edges
/// foreach(IEdge e in g.OutEdges(u))
/// {
/// OnExamineEdge(e); // event
/// if (Colors[u] == White)
/// {
/// OnTreeEdge(e); // event
/// Visit(e.Target);
/// }
/// else if (Colors[u] == Gray)
/// {
/// OnBackEdge(e); // event
/// }
/// else
/// OnForwardOrCrossEdge(e); // event
/// }
///
/// Colors[u] = Black;
/// OnFinishVertex(u); // event
/// }
/// </code>
/// </para>
/// <para>In itself the algorithm does not take action, it is the user
/// job to attach handlers to the different events that take part during
/// the algorithm:
/// <list type="bullet">
/// <listheader>
/// <term>Event</term>
/// <description>When</description>
/// </listheader>
/// <item>
/// <term>InitializeVertex</term>
/// <description>Invoked on every vertex of the graph before the start of the graph
/// search.</description>
/// </item>
/// <item>
/// <term>StartVertex</term>
/// <description>Invoked on the source vertex once before the start of the search.</description>
/// </item>
/// <item>
/// <term>DiscoverVertex</term>
/// <description>Invoked when a vertex is encountered for the first time. </description>
/// </item>
/// <item>
/// <term>ExamineEdge</term>
/// <description>Invoked on every out-edge of each vertex after it is discovered.</description>
/// </item>
/// <item>
/// <term>TreeEdge</term>
/// <description>Invoked on each edge as it becomes a member of the edges that form
/// the search tree. If you wish to record predecessors, do so at this
/// event point. </description>
/// </item>
/// <item>
/// <term>BackEdge</term>
/// <description>Invoked on the back edges in the graph. </description>
/// </item>
/// <item>
/// <term>FowardOrCrossEdge</term>
/// <description>Invoked on forward or cross edges in the graph.
/// (In an undirected graph this method is never called.)</description>
/// </item>
/// <item>
/// <term>FinishVertex</term>
/// <description>Invoked on a vertex after all of its out edges have been added to
/// the search tree and all of the adjacent vertices have been
/// discovered (but before their out-edges have been examined).</description>
/// </item>
/// </list>
/// </para>
/// <para>
/// Predifined visitors, such as <seealso cref="QuickGraph.Concepts.Visitors.IPredecessorRecorderVisitor"/>
/// and <seealso cref="QuickGraph.Concepts.Visitors.ITimeStamperVisitor"/>
/// can be used with this algorithm.
/// </para>
/// <para>This algorithm is directly inspired from the
/// BoostGraphLibrary implementation.
/// </para>
/// </remarks>
public class DepthFirstSearchAlgorithm :
IAlgorithm,
IPredecessorRecorderAlgorithm,
ITimeStamperAlgorithm,
IVertexColorizerAlgorithm,
ITreeEdgeBuilderAlgorithm
{
private IVertexListGraph visitedGraph;
private VertexColorDictionary colors;
private int maxDepth = int.MaxValue;
/// <summary>
/// A depth first search algorithm on a directed graph
/// </summary>
/// <param name="g">The graph to traverse</param>
/// <exception cref="ArgumentNullException">g is null</exception>
public DepthFirstSearchAlgorithm(IVertexListGraph g)
{
if (g == null)
throw new ArgumentNullException("g");
this.visitedGraph = g;
this.colors = new VertexColorDictionary();
}
/// <summary>
/// A depth first search algorithm on a directed graph
/// </summary>
/// <param name="g">The graph to traverse</param>
/// <param name="colors">vertex color map</param>
/// <exception cref="ArgumentNullException">g or colors are null</exception>
public DepthFirstSearchAlgorithm(
IVertexListGraph g,
VertexColorDictionary colors
)
{
if (g == null)
throw new ArgumentNullException("g");
if (colors == null)
throw new ArgumentNullException("Colors");
this.visitedGraph = g;
this.colors = colors;
}
/// <summary>
/// Visited graph
/// </summary>
public IVertexListGraph VisitedGraph
{
get
{
return this.visitedGraph;
}
}
Object IAlgorithm.VisitedGraph
{
get
{
return this.VisitedGraph;
}
}
/// <summary>
/// Gets the vertex color map
/// </summary>
/// <value>
/// Vertex color (<see cref="GraphColor"/>) dictionary
/// </value>
public VertexColorDictionary Colors
{
get
{
return this.colors;
}
}
/// <summary>
/// IVertexColorizerAlgorithm implementation
/// </summary>
IDictionary IVertexColorizerAlgorithm.Colors
{
get
{
return this.Colors;
}
}
/// <summary>
/// Gets or sets the maximum exploration depth, from
/// the start vertex.
/// </summary>
/// <remarks>
/// Defaulted at <c>int.MaxValue</c>.
/// </remarks>
/// <value>
/// Maximum exploration depth.
/// </value>
public int MaxDepth
{
get
{
return this.maxDepth;
}
set
{
this.maxDepth = value;
}
}
#region Events
/// <summary>
/// Invoked on every vertex of the graph before the start of the graph
/// search.
/// </summary>
public event VertexEventHandler InitializeVertex;
/// <summary>
/// Raises the <see cref="InitializeVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
protected void OnInitializeVertex(IVertex v)
{
if (InitializeVertex!=null)
InitializeVertex(this, new VertexEventArgs(v));
}
/// <summary>
/// Invoked on the source vertex once before the start of the search.
/// </summary>
public event VertexEventHandler StartVertex;
/// <summary>
/// Raises the <see cref="StartVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
protected void OnStartVertex(IVertex v)
{
if (StartVertex!=null)
StartVertex(this, new VertexEventArgs(v));
}
/// <summary>
/// Invoked when a vertex is encountered for the first time.
/// </summary>
public event VertexEventHandler DiscoverVertex;
/// <summary>
/// Raises the <see cref="DiscoverVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
protected void OnDiscoverVertex(IVertex v)
{
if (DiscoverVertex!=null)
DiscoverVertex(this, new VertexEventArgs(v));
}
/// <summary>
/// Invoked on every out-edge of each vertex after it is discovered.
/// </summary>
public event EdgeEventHandler ExamineEdge;
/// <summary>
/// Raises the <see cref="ExamineEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
protected void OnExamineEdge(IEdge e)
{
if (ExamineEdge!=null)
ExamineEdge(this, new EdgeEventArgs(e));
}
/// <summary>
/// Invoked on each edge as it becomes a member of the edges that form
/// the search tree. If you wish to record predecessors, do so at this
/// event point.
/// </summary>
public event EdgeEventHandler TreeEdge;
/// <summary>
/// Raises the <see cref="TreeEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
protected void OnTreeEdge(IEdge e)
{
if (TreeEdge!=null)
TreeEdge(this, new EdgeEventArgs(e));
}
/// <summary>
/// Invoked on the back edges in the graph.
/// </summary>
public event EdgeEventHandler BackEdge;
/// <summary>
/// Raises the <see cref="BackEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
protected void OnBackEdge(IEdge e)
{
if (BackEdge!=null)
BackEdge(this, new EdgeEventArgs(e));
}
/// <summary>
/// Invoked on forward or cross edges in the graph.
/// (In an undirected graph this method is never called.)
/// </summary>
public event EdgeEventHandler ForwardOrCrossEdge;
/// <summary>
/// Raises the <see cref="ForwardOrCrossEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
protected void OnForwardOrCrossEdge(IEdge e)
{
if (ForwardOrCrossEdge!=null)
ForwardOrCrossEdge(this, new EdgeEventArgs(e));
}
/// <summary>
/// Invoked on a vertex after all of its out edges have been added to
/// the search tree and all of the adjacent vertices have been
/// discovered (but before their out-edges have been examined).
/// </summary>
public event VertexEventHandler FinishVertex;
/// <summary>
/// Raises the <see cref="FinishVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
protected void OnFinishVertex(IVertex v)
{
if (FinishVertex!=null)
FinishVertex(this, new VertexEventArgs(v));
}
#endregion
/// <summary>
/// Execute the DFS search.
/// </summary>
public void Compute()
{
Compute(null);
}
/// <summary>
/// Execute the DFS starting with the vertex s
/// </summary>
/// <param name="s">Starting vertex</param>
public void Compute(IVertex s)
{
// put all vertex to white
Initialize();
// if there is a starting vertex, start whith him:
if (s != null)
{
OnStartVertex(s);
Visit(s,0);
}
// process each vertex
foreach(IVertex u in VisitedGraph.Vertices)
{
if (Colors[u] == GraphColor.White)
{
OnStartVertex(u);
Visit(u,0);
}
}
}
/// <summary>
/// Initializes the vertex color map
/// </summary>
/// <remarks>
/// </remarks>
public void Initialize()
{
foreach(IVertex u in VisitedGraph.Vertices)
{
Colors[u] = GraphColor.White;
OnInitializeVertex(u);
}
}
/// <summary>
/// Does a depth first search on the vertex u
/// </summary>
/// <param name="u">vertex to explore</param>
/// <param name="depth">current recursion depth</param>
/// <exception cref="ArgumentNullException">u cannot be null</exception>
public void Visit(IVertex u, int depth)
{
if (depth > this.maxDepth)
return;
if (u==null)
throw new ArgumentNullException("u");
Colors[u] = GraphColor.Gray;
OnDiscoverVertex(u);
IVertex v = null;
foreach(IEdge e in VisitedGraph.OutEdges(u))
{
OnExamineEdge(e);
v = e.Target;
GraphColor c=Colors[v];
if (c == GraphColor.White)
{
OnTreeEdge(e);
Visit(v,depth+1);
}
else if (c == GraphColor.Gray)
{
OnBackEdge(e);
}
else
{
OnForwardOrCrossEdge(e);
}
}
Colors[u] = GraphColor.Black;
OnFinishVertex(u);
}
/// <summary>
/// Registers the predecessors handler
/// </summary>
/// <param name="vis"></param>
public void RegisterPredecessorRecorderHandlers(IPredecessorRecorderVisitor vis)
{
if (vis == null)
throw new ArgumentNullException("visitor");
TreeEdge += new EdgeEventHandler(vis.TreeEdge);
FinishVertex += new VertexEventHandler(vis.FinishVertex);
}
/// <summary>
///
/// </summary>
/// <param name="vis"></param>
public void RegisterTimeStamperHandlers(ITimeStamperVisitor vis)
{
if (vis == null)
throw new ArgumentNullException("visitor");
DiscoverVertex += new VertexEventHandler(vis.DiscoverVertex);
FinishVertex += new VertexEventHandler(vis.FinishVertex);
}
/// <summary>
///
/// </summary>
/// <param name="vis"></param>
public void RegisterVertexColorizerHandlers(IVertexColorizerVisitor vis)
{
if (vis == null)
throw new ArgumentNullException("visitor");
InitializeVertex += new VertexEventHandler(vis.InitializeVertex);
DiscoverVertex += new VertexEventHandler(vis.DiscoverVertex);
FinishVertex += new VertexEventHandler(vis.FinishVertex);
}
/// <summary>
///
/// </summary>
/// <param name="vis"></param>
public void RegisterTreeEdgeBuilderHandlers(ITreeEdgeBuilderVisitor vis)
{
if (vis == null)
throw new ArgumentNullException("visitor");
TreeEdge += new EdgeEventHandler(vis.TreeEdge);
}
}
}
| |
/*
* Created by: Leslie Sanford
*
* Contact: jabberdabber@hotmail.com
*
* Last modified: 09/26/2005
*/
using System;
using System.Collections;
namespace CNNWB.Common
{
/// <summary>
/// Represents a simple double-ended-queue collection of objects.
/// </summary>
[Serializable()]
public class Deque : ICollection, IEnumerable, ICloneable
{
#region Deque Members
#region Fields
// The node at the front of the deque.
private Node front = null;
// The node at the back of the deque.
private Node back = null;
// The number of elements in the deque.
private int count = 0;
// The version of the deque.
private long version = 0;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the Deque class.
/// </summary>
public Deque()
{
}
/// <summary>
/// Initializes a new instance of the Deque class that contains
/// elements copied from the specified collection.
/// </summary>
/// <param name="col">
/// The ICollection to copy elements from.
/// </param>
public Deque(ICollection col)
{
#region Preconditions
if(col == null)
{
throw new ArgumentNullException("col");
}
#endregion
foreach(object obj in col)
{
PushBack(obj);
}
}
#endregion
#region Methods
/// <summary>
/// Removes all objects from the Deque.
/// </summary>
public virtual void Clear()
{
count = 0;
front = back = null;
version++;
}
/// <summary>
/// Determines whether or not an element is in the Deque.
/// </summary>
/// <param name="obj">
/// The Object to locate in the Deque.
/// </param>
/// <returns>
/// <b>true</b> if <i>obj</i> if found in the Deque; otherwise,
/// <b>false</b>.
/// </returns>
public virtual bool Contains(object obj)
{
foreach(object o in this)
{
if(o == null && obj == null)
{
return true;
}
else if(o.Equals(obj))
{
return true;
}
}
return false;
}
/// <summary>
/// Inserts an object at the front of the Deque.
/// </summary>
/// <param name="obj">
/// The object to push onto the deque;
/// </param>
public virtual void PushFront(object obj)
{
// The new node to add to the front of the deque.
Node n = new Node(obj);
// Link the new node to the front node. The current front node at
// the front of the deque is now the second node in the deque.
n.Next = front;
// If the deque isn't empty
if(Count > 0)
{
// Link the current front to the new node.
front.Previous = n;
}
// Make the new node the front of the deque.
front = n;
// Keep track of the number of elements in the deque.
count++;
// If this is the first element in the deque.
if(Count == 1)
{
// The front and back nodes are the same.
back = front;
}
version++;
}
/// <summary>
/// Inserts an object at the back of the Deque.
/// </summary>
/// <param name="obj">
/// The object to push onto the deque;
/// </param>
public virtual void PushBack(object obj)
{
// The new node to add to the back of the deque.
Node n = new Node(obj);
// Link the new node to the back node. The current back node at
// the back of the deque is now the second to the last node in the
// deque.
n.Previous = back;
// If the deque is not empty.
if(Count > 0)
{
// Link the current back node to the new node.
back.Next = n;
}
// Make the new node the back of the deque.
back = n;
// Keep track of the number of elements in the deque.
count++;
// If this is the first element in the deque.
if(Count == 1)
{
// The front and back nodes are the same.
front = back;
}
version++;
}
/// <summary>
/// Removes and returns the object at the front of the Deque.
/// </summary>
/// <returns>
/// The object at the front of the Deque.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The Deque is empty.
/// </exception>
public virtual object PopFront()
{
#region Preconditions
if(Count == 0)
{
throw new InvalidOperationException("Deque is empty.");
}
#endregion
// Get the object at the front of the deque.
object obj = front.Value;
// Move the front back one node.
front = front.Next;
// Keep track of the number of nodes in the deque.
count--;
// If the deque is not empty.
if(Count > 0)
{
// Tie off the previous link in the front node.
front.Previous = null;
}
// Else the deque is empty.
else
{
// Indicate that there is no back node.
back = null;
}
version++;
return obj;
}
/// <summary>
/// Removes and returns the object at the back of the Deque.
/// </summary>
/// <returns>
/// The object at the back of the Deque.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The Deque is empty.
/// </exception>
public virtual object PopBack()
{
#region Preconditions
if(Count == 0)
{
throw new InvalidOperationException("Deque is empty.");
}
#endregion
// Get the object at the back of the deque.
object obj = back.Value;
// Move back node forward one node.
back = back.Previous;
// Keep track of the number of nodes in the deque.
count--;
// If the deque is not empty.
if(Count > 0)
{
// Tie off the next link in the back node.
back.Next = null;
}
// Else the deque is empty.
else
{
// Indicate that there is no front node.
front = null;
}
version++;
return obj;
}
/// <summary>
/// Returns the object at the front of the Deque without removing it.
/// </summary>
/// <returns>
/// The object at the front of the Deque.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The Deque is empty.
/// </exception>
public virtual object PeekFront()
{
#region Preconditions
if(Count == 0)
{
throw new InvalidOperationException("Deque is empty.");
}
#endregion
return front.Value;
}
/// <summary>
/// Returns the object at the back of the Deque without removing it.
/// </summary>
/// <returns>
/// The object at the back of the Deque.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The Deque is empty.
/// </exception>
public virtual object PeekBack()
{
#region Preconditions
if(Count == 0)
{
throw new InvalidOperationException("Deque is empty.");
}
#endregion
return back.Value;
}
/// <summary>
/// Copies the Deque to a new array.
/// </summary>
/// <returns>
/// A new array containing copies of the elements of the Deque.
/// </returns>
public virtual object[] ToArray()
{
object[] array = new object[Count];
int index = 0;
foreach(object obj in this)
{
array[index] = obj;
index++;
}
return array;
}
/// <summary>
/// Returns a synchronized (thread-safe) wrapper for the Deque.
/// </summary>
/// <param name="deque">
/// The Deque to synchronize.
/// </param>
/// <returns>
/// A synchronized wrapper around the Deque.
/// </returns>
public static Deque Synchronized(Deque deque)
{
#region Preconditions
if(deque == null)
{
throw new ArgumentNullException("deque");
}
#endregion
return new SynchronizedDeque(deque);
}
#endregion
#region Node Class
// Represents a node in the deque.
[Serializable()]
private class Node
{
private object value;
private Node previous = null;
private Node next = null;
public Node(object value)
{
this.value = value;
}
public object Value
{
get
{
return value;
}
}
public Node Previous
{
get
{
return previous;
}
set
{
previous = value;
}
}
public Node Next
{
get
{
return next;
}
set
{
next = value;
}
}
}
#endregion
#region DequeEnumerator Class
[Serializable()]
private class DequeEnumerator : IEnumerator
{
private Deque owner;
private Node current;
private bool beforeBeginning = true;
private long version;
public DequeEnumerator(Deque owner)
{
this.owner = owner;
current = owner.front;
this.version = owner.version;
}
#region IEnumerator Members
public void Reset()
{
#region Preconditions
if(version != owner.version)
{
throw new InvalidOperationException(
"The Deque was modified after the enumerator was created.");
}
#endregion
beforeBeginning = true;
}
public object Current
{
get
{
#region Preconditions
if(beforeBeginning || current == null)
{
throw new InvalidOperationException(
"The enumerator is positioned before the first " +
"element of the Deque or after the last element.");
}
#endregion
return current.Value;
}
}
public bool MoveNext()
{
#region Preconditions
if(version != owner.version)
{
throw new InvalidOperationException(
"The Deque was modified after the enumerator was created.");
}
#endregion
bool result = false;
// If the enumerator is positioned before the front of the
// deque.
if(beforeBeginning)
{
// Position the enumerator at the front of the deque.
current = owner.front;
// Indicate that the enumerator is no longer positioned
// before the beginning of the deque.
beforeBeginning = false;
}
// Else if the enumerator has not yet reached the end of the
// deque.
else if(current != null)
{
// Move to the next element in the deque.
current = current.Next;
}
// If the enumerator has not reached the end of the deque.
if(current != null)
{
// Indicate that the enumerator has not reached the end of
// the deque.
result = true;
}
return result;
}
#endregion
}
#endregion
#region SynchronizedDeque Class
// Implements a synchronization wrapper around a deque.
[Serializable()]
private class SynchronizedDeque : Deque
{
#region SynchronziedDeque Members
#region Fields
// The wrapped deque.
private Deque deque;
// The object to lock on.
private object root;
#endregion
#region Construction
public SynchronizedDeque(Deque deque)
{
this.deque = deque;
this.root = deque.SyncRoot;
}
#endregion
#region Methods
public override void Clear()
{
lock(root)
{
deque.Clear();
}
}
public override bool Contains(object obj)
{
bool result;
lock(root)
{
result = deque.Contains(obj);
}
return result;
}
public override void PushFront(object obj)
{
lock(root)
{
deque.PushFront(obj);
}
}
public override void PushBack(object obj)
{
lock(root)
{
deque.PushBack(obj);
}
}
public override object PopFront()
{
object obj;
lock(root)
{
obj = deque.PopFront();
}
return obj;
}
public override object PopBack()
{
object obj;
lock(root)
{
obj = deque.PopBack();
}
return obj;
}
public override object PeekFront()
{
object obj;
lock(root)
{
obj = deque.PeekFront();
}
return obj;
}
public override object PeekBack()
{
object obj;
lock(root)
{
obj = deque.PeekBack();
}
return obj;
}
public override object[] ToArray()
{
object[] array;
lock(root)
{
array = deque.ToArray();
}
return array;
}
public override object Clone()
{
object clone;
lock(root)
{
clone = deque.Clone();
}
return clone;
}
public override void CopyTo(Array array, int index)
{
lock(root)
{
deque.CopyTo(array, index);
}
}
public override IEnumerator GetEnumerator()
{
IEnumerator e;
lock(root)
{
e = deque.GetEnumerator();
}
return e;
}
#endregion
#region Properties
public override int Count
{
get
{
int count;
lock(root)
{
count = deque.Count;
}
return count;
}
}
public override bool IsSynchronized
{
get
{
return true;
}
}
#endregion
#endregion
}
#endregion
#endregion
#region ICollection Members
/// <summary>
/// Gets a value indicating whether access to the Deque is synchronized
/// (thread-safe).
/// </summary>
public virtual bool IsSynchronized
{
get
{
return false;
}
}
/// <summary>
/// Gets the number of elements contained in the Deque.
/// </summary>
public virtual int Count
{
get
{
return count;
}
}
/// <summary>
/// Copies the Deque elements to an existing one-dimensional Array,
/// starting at the specified array index.
/// </summary>
/// <param name="array">
/// The one-dimensional Array that is the destination of the elements
/// copied from Deque. The Array must have zero-based indexing.
/// </param>
/// <param name="index">
/// The zero-based index in array at which copying begins.
/// </param>
public virtual void CopyTo(Array array, int index)
{
#region Preconditions
if(array == null)
{
throw new ArgumentNullException("array");
}
else if(index < 0)
{
throw new ArgumentOutOfRangeException("index", index,
"Index is less than zero.");
}
else if(array.Rank > 1)
{
throw new ArgumentException("Array is multidimensional.");
}
else if(index >= array.Length)
{
throw new ArgumentException("Index is equal to or greater " +
"than the length of array.");
}
else if(Count > array.Length - index)
{
throw new ArgumentException(
"The number of elements in the source Deque is greater " +
"than the available space from index to the end of the " +
"destination array.");
}
#endregion
int i = index;
foreach(object obj in this)
{
array.SetValue(obj, i);
i++;
}
}
/// <summary>
/// Gets an object that can be used to synchronize access to the Deque.
/// </summary>
public virtual object SyncRoot
{
get
{
return this;
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that can iterate through the Deque.
/// </summary>
/// <returns>
/// An IEnumerator for the Deque.
/// </returns>
public virtual IEnumerator GetEnumerator()
{
return new DequeEnumerator(this);
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a shallow copy of the Deque.
/// </summary>
/// <returns>
/// A shalloe copy of the Deque.
/// </returns>
public virtual object Clone()
{
Deque clone = new Deque(this);
clone.version = this.version;
return clone;
}
#endregion
}
}
| |
using System;
using System.Net.Http;
using System.Threading.Tasks;
using dto.endpoint.auth.session.v2;
using dto.endpoint.auth.encryptionkey;
using dto.endpoint.browse;
using dto.endpoint.watchlists.retrieve;
using IGWebApiClient.Common;
using IGWebApiClient.Security;
using dto.endpoint.accountactivity.transaction;
using dto.endpoint.accountactivity.activity;
using dto.endpoint.marketdetails.v2;
using dto.endpoint.positions.create.otc.v1;
using dto.endpoint.positions.edit.v1;
using dto.endpoint.positions.close.v1;
using dto.endpoint.prices.v2;
using dto.endpoint.search;
using dto.endpoint.watchlists.manage.delete;
using dto.endpoint.watchlists.manage.create;
using dto.endpoint.watchlists.manage.edit;
using dto.endpoint.workingorders.create.v1;
using dto.endpoint.workingorders.edit.v1;
using dto.endpoint.workingorders.delete.v1;
using dto.endpoint.confirms;
using dto.endpoint.browse.sprintmarkets;
using dto.endpoint.clientsentiment;
using dto.endpoint.application.operation;
using System.Collections.Generic;
using dto.endpoint.accountswitch;
using dto.endpoint.accountbalance;
namespace IGWebApiClient
{
public partial class IgRestApiClient
{
private PropertyEventDispatcher eventDispatcher;
private ConversationContext _conversationContext;
private IgRestService _igRestService;
public IgRestApiClient(string environment, PropertyEventDispatcher eventDispatcher)
{
this.eventDispatcher = eventDispatcher;
this._igRestService = new IgRestService(eventDispatcher, environment);
}
private EncryptionKeyResponse ekr { get; set; }
public ConversationContext GetConversationContext()
{
return _conversationContext;
}
public async Task<IgResponse<AuthenticationResponse>> SecureAuthenticate(AuthenticationRequest ar, string apiKey)
{
_conversationContext = new ConversationContext(null, null, apiKey);
var encryptedPassword = await SecurePassword(ar.password);
if (encryptedPassword == ar.password)
{
ar.encryptedPassword = false;
}
else
{
ar.encryptedPassword = true;
}
ar.password = encryptedPassword;
return await authenticate(ar);
}
private async Task<string> SecurePassword(string rawPassword)
{
var encryptedPassword = rawPassword;
//Try encrypting password. If we can encrypt it, do so...
var secureResponse = await fetchEncryptionKey();
ekr = new EncryptionKeyResponse();
ekr = secureResponse.Response;
if (ekr != null)
{
byte[] encryptedBytes;
// get a public key to ENCRYPT...
Rsa rsa = new Rsa(Convert.FromBase64String(ekr.encryptionKey), true);
encryptedBytes = rsa.RsaEncrypt(string.Format("{0}|{1}", rawPassword, ekr.timeStamp));
encryptedPassword = Convert.ToBase64String(encryptedBytes);
}
return encryptedPassword;
}
///<Summary>
///Creates a trading session, obtaining session tokens for subsequent API access.
///<p>
/// Please note that region-specific <a href=/loginrestrictions>login restrictions</a> may apply.
///</p>
///@param authenticationRequest Client login credentials
///@return Client summary account information
///</Summary>
public async Task<IgResponse<dto.endpoint.auth.session.v2.AuthenticationResponse>> authenticate(dto.endpoint.auth.session.v2.AuthenticationRequest authenticationRequest)
{
return await _igRestService.RestfulService<dto.endpoint.auth.session.v2.AuthenticationResponse>("/gateway/deal/session", HttpMethod.Post, "2", _conversationContext, authenticationRequest);
}
///<Summary>
///Creates a trading session, obtaining session tokens for subsequent API access
///@return the encryption key to be used to encode the credentials
///</Summary>
public async Task<IgResponse<EncryptionKeyResponse>> fetchEncryptionKey()
{
return await _igRestService.RestfulService<EncryptionKeyResponse>("/gateway/deal/session/encryptionKey", HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Log out of the current session
///</Summary>
public async void logout()
{
await _igRestService.RestfulService("/gateway/deal/session", HttpMethod.Delete, "1", _conversationContext);
}
///<Summary>
///Returns all top-level nodes (market categories) in the market navigation hierarchy.
///</Summary>
public async Task<IgResponse<BrowseMarketsResponse>> browseRoot()
{
return await _igRestService.RestfulService<BrowseMarketsResponse>("/gateway/deal/marketnavigation", HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns all sub-nodes of the given node in the market navigation hierarchy
///@return the children of the selected node
///@throws BrowseMarketsException
///@pathParam nodeId the identifier of the node to browse
///</Summary>
public async Task<IgResponse<BrowseMarketsResponse>> browse(string nodeId)
{
return await _igRestService.RestfulService<BrowseMarketsResponse>("/gateway/deal/marketnavigation/" + nodeId, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns all open positions for the active account
///</Summary>
public async Task<IgResponse<dto.endpoint.positions.get.otc.v2.PositionsResponse>> getOTCOpenPositionsV2()
{
return await _igRestService.RestfulService<dto.endpoint.positions.get.otc.v2.PositionsResponse>("/gateway/deal/positions", HttpMethod.Get, "2", _conversationContext);
}
///<Summary>
///Returns all watchlists belonging to the active account
///</Summary>
public async Task<IgResponse<ListOfWatchlistsResponse>> listOfWatchlists()
{
return await _igRestService.RestfulService<ListOfWatchlistsResponse>("/gateway/deal/watchlists", HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns the given watchlists markets
///@pathParam watchlistId Watchlist id
///</Summary>
public async Task<IgResponse<WatchlistInstrumentsResponse>> instrumentsForWatchlist(string watchlistId)
{
return await _igRestService.RestfulService<WatchlistInstrumentsResponse>("/gateway/deal/watchlists/" + watchlistId, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns all open working orders for the active account
///</Summary>
public async Task<IgResponse<dto.endpoint.workingorders.get.v2.WorkingOrdersResponse>> workingOrdersV2()
{
return await _igRestService.RestfulService<dto.endpoint.workingorders.get.v2.WorkingOrdersResponse>("/gateway/deal/workingorders", HttpMethod.Get, "2", _conversationContext);
}
///<Summary>
///Returns the account activity history for the last specified period
///@pathParam lastPeriod Interval in milliseconds
///</Summary>
public async Task<IgResponse<ActivityHistoryResponse>> lastActivityPeriod(string lastPeriod)
{
return await _igRestService.RestfulService<ActivityHistoryResponse>("/gateway/deal/history/activity/" + lastPeriod, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns the account activity history for the given date range
///@pathParam fromDateStr Start date in dd-mm-yyyy format
///@pathParam toDateStr End date in dd-mm-yyyy format
///</Summary>
public async Task<IgResponse<ActivityHistoryResponse>> lastActivityTimeRange(string fromDate, string toDate)
{
return await _igRestService.RestfulService<ActivityHistoryResponse>("/gateway/deal/history/activity/" + fromDate + "/" + toDate, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns the transaction history for the specified transaction type and period
///@pathParam transactionType Transaction type (( ALL, ALL_DEAL, DEPOSIT, WITHDRAWAL ) )
///@pathParam lastPeriod Interval in milliseconds
///</Summary>
public async Task<IgResponse<TransactionHistoryResponse>> lastTransactionPeriod(string transactionType, string lastPeriod)
{
return await _igRestService.RestfulService<TransactionHistoryResponse>("/gateway/deal/history/transactions/" + transactionType + "/" + lastPeriod, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns the transaction history for the specified transaction type and given date range
///@pathParam transactionType Transaction type (( ALL, ALL_DEAL, DEPOSIT, WITHDRAWAL ) )
///@pathParam fromDate Start date in dd-mm-yyyy format
///@pathParam toDate End date in dd-mm-yyyy format
///</Summary>
public async Task<IgResponse<TransactionHistoryResponse>> lastTransactionTimeRange(string transactionType, string fromDate, string toDate)
{
return await _igRestService.RestfulService<TransactionHistoryResponse>("/gateway/deal/history/transactions/" + transactionType + "/" + fromDate + "/" + toDate, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns a list of accounts belonging to the logged-in client
///</Summary>
public async Task<IgResponse<AccountDetailsResponse>> accountBalance()
{
return await _igRestService.RestfulService<AccountDetailsResponse>("/gateway/deal/accounts", HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Switches active accounts, optionally setting the default account
///@param accountSwitchRequest Account switch request
///</Summary>
public async Task<IgResponse<AccountSwitchResponse>> accountSwitch(AccountSwitchRequest accountSwitchRequest)
{
return await _igRestService.RestfulService<AccountSwitchResponse>("/gateway/deal/session", HttpMethod.Put, "1", _conversationContext, accountSwitchRequest);
}
///<Summary>
///Alters the details of a given user application
///@param updateApplicationRequest application update request
///</Summary>
public async Task<IgResponse<Application>> update(UpdateApplicationRequest updateApplicationRequest)
{
return await _igRestService.RestfulService<Application>("/gateway/deal/operations/application", HttpMethod.Put, "1", _conversationContext, updateApplicationRequest);
}
///<Summary>
///Disables the current application key from processing further requests. Disabled keys may be reenabled via the My Account section on our web dealing platform.
///</Summary>
public async Task<IgResponse<Application>> disableApplication()
{
return await _igRestService.RestfulService<Application>("/gateway/deal/operations/application/disable", HttpMethod.Put, "1", _conversationContext);
}
///<Summary>
///Returns a list of client-owned applications
///</Summary>
public async Task<IgResponse<List<Application>>> findClientApplications()
{
return await _igRestService.RestfulService<List<Application>>("/gateway/deal/operations/application", HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Creates a trading session, obtaining session tokens for subsequent API access
///@param authenticationRequest Client login credentials
///@return Client summary account information
///</Summary>
private async Task<IgResponse<dto.endpoint.auth.session.AuthenticationResponse>> authenticate(dto.endpoint.auth.session.AuthenticationRequest authenticationRequest)
{
return await _igRestService.RestfulService<dto.endpoint.auth.session.AuthenticationResponse>("/gateway/deal/session", HttpMethod.Post, "1", _conversationContext, authenticationRequest);
}
///<Summary>
///</Summary>
public async Task<IgResponse<SprintMarketsSearchResponse>> findAll()
{
return await _igRestService.RestfulService<SprintMarketsSearchResponse>("/gateway/deal/sprintmarkets", HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns the client sentiment for the given instrument's market
///@pathParam marketId Market identifier
///</Summary>
public async Task<IgResponse<ClientSentiment>> getClientSentiment(string marketId)
{
return await _igRestService.RestfulService<ClientSentiment>("/gateway/deal/clientsentiment/" + marketId, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns a list of related (what others have traded) client sentiment for the given instrument's market
///@pathParam marketId Market identifier
///</Summary>
public async Task<IgResponse<ClientSentimentList>> getRelatedClientSentiment(string marketId)
{
return await _igRestService.RestfulService<ClientSentimentList>("/gateway/deal/clientsentiment/related/" + marketId, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns a deal confirmation for the given deal reference
///@pathParam dealReference Deal reference
///</Summary>
public async Task<IgResponse<ConfirmsResponse>> retrieveConfirm(string dealReference)
{
return await _igRestService.RestfulService<ConfirmsResponse>("/gateway/deal/confirms/" + dealReference, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns the details of the given market
///@pathParam epic The epic of the market to be retrieved
///</Summary>
public async Task<IgResponse<dto.endpoint.marketdetails.v1.MarketDetailsResponse>> marketDetails(string epic)
{
return await _igRestService.RestfulService<dto.endpoint.marketdetails.v1.MarketDetailsResponse>("/gateway/deal/markets/" + epic, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns the details of the given market
///@pathParam epic The epic of the market to be retrieved
///</Summary>
public async Task<IgResponse<dto.endpoint.marketdetails.v2.MarketDetailsResponse>> marketDetailsV2(string epic)
{
return await _igRestService.RestfulService<dto.endpoint.marketdetails.v2.MarketDetailsResponse>("/gateway/deal/markets/" + epic, HttpMethod.Get, "2", _conversationContext);
}
///<Summary>
///Returns the details of the given markets.
///@pathParam epics The epics of the market to be retrieved, separated by a comma. Max number of epics is limited to 50.
///</Summary>
public async Task<IgResponse<MarketDetailsListResponse>> marketDetailsMulti(string epicsList)
{
return await _igRestService.RestfulService<MarketDetailsListResponse>("/gateway/deal/markets?epics=" + epicsList, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Creates an OTC position
///@param createPositionRequest the request for creating a position
///@return OTC create position response
///</Summary>
public async Task<IgResponse<CreatePositionResponse>> createPositionV1(dto.endpoint.positions.create.otc.v1.CreatePositionRequest createPositionRequest)
{
return await _igRestService.RestfulService<CreatePositionResponse>("/gateway/deal/positions/otc", HttpMethod.Post, "1", _conversationContext, createPositionRequest);
}
///<Summary>
///Creates an OTC position
///@param createPositionRequest the request for creating a position
///@return OTC create position response
///</Summary>
public async Task<IgResponse<CreatePositionResponse>> createPositionV2(dto.endpoint.positions.create.otc.v2.CreatePositionRequest createPositionRequest)
{
return await _igRestService.RestfulService<CreatePositionResponse>("/gateway/deal/positions/otc", HttpMethod.Post, "2", _conversationContext, createPositionRequest);
}
///<Summary>
///Updates an OTC position
///@pathParam dealId Deal reference identifier
///@param editPositionRequest the request for updating a position
///@return OTC edit position response
///</Summary>
public async Task<IgResponse<EditPositionResponse>> editPositionV1(string dealId, dto.endpoint.positions.edit.v1.EditPositionRequest editPositionRequest)
{
return await _igRestService.RestfulService<EditPositionResponse>("/gateway/deal/positions/otc/" + dealId, HttpMethod.Put, "1", _conversationContext, editPositionRequest);
}
///<Summary>
///Updates an OTC position
///@pathParam dealId Deal reference identifier
///@param editPositionRequest the request for updating a position
///@return OTC edit position response
///</Summary>
public async Task<IgResponse<EditPositionResponse>> editPositionV2(string dealId, dto.endpoint.positions.edit.v2.EditPositionRequest editPositionRequest)
{
return await _igRestService.RestfulService<EditPositionResponse>("/gateway/deal/positions/otc/" + dealId, HttpMethod.Put, "2", _conversationContext, editPositionRequest);
}
///<Summary>
///Closes one or more OTC positions
///@param closePositionRequest the request for closing one or more positions
///@return OTC close position response
///</Summary>
public async Task<IgResponse<ClosePositionResponse>> closePosition(ClosePositionRequest closePositionRequest)
{
return await _igRestService.RestfulService<ClosePositionResponse>("/gateway/deal/positions/otc", HttpMethod.Delete, "1", _conversationContext, closePositionRequest);
}
///<Summary>
///Returns all open positions for the active account
///</Summary>
public async Task<IgResponse<dto.endpoint.positions.get.otc.v1.PositionsResponse>> getOTCOpenPositionsV1()
{
return await _igRestService.RestfulService<dto.endpoint.positions.get.otc.v1.PositionsResponse>("/gateway/deal/positions", HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns an open position for the active account by deal identifier
///@pathParam dealId Deal reference identifier
///</Summary>
public async Task<IgResponse<dto.endpoint.positions.get.otc.v1.OpenPosition>> getOTCOpenPositionByDealIdV1(string dealId)
{
return await _igRestService.RestfulService<dto.endpoint.positions.get.otc.v1.OpenPosition>("/gateway/deal/positions/" + dealId, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns an open position for the active account by deal identifier
///@pathParam dealId Deal reference identifier
///</Summary>
public async Task<IgResponse<dto.endpoint.positions.get.otc.v2.OpenPosition>> getOTCOpenPositionByDealIdV2(string dealId)
{
return await _igRestService.RestfulService<dto.endpoint.positions.get.otc.v2.OpenPosition>("/gateway/deal/positions/" + dealId, HttpMethod.Get, "2", _conversationContext);
}
///<Summary>
///Returns a list of historical prices for the given epic, resolution and date range.
///@pathParam epic Instrument epic
///@pathParam resolution Price resolution (MINUTE, MINUTE_2, MINUTE_3, MINUTE_5, MINUTE_10, MINUTE_15, MINUTE_30, HOUR, HOUR_2, HOUR_3, HOUR_4, DAY, WEEK, MONTH)
///@requestParam startdate Start date (yyyy:MM:dd-HH:mm:ss)
///@requestParam enddate End date (yyyy:MM:dd-HH:mm:ss). Must be later then the start date.
///</Summary>
public async Task<IgResponse<PriceList>> priceSearchByDate(string epic, string resolution, string startdate, string enddate)
{
return await _igRestService.RestfulService<PriceList>("/gateway/deal/prices/" + epic + "/" + resolution + "?startdate=" + startdate + "&enddate=" + enddate, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns a list of historical prices for the given epic, resolution and number of data points
///@pathParam epic Instrument epic
///@pathParam resolution Price resolution (MINUTE, MINUTE_2, MINUTE_3, MINUTE_5, MINUTE_10, MINUTE_15, MINUTE_30, HOUR, HOUR_2, HOUR_3, HOUR_4, DAY, WEEK, MONTH)
///@pathParam numPoints Number of data points required
///</Summary>
public async Task<IgResponse<PriceList>> priceSearchByNum(string epic, string resolution, string numPoints)
{
return await _igRestService.RestfulService<PriceList>("/gateway/deal/prices/" + epic + "/" + resolution + "/" + numPoints, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Returns a list of historical prices for the given epic, resolution and date range.
///@pathParam epic Instrument epic
///@pathParam resolution Price resolution (MINUTE, MINUTE_2, MINUTE_3, MINUTE_5, MINUTE_10, MINUTE_15, MINUTE_30, HOUR, HOUR_2, HOUR_3, HOUR_4, DAY, WEEK, MONTH)
///@pathParam startDate Start date (yyyy-MM-dd HH:mm:ss)
///@pathParam endDate End date (yyyy-MM-dd HH:mm:ss). Must be later then the start date.
///</Summary>
public async Task<IgResponse<PriceList>> priceSearchByDateV2(string epic, string resolution, string startDate, string endDate)
{
return await _igRestService.RestfulService<PriceList>("/gateway/deal/prices/" + epic + "/" + resolution + "/" + startDate + "/" + endDate, HttpMethod.Get, "2", _conversationContext);
}
///<Summary>
///Returns a list of historical prices for the given epic, resolution and number of data points
///@pathParam epic Instrument epic
///@pathParam resolution Price resolution (MINUTE, MINUTE_2, MINUTE_3, MINUTE_5, MINUTE_10, MINUTE_15, MINUTE_30, HOUR, HOUR_2, HOUR_3, HOUR_4, DAY, WEEK, MONTH)
///@pathParam numPoints Number of data points required
///</Summary>
public async Task<IgResponse<PriceList>> priceSearchByNumV2(string epic, string resolution, string numPoints)
{
return await _igRestService.RestfulService<PriceList>("/gateway/deal/prices/" + epic + "/" + resolution + "/" + numPoints, HttpMethod.Get, "2", _conversationContext);
}
///<Summary>
///Returns all markets matching the search term
///@return market search result
///@throws SearchMarketsException
///@requestParam searchTerm The term to be used in the search
///</Summary>
public async Task<IgResponse<SearchMarketsResponse>> searchMarket(string searchTerm)
{
return await _igRestService.RestfulService<SearchMarketsResponse>("/gateway/deal/markets?searchTerm=" + searchTerm, HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Deletes a watchlist
///@pathParam watchlistId Watchlist id
///</Summary>
public async Task<IgResponse<DeleteWatchlistResponse>> deleteWatchlist(string watchlistId)
{
return await _igRestService.RestfulService<DeleteWatchlistResponse>("/gateway/deal/watchlists/" + watchlistId, HttpMethod.Delete, "1", _conversationContext);
}
///<Summary>
///Creates a watchlist
///@param createWatchlistRequest Watchlist create request
///</Summary>
public async Task<IgResponse<CreateWatchlistResponse>> createWatchlist(CreateWatchlistRequest createWatchlistRequest)
{
return await _igRestService.RestfulService<CreateWatchlistResponse>("/gateway/deal/watchlists", HttpMethod.Post, "1", _conversationContext, createWatchlistRequest);
}
///<Summary>
///Adds a market to a watchlist
///@pathParam watchlistId Watchlist id
///@param addInstrumentToWatchlistRequest Add market to watchlist request
///</Summary>
public async Task<IgResponse<AddInstrumentToWatchlistResponse>> addInstrumentToWatchlist(string watchlistId, AddInstrumentToWatchlistRequest addInstrumentToWatchlistRequest)
{
return await _igRestService.RestfulService<AddInstrumentToWatchlistResponse>("/gateway/deal/watchlists/" + watchlistId, HttpMethod.Put, "1", _conversationContext, addInstrumentToWatchlistRequest);
}
///<Summary>
///Remove a market from a watchlist
///@pathParam watchlistId Watchlist id
///@pathParam epic Market epic
///</Summary>
public async Task<IgResponse<RemoveInstrumentFromWatchlistResponse>> removeInstrumentFromWatchlist(string watchlistId, string epic)
{
return await _igRestService.RestfulService<RemoveInstrumentFromWatchlistResponse>("/gateway/deal/watchlists/" + watchlistId + "/" + epic, HttpMethod.Delete, "1", _conversationContext);
}
///<Summary>
///Returns all open working orders for the active account
///</Summary>
public async Task<IgResponse<dto.endpoint.workingorders.get.v1.WorkingOrdersResponse>> workingOrdersV1()
{
return await _igRestService.RestfulService<dto.endpoint.workingorders.get.v1.WorkingOrdersResponse>("/gateway/deal/workingorders", HttpMethod.Get, "1", _conversationContext);
}
///<Summary>
///Creates an OTC working order
///@deprecated Use version 2 of the service instead
///@param createWorkingOrderRequest Create working order request data
///</Summary>
public async Task<IgResponse<CreateWorkingOrderResponse>> createWorkingOrderV1(dto.endpoint.workingorders.create.v1.CreateWorkingOrderRequest createWorkingOrderRequest)
{
return await _igRestService.RestfulService<CreateWorkingOrderResponse>("/gateway/deal/workingorders/otc", HttpMethod.Post, "1", _conversationContext, createWorkingOrderRequest);
}
///<Summary>
///Creates an OTC working order
///@param createWorkingOrderRequest Create working order request data
///</Summary>
public async Task<IgResponse<CreateWorkingOrderResponse>> createWorkingOrderV2(dto.endpoint.workingorders.create.v2.CreateWorkingOrderRequest createWorkingOrderRequest)
{
return await _igRestService.RestfulService<CreateWorkingOrderResponse>("/gateway/deal/workingorders/otc", HttpMethod.Post, "2", _conversationContext, createWorkingOrderRequest);
}
///<Summary>
///Updates an OTC working order
///@deprecated Use version 2 of the service instead
///@pathParam dealId Deal identifier
///@param editWorkingOrderRequest Update working order request data
///</Summary>
public async Task<IgResponse<EditWorkingOrderResponse>> editWorkingOrderV1(string dealId, dto.endpoint.workingorders.edit.v1.EditWorkingOrderRequest editWorkingOrderRequest)
{
return await _igRestService.RestfulService<EditWorkingOrderResponse>("/gateway/deal/workingorders/otc/" + dealId, HttpMethod.Put, "1", _conversationContext, editWorkingOrderRequest);
}
///<Summary>
///Updates an OTC working order
///@pathParam dealId Deal identifier
///@param editWorkingOrderRequest Update working order request data
///</Summary>
public async Task<IgResponse<EditWorkingOrderResponse>> editWorkingOrderV2(string dealId, dto.endpoint.workingorders.edit.v2.EditWorkingOrderRequest editWorkingOrderRequest)
{
return await _igRestService.RestfulService<EditWorkingOrderResponse>("/gateway/deal/workingorders/otc/" + dealId, HttpMethod.Put, "2", _conversationContext, editWorkingOrderRequest);
}
///<Summary>
///Deletes an OTC working order
///@pathParam dealId Deal identifier
///@param deleteWorkingOrderRequest Delete working order request data
///</Summary>
public async Task<IgResponse<DeleteWorkingOrderResponse>> deleteWorkingOrder(string dealId, DeleteWorkingOrderRequest deleteWorkingOrderRequest)
{
return await _igRestService.RestfulService<DeleteWorkingOrderResponse>("/gateway/deal/workingorders/otc/" + dealId, HttpMethod.Delete, "1", _conversationContext, deleteWorkingOrderRequest);
}
}
}
| |
namespace PackageEditor
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.fsFolderTree = new System.Windows.Forms.TreeView();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.fsFilesList = new System.Windows.Forms.ListView();
this.columnFileName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnFileSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnFileType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.fileContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.fileContextMenuDelete = new System.Windows.Forms.ToolStripMenuItem();
this.fileContextMenuProperties = new System.Windows.Forms.ToolStripMenuItem();
this.panel2 = new System.Windows.Forms.Panel();
this.panel3 = new System.Windows.Forms.Panel();
this.fsFolderInfoIsolationCombo = new System.Windows.Forms.ComboBox();
this.fsFolderInfoIsolationLbl = new System.Windows.Forms.Label();
this.fsFolderInfoFullName = new System.Windows.Forms.Label();
this.regSplitContainer = new System.Windows.Forms.SplitContainer();
this.regFolderTree = new System.Windows.Forms.TreeView();
this.ContextMenuStripRegistryFolder = new System.Windows.Forms.ContextMenuStrip(this.components);
this.toolStripMenuItemExport = new System.Windows.Forms.ToolStripMenuItem();
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tbType = new System.Windows.Forms.TextBox();
this.tbValue = new System.Windows.Forms.TextBox();
this.tbSize = new System.Windows.Forms.TextBox();
this.tbFile = new System.Windows.Forms.TextBox();
this.panel4 = new System.Windows.Forms.Panel();
this.panel6 = new System.Windows.Forms.Panel();
this.regFolderInfoIsolationCombo = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.regFolderInfoFullName = new System.Windows.Forms.Label();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveasToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportXmlToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.langToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.englishMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.frenchMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.spanishMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.chineseMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.regProgressTimer = new System.Windows.Forms.Timer(this.components);
this.itemHoverTimer = new System.Windows.Forms.Timer(this.components);
this.tabControl = new System.Windows.Forms.TabControl();
this.tabGeneral = new System.Windows.Forms.TabPage();
this.dropboxLabel = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.label10 = new System.Windows.Forms.Label();
this.propertyFileVersion = new System.Windows.Forms.TextBox();
this.lnkChangeIcon = new System.Windows.Forms.LinkLabel();
this.label2 = new System.Windows.Forms.Label();
this.propertyFriendlyName = new System.Windows.Forms.TextBox();
this.propertyIcon = new System.Windows.Forms.PictureBox();
this.propertyAppID = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox11 = new System.Windows.Forms.GroupBox();
this.lnkAutoLaunch = new System.Windows.Forms.LinkLabel();
this.lnkChangeDataStorage = new System.Windows.Forms.LinkLabel();
this.propertyAutoLaunch = new System.Windows.Forms.Label();
this.propertyDataStorage = new System.Windows.Forms.Label();
this.groupBox9 = new System.Windows.Forms.GroupBox();
this.helpVirtMode = new System.Windows.Forms.Label();
this.picRAM = new System.Windows.Forms.PictureBox();
this.picDisk = new System.Windows.Forms.PictureBox();
this.propertyVirtModeRam = new System.Windows.Forms.RadioButton();
this.propertyVirtModeDisk = new System.Windows.Forms.RadioButton();
this.label9 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.lblAutoLaunch = new System.Windows.Forms.Label();
this.groupBox10 = new System.Windows.Forms.GroupBox();
this.picFullAccess = new System.Windows.Forms.PictureBox();
this.picIsolatedMode = new System.Windows.Forms.PictureBox();
this.helpIsolationMode = new System.Windows.Forms.Label();
this.picDataMode = new System.Windows.Forms.PictureBox();
this.propertyIsolationDataMode = new System.Windows.Forms.RadioButton();
this.propertyIsolationIsolated = new System.Windows.Forms.RadioButton();
this.propertyIsolationMerge = new System.Windows.Forms.RadioButton();
this.dropboxButton = new System.Windows.Forms.Button();
this.tabFileSystem = new System.Windows.Forms.TabPage();
this.panel5 = new System.Windows.Forms.Panel();
this.fileToolStrip = new System.Windows.Forms.ToolStrip();
this.fsAddBtn = new System.Windows.Forms.ToolStripButton();
this.fsAddEmptyDirBtn = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.fsRemoveBtn = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.fsAddDirBtn = new System.Windows.Forms.ToolStripButton();
this.fsSaveFileAsBtn = new System.Windows.Forms.ToolStripButton();
this.tabRegistry = new System.Windows.Forms.TabPage();
this.panel8 = new System.Windows.Forms.Panel();
this.panel1 = new System.Windows.Forms.Panel();
this.panel7 = new System.Windows.Forms.Panel();
this.regProgressBar = new System.Windows.Forms.ProgressBar();
this.regToolStrip = new System.Windows.Forms.ToolStrip();
this.regRemoveBtn = new System.Windows.Forms.ToolStripButton();
this.regEditBtn = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.regImportBtn = new System.Windows.Forms.ToolStripButton();
this.regExportBtn = new System.Windows.Forms.ToolStripButton();
this.tabAdvanced = new System.Windows.Forms.TabPage();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.cbVolatileRegistry = new System.Windows.Forms.CheckBox();
this.propertyScmDirect = new System.Windows.Forms.CheckBox();
this.propertyDisplayLogo = new System.Windows.Forms.CheckBox();
this.cbDatFile = new System.Windows.Forms.CheckBox();
this.lnkAutoUpdate = new System.Windows.Forms.LinkLabel();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.lnkCustomEvents = new System.Windows.Forms.LinkLabel();
this.propertyStopInheritance = new System.Windows.Forms.TextBox();
this.groupBox7 = new System.Windows.Forms.GroupBox();
this.chkCleanDoneDialog = new System.Windows.Forms.CheckBox();
this.rdbCleanNone = new System.Windows.Forms.RadioButton();
this.chkCleanAsk = new System.Windows.Forms.CheckBox();
this.rdbCleanAll = new System.Windows.Forms.RadioButton();
this.rdbCleanRegOnly = new System.Windows.Forms.RadioButton();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.rdbIntegrateVirtual = new System.Windows.Forms.RadioButton();
this.rdbIntegrateStandard = new System.Windows.Forms.RadioButton();
this.rdbIntegrateNone = new System.Windows.Forms.RadioButton();
this.tabSecurity = new System.Windows.Forms.TabPage();
this.panel10 = new System.Windows.Forms.Panel();
this.groupDataEncrypt = new System.Windows.Forms.GroupBox();
this.panel16 = new System.Windows.Forms.Panel();
this.lnkExportPwdKey = new System.Windows.Forms.LinkLabel();
this.lnkImportPwdKey = new System.Windows.Forms.LinkLabel();
this.propertyEncryptUserCreatedPassword = new System.Windows.Forms.RadioButton();
this.lnkEncryptionLearnMore = new System.Windows.Forms.LinkLabel();
this.label12 = new System.Windows.Forms.Label();
this.tbEncryptionPwdConfirm = new System.Windows.Forms.TextBox();
this.tbEncryptionPwd = new System.Windows.Forms.TextBox();
this.lnkGenerateEncKey = new System.Windows.Forms.LinkLabel();
this.tbEncryptionKey = new System.Windows.Forms.TextBox();
this.propertyEncryptUsingPassword = new System.Windows.Forms.RadioButton();
this.propertyEncryptUsingKey = new System.Windows.Forms.RadioButton();
this.propertyEncryption = new System.Windows.Forms.CheckBox();
this.groupUsageRights = new System.Windows.Forms.GroupBox();
this.lnkActiveDirectory = new System.Windows.Forms.LinkLabel();
this.groupExpiration = new System.Windows.Forms.GroupBox();
this.propertyExpirationDatePicker = new System.Windows.Forms.DateTimePicker();
this.propertyExpiration = new System.Windows.Forms.CheckBox();
this.propertyTtlDays = new System.Windows.Forms.CheckBox();
this.propertyTtlResistRemove = new System.Windows.Forms.CheckBox();
this.propertyTtlDaysValue = new System.Windows.Forms.NumericUpDown();
this.groupEditProtect = new System.Windows.Forms.GroupBox();
this.label6 = new System.Windows.Forms.Label();
this.tbPasswordConfirm = new System.Windows.Forms.TextBox();
this.propertyProtPassword = new System.Windows.Forms.TextBox();
this.propertyProt = new System.Windows.Forms.CheckBox();
this.tabWelcome = new System.Windows.Forms.TabPage();
this.panelWelcome = new System.Windows.Forms.Panel();
this.panel13 = new System.Windows.Forms.Panel();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.listViewMRU = new System.Windows.Forms.ListView();
this.columnFileN = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.imageListMRU = new System.Windows.Forms.ImageList(this.components);
this.lnkPackageEdit = new System.Windows.Forms.LinkLabel();
this.panel9 = new System.Windows.Forms.Panel();
this.label11 = new System.Windows.Forms.Label();
this.line = new System.Windows.Forms.GroupBox();
this.bkPanel = new System.Windows.Forms.Panel();
this.panelLicense = new System.Windows.Forms.Panel();
this.lnkUpgrade = new System.Windows.Forms.LinkLabel();
this.lblNotCommercial = new System.Windows.Forms.Label();
this.regFilesList = new PackageEditor.ListViewEx();
this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.fileContextMenu.SuspendLayout();
this.panel2.SuspendLayout();
this.panel3.SuspendLayout();
this.regSplitContainer.Panel1.SuspendLayout();
this.regSplitContainer.Panel2.SuspendLayout();
this.regSplitContainer.SuspendLayout();
this.ContextMenuStripRegistryFolder.SuspendLayout();
this.panel4.SuspendLayout();
this.panel6.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.tabControl.SuspendLayout();
this.tabGeneral.SuspendLayout();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.propertyIcon)).BeginInit();
this.groupBox1.SuspendLayout();
this.groupBox11.SuspendLayout();
this.groupBox9.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picRAM)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picDisk)).BeginInit();
this.groupBox10.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picFullAccess)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picIsolatedMode)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picDataMode)).BeginInit();
this.tabFileSystem.SuspendLayout();
this.panel5.SuspendLayout();
this.fileToolStrip.SuspendLayout();
this.tabRegistry.SuspendLayout();
this.panel8.SuspendLayout();
this.panel1.SuspendLayout();
this.panel7.SuspendLayout();
this.regToolStrip.SuspendLayout();
this.tabAdvanced.SuspendLayout();
this.groupBox5.SuspendLayout();
this.groupBox7.SuspendLayout();
this.groupBox4.SuspendLayout();
this.tabSecurity.SuspendLayout();
this.groupDataEncrypt.SuspendLayout();
this.panel16.SuspendLayout();
this.groupUsageRights.SuspendLayout();
this.groupExpiration.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.propertyTtlDaysValue)).BeginInit();
this.groupEditProtect.SuspendLayout();
this.tabWelcome.SuspendLayout();
this.panelWelcome.SuspendLayout();
this.panel13.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.panel9.SuspendLayout();
this.bkPanel.SuspendLayout();
this.panelLicense.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
resources.ApplyResources(this.splitContainer1, "splitContainer1");
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.fsFolderTree);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.fsFilesList);
this.splitContainer1.Panel2.Controls.Add(this.panel2);
//
// fsFolderTree
//
this.fsFolderTree.AllowDrop = true;
resources.ApplyResources(this.fsFolderTree, "fsFolderTree");
this.fsFolderTree.ImageList = this.imageList;
this.fsFolderTree.Name = "fsFolderTree";
this.fsFolderTree.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.fsFolderTree_ItemDrag);
this.fsFolderTree.BeforeSelect += new System.Windows.Forms.TreeViewCancelEventHandler(this.fsFolderTree_BeforeSelect);
this.fsFolderTree.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.fsFolderTree_AfterSelect);
this.fsFolderTree.DragDrop += new System.Windows.Forms.DragEventHandler(this.Vfs_DragDrop);
this.fsFolderTree.DragEnter += new System.Windows.Forms.DragEventHandler(this.Vfs_DragEnter);
this.fsFolderTree.DragOver += new System.Windows.Forms.DragEventHandler(this.fsFolderTree_DragOver);
//
// imageList
//
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.Red;
this.imageList.Images.SetKeyName(0, "folder_fullaccess.png");
this.imageList.Images.SetKeyName(1, "folder");
this.imageList.Images.SetKeyName(2, "folder_strictlyisolated.png");
this.imageList.Images.SetKeyName(3, "remove");
this.imageList.Images.SetKeyName(4, "058.png");
this.imageList.Images.SetKeyName(5, "folder_opened");
this.imageList.Images.SetKeyName(6, "new_document");
this.imageList.Images.SetKeyName(7, "078b.png");
this.imageList.Images.SetKeyName(8, "add");
//
// fsFilesList
//
this.fsFilesList.AllowDrop = true;
this.fsFilesList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnFileName,
this.columnFileSize,
this.columnFileType});
this.fsFilesList.ContextMenuStrip = this.fileContextMenu;
resources.ApplyResources(this.fsFilesList, "fsFilesList");
this.fsFilesList.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
((System.Windows.Forms.ListViewItem)(resources.GetObject("fsFilesList.Items"))),
((System.Windows.Forms.ListViewItem)(resources.GetObject("fsFilesList.Items1")))});
this.fsFilesList.Name = "fsFilesList";
this.fsFilesList.SmallImageList = this.imageList;
this.fsFilesList.UseCompatibleStateImageBehavior = false;
this.fsFilesList.View = System.Windows.Forms.View.Details;
this.fsFilesList.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.fsFilesList_ColumnClick);
this.fsFilesList.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.fsFilesList_ItemDrag);
this.fsFilesList.DragDrop += new System.Windows.Forms.DragEventHandler(this.Vfs_DragDrop);
this.fsFilesList.DragEnter += new System.Windows.Forms.DragEventHandler(this.Vfs_DragEnter);
this.fsFilesList.DoubleClick += new System.EventHandler(this.fileContextMenuProperties_Click);
//
// columnFileName
//
resources.ApplyResources(this.columnFileName, "columnFileName");
//
// columnFileSize
//
resources.ApplyResources(this.columnFileSize, "columnFileSize");
//
// columnFileType
//
resources.ApplyResources(this.columnFileType, "columnFileType");
//
// fileContextMenu
//
this.fileContextMenu.ImageScalingSize = new System.Drawing.Size(20, 20);
this.fileContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileContextMenuDelete,
this.fileContextMenuProperties});
this.fileContextMenu.Name = "fileContextMenu";
resources.ApplyResources(this.fileContextMenu, "fileContextMenu");
//
// fileContextMenuDelete
//
this.fileContextMenuDelete.Name = "fileContextMenuDelete";
resources.ApplyResources(this.fileContextMenuDelete, "fileContextMenuDelete");
this.fileContextMenuDelete.Click += new System.EventHandler(this.fileContextMenuDelete_Click);
//
// fileContextMenuProperties
//
this.fileContextMenuProperties.Name = "fileContextMenuProperties";
resources.ApplyResources(this.fileContextMenuProperties, "fileContextMenuProperties");
this.fileContextMenuProperties.Click += new System.EventHandler(this.fileContextMenuProperties_Click);
//
// panel2
//
this.panel2.Controls.Add(this.panel3);
this.panel2.Controls.Add(this.fsFolderInfoFullName);
resources.ApplyResources(this.panel2, "panel2");
this.panel2.Name = "panel2";
//
// panel3
//
this.panel3.Controls.Add(this.fsFolderInfoIsolationCombo);
this.panel3.Controls.Add(this.fsFolderInfoIsolationLbl);
resources.ApplyResources(this.panel3, "panel3");
this.panel3.Name = "panel3";
//
// fsFolderInfoIsolationCombo
//
this.fsFolderInfoIsolationCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.fsFolderInfoIsolationCombo.FormattingEnabled = true;
resources.ApplyResources(this.fsFolderInfoIsolationCombo, "fsFolderInfoIsolationCombo");
this.fsFolderInfoIsolationCombo.Name = "fsFolderInfoIsolationCombo";
//
// fsFolderInfoIsolationLbl
//
resources.ApplyResources(this.fsFolderInfoIsolationLbl, "fsFolderInfoIsolationLbl");
this.fsFolderInfoIsolationLbl.Name = "fsFolderInfoIsolationLbl";
//
// fsFolderInfoFullName
//
resources.ApplyResources(this.fsFolderInfoFullName, "fsFolderInfoFullName");
this.fsFolderInfoFullName.Name = "fsFolderInfoFullName";
//
// regSplitContainer
//
resources.ApplyResources(this.regSplitContainer, "regSplitContainer");
this.regSplitContainer.Name = "regSplitContainer";
//
// regSplitContainer.Panel1
//
this.regSplitContainer.Panel1.Controls.Add(this.regFolderTree);
//
// regSplitContainer.Panel2
//
this.regSplitContainer.Panel2.Controls.Add(this.tbType);
this.regSplitContainer.Panel2.Controls.Add(this.tbValue);
this.regSplitContainer.Panel2.Controls.Add(this.tbSize);
this.regSplitContainer.Panel2.Controls.Add(this.tbFile);
this.regSplitContainer.Panel2.Controls.Add(this.regFilesList);
this.regSplitContainer.Panel2.Controls.Add(this.panel4);
//
// regFolderTree
//
this.regFolderTree.ContextMenuStrip = this.ContextMenuStripRegistryFolder;
resources.ApplyResources(this.regFolderTree, "regFolderTree");
this.regFolderTree.ImageList = this.imageList;
this.regFolderTree.Name = "regFolderTree";
//
// ContextMenuStripRegistryFolder
//
this.ContextMenuStripRegistryFolder.ImageScalingSize = new System.Drawing.Size(20, 20);
this.ContextMenuStripRegistryFolder.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItemExport,
this.deleteToolStripMenuItem});
this.ContextMenuStripRegistryFolder.Name = "Export";
resources.ApplyResources(this.ContextMenuStripRegistryFolder, "ContextMenuStripRegistryFolder");
//
// toolStripMenuItemExport
//
this.toolStripMenuItemExport.Name = "toolStripMenuItemExport";
resources.ApplyResources(this.toolStripMenuItemExport, "toolStripMenuItemExport");
this.toolStripMenuItemExport.Click += new System.EventHandler(this.toolStripMenuItemExport_Click);
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
resources.ApplyResources(this.deleteToolStripMenuItem, "deleteToolStripMenuItem");
this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripMenuItem_Click);
//
// tbType
//
this.tbType.BackColor = System.Drawing.SystemColors.Window;
resources.ApplyResources(this.tbType, "tbType");
this.tbType.Name = "tbType";
this.tbType.ReadOnly = true;
//
// tbValue
//
resources.ApplyResources(this.tbValue, "tbValue");
this.tbValue.Name = "tbValue";
//
// tbSize
//
this.tbSize.BackColor = System.Drawing.SystemColors.Window;
resources.ApplyResources(this.tbSize, "tbSize");
this.tbSize.Name = "tbSize";
this.tbSize.ReadOnly = true;
//
// tbFile
//
this.tbFile.BackColor = System.Drawing.SystemColors.Window;
resources.ApplyResources(this.tbFile, "tbFile");
this.tbFile.Name = "tbFile";
this.tbFile.ReadOnly = true;
//
// panel4
//
this.panel4.Controls.Add(this.panel6);
this.panel4.Controls.Add(this.regFolderInfoFullName);
resources.ApplyResources(this.panel4, "panel4");
this.panel4.Name = "panel4";
//
// panel6
//
this.panel6.Controls.Add(this.regFolderInfoIsolationCombo);
this.panel6.Controls.Add(this.label3);
resources.ApplyResources(this.panel6, "panel6");
this.panel6.Name = "panel6";
//
// regFolderInfoIsolationCombo
//
this.regFolderInfoIsolationCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.regFolderInfoIsolationCombo.FormattingEnabled = true;
resources.ApplyResources(this.regFolderInfoIsolationCombo, "regFolderInfoIsolationCombo");
this.regFolderInfoIsolationCombo.Name = "regFolderInfoIsolationCombo";
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// regFolderInfoFullName
//
resources.ApplyResources(this.regFolderInfoFullName, "regFolderInfoFullName");
this.regFolderInfoFullName.Name = "regFolderInfoFullName";
//
// menuStrip1
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
resources.ApplyResources(this.menuStrip1, "menuStrip1");
this.menuStrip1.Name = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.newToolStripMenuItem,
this.saveToolStripMenuItem,
this.saveasToolStripMenuItem,
this.closeToolStripMenuItem,
this.exportXmlToolStripMenuItem,
this.langToolStripMenuItem,
this.toolStripMenuItem1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
resources.ApplyResources(this.openToolStripMenuItem, "openToolStripMenuItem");
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
resources.ApplyResources(this.newToolStripMenuItem, "newToolStripMenuItem");
this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
resources.ApplyResources(this.saveToolStripMenuItem, "saveToolStripMenuItem");
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// saveasToolStripMenuItem
//
this.saveasToolStripMenuItem.Name = "saveasToolStripMenuItem";
resources.ApplyResources(this.saveasToolStripMenuItem, "saveasToolStripMenuItem");
this.saveasToolStripMenuItem.Click += new System.EventHandler(this.saveasToolStripMenuItem_Click);
//
// closeToolStripMenuItem
//
this.closeToolStripMenuItem.Name = "closeToolStripMenuItem";
resources.ApplyResources(this.closeToolStripMenuItem, "closeToolStripMenuItem");
this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click);
//
// exportXmlToolStripMenuItem
//
this.exportXmlToolStripMenuItem.Name = "exportXmlToolStripMenuItem";
resources.ApplyResources(this.exportXmlToolStripMenuItem, "exportXmlToolStripMenuItem");
this.exportXmlToolStripMenuItem.Click += new System.EventHandler(this.exportXmlToolStripMenuItem_Click);
//
// langToolStripMenuItem
//
this.langToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.englishMenuItem,
this.frenchMenuItem,
this.spanishMenuItem,
this.chineseMenuItem});
this.langToolStripMenuItem.Name = "langToolStripMenuItem";
resources.ApplyResources(this.langToolStripMenuItem, "langToolStripMenuItem");
//
// englishMenuItem
//
this.englishMenuItem.Name = "englishMenuItem";
resources.ApplyResources(this.englishMenuItem, "englishMenuItem");
this.englishMenuItem.Click += new System.EventHandler(this.langMenuItem_Click);
//
// frenchMenuItem
//
this.frenchMenuItem.Name = "frenchMenuItem";
resources.ApplyResources(this.frenchMenuItem, "frenchMenuItem");
this.frenchMenuItem.Click += new System.EventHandler(this.langMenuItem_Click);
//
// spanishMenuItem
//
this.spanishMenuItem.Name = "spanishMenuItem";
resources.ApplyResources(this.spanishMenuItem, "spanishMenuItem");
this.spanishMenuItem.Click += new System.EventHandler(this.langMenuItem_Click);
//
// chineseMenuItem
//
this.chineseMenuItem.Name = "chineseMenuItem";
resources.ApplyResources(this.chineseMenuItem, "chineseMenuItem");
this.chineseMenuItem.Click += new System.EventHandler(this.langMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1");
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem");
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// regProgressTimer
//
this.regProgressTimer.Tick += new System.EventHandler(this.regProgressTimer_Tick);
//
// itemHoverTimer
//
this.itemHoverTimer.Tick += new System.EventHandler(this.OnItemHover);
//
// tabControl
//
resources.ApplyResources(this.tabControl, "tabControl");
this.tabControl.Controls.Add(this.tabGeneral);
this.tabControl.Controls.Add(this.tabFileSystem);
this.tabControl.Controls.Add(this.tabRegistry);
this.tabControl.Controls.Add(this.tabAdvanced);
this.tabControl.Controls.Add(this.tabSecurity);
this.tabControl.Controls.Add(this.tabWelcome);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.SelectedIndexChanged += new System.EventHandler(this.tabControl_SelectedIndexChanged);
//
// tabGeneral
//
this.tabGeneral.BackColor = System.Drawing.Color.White;
this.tabGeneral.Controls.Add(this.dropboxLabel);
this.tabGeneral.Controls.Add(this.groupBox3);
this.tabGeneral.Controls.Add(this.groupBox1);
this.tabGeneral.Controls.Add(this.dropboxButton);
resources.ApplyResources(this.tabGeneral, "tabGeneral");
this.tabGeneral.Name = "tabGeneral";
//
// dropboxLabel
//
resources.ApplyResources(this.dropboxLabel, "dropboxLabel");
this.dropboxLabel.Name = "dropboxLabel";
//
// groupBox3
//
this.groupBox3.Controls.Add(this.label10);
this.groupBox3.Controls.Add(this.propertyFileVersion);
this.groupBox3.Controls.Add(this.lnkChangeIcon);
this.groupBox3.Controls.Add(this.label2);
this.groupBox3.Controls.Add(this.propertyFriendlyName);
this.groupBox3.Controls.Add(this.propertyIcon);
this.groupBox3.Controls.Add(this.propertyAppID);
this.groupBox3.Controls.Add(this.label1);
resources.ApplyResources(this.groupBox3, "groupBox3");
this.groupBox3.Name = "groupBox3";
this.groupBox3.TabStop = false;
//
// label10
//
resources.ApplyResources(this.label10, "label10");
this.label10.Name = "label10";
//
// propertyFileVersion
//
resources.ApplyResources(this.propertyFileVersion, "propertyFileVersion");
this.propertyFileVersion.Name = "propertyFileVersion";
this.propertyFileVersion.TextChanged += new System.EventHandler(this.PropertyChange);
//
// lnkChangeIcon
//
resources.ApplyResources(this.lnkChangeIcon, "lnkChangeIcon");
this.lnkChangeIcon.Name = "lnkChangeIcon";
this.lnkChangeIcon.TabStop = true;
this.lnkChangeIcon.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkChangeIcon_LinkClicked);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// propertyFriendlyName
//
resources.ApplyResources(this.propertyFriendlyName, "propertyFriendlyName");
this.propertyFriendlyName.Name = "propertyFriendlyName";
this.propertyFriendlyName.TextChanged += new System.EventHandler(this.PropertyChange);
//
// propertyIcon
//
resources.ApplyResources(this.propertyIcon, "propertyIcon");
this.propertyIcon.Name = "propertyIcon";
this.propertyIcon.TabStop = false;
//
// propertyAppID
//
resources.ApplyResources(this.propertyAppID, "propertyAppID");
this.propertyAppID.Name = "propertyAppID";
this.propertyAppID.TextChanged += new System.EventHandler(this.PropertyChange);
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Controls.Add(this.groupBox11);
this.groupBox1.Controls.Add(this.groupBox9);
this.groupBox1.Controls.Add(this.label9);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.lblAutoLaunch);
this.groupBox1.Controls.Add(this.groupBox10);
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// groupBox11
//
resources.ApplyResources(this.groupBox11, "groupBox11");
this.groupBox11.Controls.Add(this.lnkAutoLaunch);
this.groupBox11.Controls.Add(this.lnkChangeDataStorage);
this.groupBox11.Controls.Add(this.propertyAutoLaunch);
this.groupBox11.Controls.Add(this.propertyDataStorage);
this.groupBox11.Name = "groupBox11";
this.groupBox11.TabStop = false;
//
// lnkAutoLaunch
//
resources.ApplyResources(this.lnkAutoLaunch, "lnkAutoLaunch");
this.lnkAutoLaunch.Name = "lnkAutoLaunch";
this.lnkAutoLaunch.TabStop = true;
this.lnkAutoLaunch.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkAutoLaunch_LinkClicked);
//
// lnkChangeDataStorage
//
resources.ApplyResources(this.lnkChangeDataStorage, "lnkChangeDataStorage");
this.lnkChangeDataStorage.Name = "lnkChangeDataStorage";
this.lnkChangeDataStorage.TabStop = true;
this.lnkChangeDataStorage.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkChangeDataStorage_LinkClicked);
//
// propertyAutoLaunch
//
resources.ApplyResources(this.propertyAutoLaunch, "propertyAutoLaunch");
this.propertyAutoLaunch.Name = "propertyAutoLaunch";
//
// propertyDataStorage
//
resources.ApplyResources(this.propertyDataStorage, "propertyDataStorage");
this.propertyDataStorage.Name = "propertyDataStorage";
//
// groupBox9
//
resources.ApplyResources(this.groupBox9, "groupBox9");
this.groupBox9.Controls.Add(this.helpVirtMode);
this.groupBox9.Controls.Add(this.picRAM);
this.groupBox9.Controls.Add(this.picDisk);
this.groupBox9.Controls.Add(this.propertyVirtModeRam);
this.groupBox9.Controls.Add(this.propertyVirtModeDisk);
this.groupBox9.Name = "groupBox9";
this.groupBox9.TabStop = false;
//
// helpVirtMode
//
resources.ApplyResources(this.helpVirtMode, "helpVirtMode");
this.helpVirtMode.Name = "helpVirtMode";
//
// picRAM
//
this.picRAM.Image = global::PackageEditor.Properties.Resources.RAM;
resources.ApplyResources(this.picRAM, "picRAM");
this.picRAM.Name = "picRAM";
this.picRAM.TabStop = false;
//
// picDisk
//
this.picDisk.Image = global::PackageEditor.Properties.Resources.HardDisk;
resources.ApplyResources(this.picDisk, "picDisk");
this.picDisk.Name = "picDisk";
this.picDisk.TabStop = false;
//
// propertyVirtModeRam
//
resources.ApplyResources(this.propertyVirtModeRam, "propertyVirtModeRam");
this.propertyVirtModeRam.Name = "propertyVirtModeRam";
this.propertyVirtModeRam.TabStop = true;
this.propertyVirtModeRam.UseVisualStyleBackColor = true;
this.propertyVirtModeRam.CheckedChanged += new System.EventHandler(this.propertyVirtMode_CheckedChanged);
this.propertyVirtModeRam.Click += new System.EventHandler(this.PropertyChange);
//
// propertyVirtModeDisk
//
resources.ApplyResources(this.propertyVirtModeDisk, "propertyVirtModeDisk");
this.propertyVirtModeDisk.Name = "propertyVirtModeDisk";
this.propertyVirtModeDisk.TabStop = true;
this.propertyVirtModeDisk.UseVisualStyleBackColor = true;
this.propertyVirtModeDisk.CheckedChanged += new System.EventHandler(this.propertyVirtMode_CheckedChanged);
this.propertyVirtModeDisk.Click += new System.EventHandler(this.PropertyChange);
//
// label9
//
resources.ApplyResources(this.label9, "label9");
this.label9.Name = "label9";
//
// label5
//
resources.ApplyResources(this.label5, "label5");
this.label5.Name = "label5";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// lblAutoLaunch
//
resources.ApplyResources(this.lblAutoLaunch, "lblAutoLaunch");
this.lblAutoLaunch.Name = "lblAutoLaunch";
//
// groupBox10
//
resources.ApplyResources(this.groupBox10, "groupBox10");
this.groupBox10.Controls.Add(this.picFullAccess);
this.groupBox10.Controls.Add(this.picIsolatedMode);
this.groupBox10.Controls.Add(this.helpIsolationMode);
this.groupBox10.Controls.Add(this.picDataMode);
this.groupBox10.Controls.Add(this.propertyIsolationDataMode);
this.groupBox10.Controls.Add(this.propertyIsolationIsolated);
this.groupBox10.Controls.Add(this.propertyIsolationMerge);
this.groupBox10.Name = "groupBox10";
this.groupBox10.TabStop = false;
//
// picFullAccess
//
resources.ApplyResources(this.picFullAccess, "picFullAccess");
this.picFullAccess.Image = global::PackageEditor.Properties.Resources._033;
this.picFullAccess.Name = "picFullAccess";
this.picFullAccess.TabStop = false;
//
// picIsolatedMode
//
resources.ApplyResources(this.picIsolatedMode, "picIsolatedMode");
this.picIsolatedMode.Image = global::PackageEditor.Properties.Resources._032;
this.picIsolatedMode.Name = "picIsolatedMode";
this.picIsolatedMode.TabStop = false;
//
// helpIsolationMode
//
resources.ApplyResources(this.helpIsolationMode, "helpIsolationMode");
this.helpIsolationMode.Name = "helpIsolationMode";
//
// picDataMode
//
resources.ApplyResources(this.picDataMode, "picDataMode");
this.picDataMode.Image = global::PackageEditor.Properties.Resources.DataMode;
this.picDataMode.Name = "picDataMode";
this.picDataMode.TabStop = false;
//
// propertyIsolationDataMode
//
resources.ApplyResources(this.propertyIsolationDataMode, "propertyIsolationDataMode");
this.propertyIsolationDataMode.Name = "propertyIsolationDataMode";
this.propertyIsolationDataMode.TabStop = true;
this.propertyIsolationDataMode.UseVisualStyleBackColor = true;
this.propertyIsolationDataMode.CheckedChanged += new System.EventHandler(this.propertyIsolationMode_CheckedChanged);
this.propertyIsolationDataMode.Click += new System.EventHandler(this.IsolationChanged);
//
// propertyIsolationIsolated
//
resources.ApplyResources(this.propertyIsolationIsolated, "propertyIsolationIsolated");
this.propertyIsolationIsolated.Name = "propertyIsolationIsolated";
this.propertyIsolationIsolated.TabStop = true;
this.propertyIsolationIsolated.UseVisualStyleBackColor = true;
this.propertyIsolationIsolated.CheckedChanged += new System.EventHandler(this.propertyIsolationMode_CheckedChanged);
this.propertyIsolationIsolated.Click += new System.EventHandler(this.IsolationChanged);
//
// propertyIsolationMerge
//
resources.ApplyResources(this.propertyIsolationMerge, "propertyIsolationMerge");
this.propertyIsolationMerge.Name = "propertyIsolationMerge";
this.propertyIsolationMerge.TabStop = true;
this.propertyIsolationMerge.UseVisualStyleBackColor = true;
this.propertyIsolationMerge.CheckedChanged += new System.EventHandler(this.propertyIsolationMode_CheckedChanged);
this.propertyIsolationMerge.Click += new System.EventHandler(this.IsolationChanged);
//
// dropboxButton
//
resources.ApplyResources(this.dropboxButton, "dropboxButton");
this.dropboxButton.Name = "dropboxButton";
this.dropboxButton.UseVisualStyleBackColor = true;
this.dropboxButton.Click += new System.EventHandler(this.dropboxButton_Click);
//
// tabFileSystem
//
this.tabFileSystem.BackColor = System.Drawing.Color.White;
this.tabFileSystem.Controls.Add(this.panel5);
this.tabFileSystem.Controls.Add(this.fileToolStrip);
resources.ApplyResources(this.tabFileSystem, "tabFileSystem");
this.tabFileSystem.Name = "tabFileSystem";
//
// panel5
//
this.panel5.Controls.Add(this.splitContainer1);
resources.ApplyResources(this.panel5, "panel5");
this.panel5.Name = "panel5";
//
// fileToolStrip
//
this.fileToolStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.fileToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fsAddBtn,
this.fsAddEmptyDirBtn,
this.toolStripSeparator3,
this.fsRemoveBtn,
this.toolStripSeparator4,
this.fsAddDirBtn,
this.fsSaveFileAsBtn});
resources.ApplyResources(this.fileToolStrip, "fileToolStrip");
this.fileToolStrip.Name = "fileToolStrip";
//
// fsAddBtn
//
this.fsAddBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.fsAddBtn.Image = global::PackageEditor.Properties.Resources._078;
resources.ApplyResources(this.fsAddBtn, "fsAddBtn");
this.fsAddBtn.Name = "fsAddBtn";
//
// fsAddEmptyDirBtn
//
this.fsAddEmptyDirBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.fsAddEmptyDirBtn.Image = global::PackageEditor.Properties.Resources._115;
resources.ApplyResources(this.fsAddEmptyDirBtn, "fsAddEmptyDirBtn");
this.fsAddEmptyDirBtn.Name = "fsAddEmptyDirBtn";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// fsRemoveBtn
//
this.fsRemoveBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.fsRemoveBtn.Image = global::PackageEditor.Properties.Resources._058;
resources.ApplyResources(this.fsRemoveBtn, "fsRemoveBtn");
this.fsRemoveBtn.Name = "fsRemoveBtn";
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// fsAddDirBtn
//
this.fsAddDirBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.fsAddDirBtn.Image = global::PackageEditor.Properties.Resources._019;
resources.ApplyResources(this.fsAddDirBtn, "fsAddDirBtn");
this.fsAddDirBtn.Name = "fsAddDirBtn";
//
// fsSaveFileAsBtn
//
this.fsSaveFileAsBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.fsSaveFileAsBtn, "fsSaveFileAsBtn");
this.fsSaveFileAsBtn.Name = "fsSaveFileAsBtn";
//
// tabRegistry
//
this.tabRegistry.AllowDrop = true;
this.tabRegistry.Controls.Add(this.panel8);
resources.ApplyResources(this.tabRegistry, "tabRegistry");
this.tabRegistry.Name = "tabRegistry";
this.tabRegistry.UseVisualStyleBackColor = true;
this.tabRegistry.DragDrop += new System.Windows.Forms.DragEventHandler(this.tabRegistry_DragDrop);
this.tabRegistry.DragEnter += new System.Windows.Forms.DragEventHandler(this.tabRegistry_DragEnter);
this.tabRegistry.DragOver += new System.Windows.Forms.DragEventHandler(this.tabRegistry_DragOver);
//
// panel8
//
this.panel8.BackColor = System.Drawing.Color.White;
this.panel8.Controls.Add(this.panel1);
this.panel8.Controls.Add(this.panel7);
resources.ApplyResources(this.panel8, "panel8");
this.panel8.Name = "panel8";
//
// panel1
//
this.panel1.Controls.Add(this.regSplitContainer);
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Name = "panel1";
//
// panel7
//
resources.ApplyResources(this.panel7, "panel7");
this.panel7.Controls.Add(this.regProgressBar);
this.panel7.Controls.Add(this.regToolStrip);
this.panel7.Name = "panel7";
//
// regProgressBar
//
resources.ApplyResources(this.regProgressBar, "regProgressBar");
this.regProgressBar.Name = "regProgressBar";
//
// regToolStrip
//
this.regToolStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.regToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.regRemoveBtn,
this.regEditBtn,
this.toolStripSeparator2,
this.regImportBtn,
this.regExportBtn});
resources.ApplyResources(this.regToolStrip, "regToolStrip");
this.regToolStrip.Name = "regToolStrip";
//
// regRemoveBtn
//
this.regRemoveBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.regRemoveBtn, "regRemoveBtn");
this.regRemoveBtn.Name = "regRemoveBtn";
//
// regEditBtn
//
this.regEditBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.regEditBtn, "regEditBtn");
this.regEditBtn.Name = "regEditBtn";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// regImportBtn
//
this.regImportBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.regImportBtn, "regImportBtn");
this.regImportBtn.Name = "regImportBtn";
this.regImportBtn.Click += new System.EventHandler(this.regImportBtn_Click);
//
// regExportBtn
//
this.regExportBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.regExportBtn, "regExportBtn");
this.regExportBtn.Name = "regExportBtn";
this.regExportBtn.Click += new System.EventHandler(this.regExportBtn_Click);
//
// tabAdvanced
//
this.tabAdvanced.BackColor = System.Drawing.Color.White;
this.tabAdvanced.Controls.Add(this.groupBox5);
this.tabAdvanced.Controls.Add(this.groupBox7);
this.tabAdvanced.Controls.Add(this.groupBox4);
resources.ApplyResources(this.tabAdvanced, "tabAdvanced");
this.tabAdvanced.Name = "tabAdvanced";
//
// groupBox5
//
this.groupBox5.Controls.Add(this.cbVolatileRegistry);
this.groupBox5.Controls.Add(this.propertyScmDirect);
this.groupBox5.Controls.Add(this.propertyDisplayLogo);
this.groupBox5.Controls.Add(this.cbDatFile);
this.groupBox5.Controls.Add(this.lnkAutoUpdate);
this.groupBox5.Controls.Add(this.label8);
this.groupBox5.Controls.Add(this.label7);
this.groupBox5.Controls.Add(this.lnkCustomEvents);
this.groupBox5.Controls.Add(this.propertyStopInheritance);
resources.ApplyResources(this.groupBox5, "groupBox5");
this.groupBox5.Name = "groupBox5";
this.groupBox5.TabStop = false;
//
// cbVolatileRegistry
//
resources.ApplyResources(this.cbVolatileRegistry, "cbVolatileRegistry");
this.cbVolatileRegistry.Name = "cbVolatileRegistry";
this.cbVolatileRegistry.UseVisualStyleBackColor = true;
this.cbVolatileRegistry.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// propertyScmDirect
//
resources.ApplyResources(this.propertyScmDirect, "propertyScmDirect");
this.propertyScmDirect.Name = "propertyScmDirect";
this.propertyScmDirect.UseVisualStyleBackColor = true;
this.propertyScmDirect.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// propertyDisplayLogo
//
resources.ApplyResources(this.propertyDisplayLogo, "propertyDisplayLogo");
this.propertyDisplayLogo.Name = "propertyDisplayLogo";
this.propertyDisplayLogo.UseVisualStyleBackColor = true;
this.propertyDisplayLogo.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// cbDatFile
//
resources.ApplyResources(this.cbDatFile, "cbDatFile");
this.cbDatFile.Name = "cbDatFile";
this.cbDatFile.UseVisualStyleBackColor = true;
this.cbDatFile.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// lnkAutoUpdate
//
resources.ApplyResources(this.lnkAutoUpdate, "lnkAutoUpdate");
this.lnkAutoUpdate.Cursor = System.Windows.Forms.Cursors.Hand;
this.lnkAutoUpdate.Name = "lnkAutoUpdate";
this.lnkAutoUpdate.TabStop = true;
this.lnkAutoUpdate.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkAutoUpdate_LinkClicked);
//
// label8
//
resources.ApplyResources(this.label8, "label8");
this.label8.Name = "label8";
//
// label7
//
resources.ApplyResources(this.label7, "label7");
this.label7.Name = "label7";
//
// lnkCustomEvents
//
resources.ApplyResources(this.lnkCustomEvents, "lnkCustomEvents");
this.lnkCustomEvents.Cursor = System.Windows.Forms.Cursors.Hand;
this.lnkCustomEvents.Name = "lnkCustomEvents";
this.lnkCustomEvents.TabStop = true;
this.lnkCustomEvents.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkCustomEvents_LinkClicked);
//
// propertyStopInheritance
//
resources.ApplyResources(this.propertyStopInheritance, "propertyStopInheritance");
this.propertyStopInheritance.Name = "propertyStopInheritance";
//
// groupBox7
//
this.groupBox7.Controls.Add(this.chkCleanDoneDialog);
this.groupBox7.Controls.Add(this.rdbCleanNone);
this.groupBox7.Controls.Add(this.chkCleanAsk);
this.groupBox7.Controls.Add(this.rdbCleanAll);
this.groupBox7.Controls.Add(this.rdbCleanRegOnly);
resources.ApplyResources(this.groupBox7, "groupBox7");
this.groupBox7.Name = "groupBox7";
this.groupBox7.TabStop = false;
//
// chkCleanDoneDialog
//
resources.ApplyResources(this.chkCleanDoneDialog, "chkCleanDoneDialog");
this.chkCleanDoneDialog.Name = "chkCleanDoneDialog";
this.chkCleanDoneDialog.UseVisualStyleBackColor = true;
this.chkCleanDoneDialog.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// rdbCleanNone
//
resources.ApplyResources(this.rdbCleanNone, "rdbCleanNone");
this.rdbCleanNone.Name = "rdbCleanNone";
this.rdbCleanNone.TabStop = true;
this.rdbCleanNone.UseVisualStyleBackColor = true;
this.rdbCleanNone.CheckedChanged += new System.EventHandler(this.rdb_CheckedChanged);
//
// chkCleanAsk
//
resources.ApplyResources(this.chkCleanAsk, "chkCleanAsk");
this.chkCleanAsk.Name = "chkCleanAsk";
this.chkCleanAsk.UseVisualStyleBackColor = true;
this.chkCleanAsk.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// rdbCleanAll
//
resources.ApplyResources(this.rdbCleanAll, "rdbCleanAll");
this.rdbCleanAll.Name = "rdbCleanAll";
this.rdbCleanAll.TabStop = true;
this.rdbCleanAll.UseVisualStyleBackColor = true;
this.rdbCleanAll.CheckedChanged += new System.EventHandler(this.rdb_CheckedChanged);
//
// rdbCleanRegOnly
//
resources.ApplyResources(this.rdbCleanRegOnly, "rdbCleanRegOnly");
this.rdbCleanRegOnly.Name = "rdbCleanRegOnly";
this.rdbCleanRegOnly.TabStop = true;
this.rdbCleanRegOnly.UseVisualStyleBackColor = true;
this.rdbCleanRegOnly.CheckedChanged += new System.EventHandler(this.rdb_CheckedChanged);
//
// groupBox4
//
this.groupBox4.Controls.Add(this.rdbIntegrateVirtual);
this.groupBox4.Controls.Add(this.rdbIntegrateStandard);
this.groupBox4.Controls.Add(this.rdbIntegrateNone);
resources.ApplyResources(this.groupBox4, "groupBox4");
this.groupBox4.Name = "groupBox4";
this.groupBox4.TabStop = false;
//
// rdbIntegrateVirtual
//
resources.ApplyResources(this.rdbIntegrateVirtual, "rdbIntegrateVirtual");
this.rdbIntegrateVirtual.Name = "rdbIntegrateVirtual";
this.rdbIntegrateVirtual.TabStop = true;
this.rdbIntegrateVirtual.UseVisualStyleBackColor = true;
this.rdbIntegrateVirtual.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// rdbIntegrateStandard
//
resources.ApplyResources(this.rdbIntegrateStandard, "rdbIntegrateStandard");
this.rdbIntegrateStandard.Name = "rdbIntegrateStandard";
this.rdbIntegrateStandard.TabStop = true;
this.rdbIntegrateStandard.UseVisualStyleBackColor = true;
this.rdbIntegrateStandard.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// rdbIntegrateNone
//
resources.ApplyResources(this.rdbIntegrateNone, "rdbIntegrateNone");
this.rdbIntegrateNone.Name = "rdbIntegrateNone";
this.rdbIntegrateNone.TabStop = true;
this.rdbIntegrateNone.UseVisualStyleBackColor = true;
this.rdbIntegrateNone.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// tabSecurity
//
this.tabSecurity.Controls.Add(this.panel10);
this.tabSecurity.Controls.Add(this.groupDataEncrypt);
this.tabSecurity.Controls.Add(this.groupUsageRights);
this.tabSecurity.Controls.Add(this.groupExpiration);
this.tabSecurity.Controls.Add(this.groupEditProtect);
resources.ApplyResources(this.tabSecurity, "tabSecurity");
this.tabSecurity.Name = "tabSecurity";
this.tabSecurity.UseVisualStyleBackColor = true;
//
// panel10
//
resources.ApplyResources(this.panel10, "panel10");
this.panel10.Name = "panel10";
//
// groupDataEncrypt
//
this.groupDataEncrypt.Controls.Add(this.panel16);
this.groupDataEncrypt.Controls.Add(this.propertyEncryptUserCreatedPassword);
this.groupDataEncrypt.Controls.Add(this.lnkEncryptionLearnMore);
this.groupDataEncrypt.Controls.Add(this.label12);
this.groupDataEncrypt.Controls.Add(this.tbEncryptionPwdConfirm);
this.groupDataEncrypt.Controls.Add(this.tbEncryptionPwd);
this.groupDataEncrypt.Controls.Add(this.lnkGenerateEncKey);
this.groupDataEncrypt.Controls.Add(this.tbEncryptionKey);
this.groupDataEncrypt.Controls.Add(this.propertyEncryptUsingPassword);
this.groupDataEncrypt.Controls.Add(this.propertyEncryptUsingKey);
this.groupDataEncrypt.Controls.Add(this.propertyEncryption);
resources.ApplyResources(this.groupDataEncrypt, "groupDataEncrypt");
this.groupDataEncrypt.Name = "groupDataEncrypt";
this.groupDataEncrypt.TabStop = false;
//
// panel16
//
this.panel16.Controls.Add(this.lnkExportPwdKey);
this.panel16.Controls.Add(this.lnkImportPwdKey);
resources.ApplyResources(this.panel16, "panel16");
this.panel16.Name = "panel16";
//
// lnkExportPwdKey
//
resources.ApplyResources(this.lnkExportPwdKey, "lnkExportPwdKey");
this.lnkExportPwdKey.Name = "lnkExportPwdKey";
this.lnkExportPwdKey.TabStop = true;
this.lnkExportPwdKey.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkExportPwdKey_LinkClicked);
//
// lnkImportPwdKey
//
resources.ApplyResources(this.lnkImportPwdKey, "lnkImportPwdKey");
this.lnkImportPwdKey.Name = "lnkImportPwdKey";
this.lnkImportPwdKey.TabStop = true;
this.lnkImportPwdKey.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkImportPwdKey_LinkClicked);
//
// propertyEncryptUserCreatedPassword
//
resources.ApplyResources(this.propertyEncryptUserCreatedPassword, "propertyEncryptUserCreatedPassword");
this.propertyEncryptUserCreatedPassword.Name = "propertyEncryptUserCreatedPassword";
this.propertyEncryptUserCreatedPassword.TabStop = true;
this.propertyEncryptUserCreatedPassword.UseVisualStyleBackColor = true;
//
// lnkEncryptionLearnMore
//
resources.ApplyResources(this.lnkEncryptionLearnMore, "lnkEncryptionLearnMore");
this.lnkEncryptionLearnMore.Name = "lnkEncryptionLearnMore";
this.lnkEncryptionLearnMore.TabStop = true;
this.lnkEncryptionLearnMore.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkEncryptionLearnMore_LinkClicked);
//
// label12
//
resources.ApplyResources(this.label12, "label12");
this.label12.Name = "label12";
//
// tbEncryptionPwdConfirm
//
resources.ApplyResources(this.tbEncryptionPwdConfirm, "tbEncryptionPwdConfirm");
this.tbEncryptionPwdConfirm.Name = "tbEncryptionPwdConfirm";
//
// tbEncryptionPwd
//
resources.ApplyResources(this.tbEncryptionPwd, "tbEncryptionPwd");
this.tbEncryptionPwd.Name = "tbEncryptionPwd";
this.tbEncryptionPwd.Enter += new System.EventHandler(this.tbEncryptionPwd_Enter);
//
// lnkGenerateEncKey
//
resources.ApplyResources(this.lnkGenerateEncKey, "lnkGenerateEncKey");
this.lnkGenerateEncKey.Name = "lnkGenerateEncKey";
this.lnkGenerateEncKey.TabStop = true;
this.lnkGenerateEncKey.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkGenerateEncKey_LinkClicked);
//
// tbEncryptionKey
//
resources.ApplyResources(this.tbEncryptionKey, "tbEncryptionKey");
this.tbEncryptionKey.Name = "tbEncryptionKey";
//
// propertyEncryptUsingPassword
//
resources.ApplyResources(this.propertyEncryptUsingPassword, "propertyEncryptUsingPassword");
this.propertyEncryptUsingPassword.Name = "propertyEncryptUsingPassword";
this.propertyEncryptUsingPassword.TabStop = true;
this.propertyEncryptUsingPassword.UseVisualStyleBackColor = true;
this.propertyEncryptUsingPassword.CheckedChanged += new System.EventHandler(this.propertyEncryption_CheckedChanged);
//
// propertyEncryptUsingKey
//
resources.ApplyResources(this.propertyEncryptUsingKey, "propertyEncryptUsingKey");
this.propertyEncryptUsingKey.Name = "propertyEncryptUsingKey";
this.propertyEncryptUsingKey.TabStop = true;
this.propertyEncryptUsingKey.UseVisualStyleBackColor = true;
this.propertyEncryptUsingKey.CheckedChanged += new System.EventHandler(this.propertyEncryption_CheckedChanged);
//
// propertyEncryption
//
resources.ApplyResources(this.propertyEncryption, "propertyEncryption");
this.propertyEncryption.Name = "propertyEncryption";
this.propertyEncryption.UseVisualStyleBackColor = true;
this.propertyEncryption.CheckedChanged += new System.EventHandler(this.propertyEncryption_CheckedChanged);
//
// groupUsageRights
//
this.groupUsageRights.Controls.Add(this.lnkActiveDirectory);
resources.ApplyResources(this.groupUsageRights, "groupUsageRights");
this.groupUsageRights.Name = "groupUsageRights";
this.groupUsageRights.TabStop = false;
//
// lnkActiveDirectory
//
resources.ApplyResources(this.lnkActiveDirectory, "lnkActiveDirectory");
this.lnkActiveDirectory.Name = "lnkActiveDirectory";
this.lnkActiveDirectory.TabStop = true;
this.lnkActiveDirectory.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkActiveDirectory_LinkClicked);
//
// groupExpiration
//
this.groupExpiration.Controls.Add(this.propertyExpirationDatePicker);
this.groupExpiration.Controls.Add(this.propertyExpiration);
this.groupExpiration.Controls.Add(this.propertyTtlDays);
this.groupExpiration.Controls.Add(this.propertyTtlResistRemove);
this.groupExpiration.Controls.Add(this.propertyTtlDaysValue);
resources.ApplyResources(this.groupExpiration, "groupExpiration");
this.groupExpiration.Name = "groupExpiration";
this.groupExpiration.TabStop = false;
//
// propertyExpirationDatePicker
//
resources.ApplyResources(this.propertyExpirationDatePicker, "propertyExpirationDatePicker");
this.propertyExpirationDatePicker.Name = "propertyExpirationDatePicker";
//
// propertyExpiration
//
resources.ApplyResources(this.propertyExpiration, "propertyExpiration");
this.propertyExpiration.Name = "propertyExpiration";
this.propertyExpiration.UseVisualStyleBackColor = true;
this.propertyExpiration.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// propertyTtlDays
//
resources.ApplyResources(this.propertyTtlDays, "propertyTtlDays");
this.propertyTtlDays.Name = "propertyTtlDays";
this.propertyTtlDays.UseVisualStyleBackColor = true;
this.propertyTtlDays.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// propertyTtlResistRemove
//
resources.ApplyResources(this.propertyTtlResistRemove, "propertyTtlResistRemove");
this.propertyTtlResistRemove.Name = "propertyTtlResistRemove";
this.propertyTtlResistRemove.UseVisualStyleBackColor = true;
this.propertyTtlResistRemove.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// propertyTtlDaysValue
//
resources.ApplyResources(this.propertyTtlDaysValue, "propertyTtlDaysValue");
this.propertyTtlDaysValue.Name = "propertyTtlDaysValue";
//
// groupEditProtect
//
this.groupEditProtect.Controls.Add(this.label6);
this.groupEditProtect.Controls.Add(this.tbPasswordConfirm);
this.groupEditProtect.Controls.Add(this.propertyProtPassword);
this.groupEditProtect.Controls.Add(this.propertyProt);
resources.ApplyResources(this.groupEditProtect, "groupEditProtect");
this.groupEditProtect.Name = "groupEditProtect";
this.groupEditProtect.TabStop = false;
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.Name = "label6";
//
// tbPasswordConfirm
//
resources.ApplyResources(this.tbPasswordConfirm, "tbPasswordConfirm");
this.tbPasswordConfirm.Name = "tbPasswordConfirm";
//
// propertyProtPassword
//
resources.ApplyResources(this.propertyProtPassword, "propertyProtPassword");
this.propertyProtPassword.Name = "propertyProtPassword";
this.propertyProtPassword.Enter += new System.EventHandler(this.propertyProtPassword_Enter);
//
// propertyProt
//
resources.ApplyResources(this.propertyProt, "propertyProt");
this.propertyProt.Name = "propertyProt";
this.propertyProt.UseVisualStyleBackColor = true;
this.propertyProt.CheckedChanged += new System.EventHandler(this.propertyProt_CheckedChanged);
//
// tabWelcome
//
this.tabWelcome.Controls.Add(this.panelWelcome);
resources.ApplyResources(this.tabWelcome, "tabWelcome");
this.tabWelcome.Name = "tabWelcome";
this.tabWelcome.UseVisualStyleBackColor = true;
//
// panelWelcome
//
resources.ApplyResources(this.panelWelcome, "panelWelcome");
this.panelWelcome.BackColor = System.Drawing.Color.White;
this.panelWelcome.Controls.Add(this.panel13);
this.panelWelcome.Name = "panelWelcome";
//
// panel13
//
resources.ApplyResources(this.panel13, "panel13");
this.panel13.BackColor = System.Drawing.Color.White;
this.panel13.Controls.Add(this.pictureBox2);
this.panel13.Controls.Add(this.listViewMRU);
this.panel13.Controls.Add(this.lnkPackageEdit);
this.panel13.Controls.Add(this.panel9);
this.panel13.Name = "panel13";
//
// pictureBox2
//
resources.ApplyResources(this.pictureBox2, "pictureBox2");
this.pictureBox2.Image = global::PackageEditor.Properties.Resources.logo_black;
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.TabStop = false;
//
// listViewMRU
//
this.listViewMRU.Activation = System.Windows.Forms.ItemActivation.OneClick;
resources.ApplyResources(this.listViewMRU, "listViewMRU");
this.listViewMRU.BackColor = System.Drawing.Color.White;
this.listViewMRU.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.listViewMRU.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnFileN});
this.listViewMRU.ForeColor = System.Drawing.Color.Blue;
this.listViewMRU.FullRowSelect = true;
this.listViewMRU.Groups.AddRange(new System.Windows.Forms.ListViewGroup[] {
((System.Windows.Forms.ListViewGroup)(resources.GetObject("listViewMRU.Groups"))),
((System.Windows.Forms.ListViewGroup)(resources.GetObject("listViewMRU.Groups1")))});
this.listViewMRU.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.listViewMRU.LargeImageList = this.imageListMRU;
this.listViewMRU.MultiSelect = false;
this.listViewMRU.Name = "listViewMRU";
this.listViewMRU.SmallImageList = this.imageListMRU;
this.listViewMRU.UseCompatibleStateImageBehavior = false;
this.listViewMRU.View = System.Windows.Forms.View.List;
this.listViewMRU.Click += new System.EventHandler(this.listViewMRU_Click);
//
// columnFileN
//
resources.ApplyResources(this.columnFileN, "columnFileN");
//
// imageListMRU
//
this.imageListMRU.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
resources.ApplyResources(this.imageListMRU, "imageListMRU");
this.imageListMRU.TransparentColor = System.Drawing.Color.Transparent;
//
// lnkPackageEdit
//
resources.ApplyResources(this.lnkPackageEdit, "lnkPackageEdit");
this.lnkPackageEdit.Name = "lnkPackageEdit";
this.lnkPackageEdit.TabStop = true;
this.lnkPackageEdit.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkPackageEdit_LinkClicked);
this.lnkPackageEdit.Click += new System.EventHandler(this.btnEditPackage_Click);
//
// panel9
//
resources.ApplyResources(this.panel9, "panel9");
this.panel9.Controls.Add(this.label11);
this.panel9.Controls.Add(this.line);
this.panel9.Name = "panel9";
//
// label11
//
resources.ApplyResources(this.label11, "label11");
this.label11.Name = "label11";
//
// line
//
resources.ApplyResources(this.line, "line");
this.line.Name = "line";
this.line.TabStop = false;
//
// bkPanel
//
resources.ApplyResources(this.bkPanel, "bkPanel");
this.bkPanel.Controls.Add(this.panelLicense);
this.bkPanel.Name = "bkPanel";
//
// panelLicense
//
resources.ApplyResources(this.panelLicense, "panelLicense");
this.panelLicense.BackColor = System.Drawing.SystemColors.Control;
this.panelLicense.Controls.Add(this.lnkUpgrade);
this.panelLicense.Controls.Add(this.lblNotCommercial);
this.panelLicense.Name = "panelLicense";
//
// lnkUpgrade
//
this.lnkUpgrade.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.lnkUpgrade, "lnkUpgrade");
this.lnkUpgrade.Name = "lnkUpgrade";
this.lnkUpgrade.TabStop = true;
this.lnkUpgrade.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkUpgrade_LinkClicked);
//
// lblNotCommercial
//
resources.ApplyResources(this.lblNotCommercial, "lblNotCommercial");
this.lblNotCommercial.Name = "lblNotCommercial";
//
// regFilesList
//
this.regFilesList.AllowColumnReorder = true;
this.regFilesList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader3,
this.columnHeader4,
this.columnHeader5});
resources.ApplyResources(this.regFilesList, "regFilesList");
this.regFilesList.DoubleClickActivation = false;
this.regFilesList.FullRowSelect = true;
this.regFilesList.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
((System.Windows.Forms.ListViewItem)(resources.GetObject("regFilesList.Items"))),
((System.Windows.Forms.ListViewItem)(resources.GetObject("regFilesList.Items1")))});
this.regFilesList.Name = "regFilesList";
this.regFilesList.UseCompatibleStateImageBehavior = false;
this.regFilesList.View = System.Windows.Forms.View.Details;
this.regFilesList.SubItemClicked += new PackageEditor.SubItemEventHandler(this.regFilesList_SubItemClicked);
this.regFilesList.SubItemEndEditing += new PackageEditor.SubItemEndEditingEventHandler(this.regFilesList_SubItemEndEditing);
this.regFilesList.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.regFilesList_ColumnClick);
//
// columnHeader3
//
resources.ApplyResources(this.columnHeader3, "columnHeader3");
//
// columnHeader4
//
resources.ApplyResources(this.columnHeader4, "columnHeader4");
//
// columnHeader5
//
resources.ApplyResources(this.columnHeader5, "columnHeader5");
//
// MainForm
//
this.AllowDrop = true;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tabControl);
this.Controls.Add(this.menuStrip1);
this.Controls.Add(this.bkPanel);
this.DoubleBuffered = true;
this.MainMenuStrip = this.menuStrip1;
this.Name = "MainForm";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainForm_FormClosed);
this.Load += new System.EventHandler(this.MainForm_Load);
this.Shown += new System.EventHandler(this.MainForm_Shown);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.MainForm_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.MainForm_DragEnter);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.fileContextMenu.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.panel3.ResumeLayout(false);
this.regSplitContainer.Panel1.ResumeLayout(false);
this.regSplitContainer.Panel2.ResumeLayout(false);
this.regSplitContainer.Panel2.PerformLayout();
this.regSplitContainer.ResumeLayout(false);
this.ContextMenuStripRegistryFolder.ResumeLayout(false);
this.panel4.ResumeLayout(false);
this.panel4.PerformLayout();
this.panel6.ResumeLayout(false);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.tabControl.ResumeLayout(false);
this.tabGeneral.ResumeLayout(false);
this.tabGeneral.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.propertyIcon)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox11.ResumeLayout(false);
this.groupBox11.PerformLayout();
this.groupBox9.ResumeLayout(false);
this.groupBox9.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.picRAM)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.picDisk)).EndInit();
this.groupBox10.ResumeLayout(false);
this.groupBox10.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.picFullAccess)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.picIsolatedMode)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.picDataMode)).EndInit();
this.tabFileSystem.ResumeLayout(false);
this.tabFileSystem.PerformLayout();
this.panel5.ResumeLayout(false);
this.fileToolStrip.ResumeLayout(false);
this.fileToolStrip.PerformLayout();
this.tabRegistry.ResumeLayout(false);
this.panel8.ResumeLayout(false);
this.panel8.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel7.ResumeLayout(false);
this.panel7.PerformLayout();
this.regToolStrip.ResumeLayout(false);
this.regToolStrip.PerformLayout();
this.tabAdvanced.ResumeLayout(false);
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
this.groupBox7.ResumeLayout(false);
this.groupBox7.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.tabSecurity.ResumeLayout(false);
this.groupDataEncrypt.ResumeLayout(false);
this.groupDataEncrypt.PerformLayout();
this.panel16.ResumeLayout(false);
this.panel16.PerformLayout();
this.groupUsageRights.ResumeLayout(false);
this.groupUsageRights.PerformLayout();
this.groupExpiration.ResumeLayout(false);
this.groupExpiration.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.propertyTtlDaysValue)).EndInit();
this.groupEditProtect.ResumeLayout(false);
this.groupEditProtect.PerformLayout();
this.tabWelcome.ResumeLayout(false);
this.panelWelcome.ResumeLayout(false);
this.panel13.ResumeLayout(false);
this.panel13.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.panel9.ResumeLayout(false);
this.panel9.PerformLayout();
this.bkPanel.ResumeLayout(false);
this.panelLicense.ResumeLayout(false);
this.panelLicense.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveasToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.Timer regProgressTimer;
private System.Windows.Forms.Timer itemHoverTimer;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.TabPage tabGeneral;
private System.Windows.Forms.Label dropboxLabel;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox propertyFriendlyName;
private System.Windows.Forms.TextBox propertyAppID;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.LinkLabel lnkAutoLaunch;
private System.Windows.Forms.Label propertyAutoLaunch;
private System.Windows.Forms.LinkLabel lnkChangeIcon;
private System.Windows.Forms.LinkLabel lnkChangeDataStorage;
private System.Windows.Forms.Label propertyDataStorage;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.RadioButton propertyIsolationDataMode;
private System.Windows.Forms.RadioButton propertyIsolationIsolated;
private System.Windows.Forms.RadioButton propertyIsolationMerge;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.PictureBox propertyIcon;
private System.Windows.Forms.Label lblAutoLaunch;
private System.Windows.Forms.Button dropboxButton;
private System.Windows.Forms.TabPage tabFileSystem;
private System.Windows.Forms.Panel panel5;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.TreeView fsFolderTree;
private System.Windows.Forms.ListView fsFilesList;
private System.Windows.Forms.ColumnHeader columnFileName;
private System.Windows.Forms.ColumnHeader columnFileSize;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.ComboBox fsFolderInfoIsolationCombo;
private System.Windows.Forms.Label fsFolderInfoIsolationLbl;
private System.Windows.Forms.Label fsFolderInfoFullName;
private System.Windows.Forms.ToolStrip fileToolStrip;
private System.Windows.Forms.ToolStripButton fsAddBtn;
private System.Windows.Forms.ToolStripButton fsAddDirBtn;
private System.Windows.Forms.ToolStripButton fsRemoveBtn;
private System.Windows.Forms.ToolStripButton fsAddEmptyDirBtn;
private System.Windows.Forms.ToolStripButton fsSaveFileAsBtn;
private System.Windows.Forms.TabPage tabRegistry;
private System.Windows.Forms.Panel panel8;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.SplitContainer regSplitContainer;
private System.Windows.Forms.TreeView regFolderTree;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Panel panel6;
private System.Windows.Forms.ComboBox regFolderInfoIsolationCombo;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label regFolderInfoFullName;
private System.Windows.Forms.Panel panel7;
private System.Windows.Forms.ProgressBar regProgressBar;
private System.Windows.Forms.ToolStrip regToolStrip;
private System.Windows.Forms.ToolStripButton regRemoveBtn;
private System.Windows.Forms.ToolStripButton regEditBtn;
private System.Windows.Forms.TabPage tabAdvanced;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.LinkLabel lnkCustomEvents;
private System.Windows.Forms.TextBox propertyStopInheritance;
private System.Windows.Forms.Panel bkPanel;
private ListViewEx regFilesList;
private System.Windows.Forms.TextBox tbValue;
private System.Windows.Forms.TextBox tbSize;
private System.Windows.Forms.TextBox tbFile;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.ColumnHeader columnHeader5;
private System.Windows.Forms.TextBox tbType;
private System.Windows.Forms.GroupBox groupBox7;
private System.Windows.Forms.CheckBox chkCleanAsk;
private System.Windows.Forms.RadioButton rdbCleanAll;
private System.Windows.Forms.RadioButton rdbCleanRegOnly;
private System.Windows.Forms.RadioButton rdbCleanNone;
private System.Windows.Forms.CheckBox chkCleanDoneDialog;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ContextMenuStrip ContextMenuStripRegistryFolder;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemExport;
private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exportXmlToolStripMenuItem;
private System.Windows.Forms.Panel panelWelcome;
private System.Windows.Forms.ImageList imageListMRU;
private System.Windows.Forms.TabPage tabWelcome;
private System.Windows.Forms.ToolStripButton regImportBtn;
private System.Windows.Forms.ToolStripButton regExportBtn;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ContextMenuStrip fileContextMenu;
private System.Windows.Forms.ToolStripMenuItem fileContextMenuDelete;
private System.Windows.Forms.ToolStripMenuItem fileContextMenuProperties;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TextBox propertyFileVersion;
private System.Windows.Forms.ColumnHeader columnFileType;
private System.Windows.Forms.LinkLabel lnkPackageEdit;
private System.Windows.Forms.Panel panel9;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.ListView listViewMRU;
private System.Windows.Forms.ColumnHeader columnFileN;
private System.Windows.Forms.Panel panel13;
private System.Windows.Forms.ToolStripMenuItem langToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem englishMenuItem;
private System.Windows.Forms.ToolStripMenuItem frenchMenuItem;
private System.Windows.Forms.ToolStripMenuItem spanishMenuItem;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.RadioButton rdbIntegrateVirtual;
private System.Windows.Forms.RadioButton rdbIntegrateStandard;
private System.Windows.Forms.RadioButton rdbIntegrateNone;
private System.Windows.Forms.ToolStripMenuItem chineseMenuItem;
private System.Windows.Forms.RadioButton propertyVirtModeDisk;
private System.Windows.Forms.RadioButton propertyVirtModeRam;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.LinkLabel lnkAutoUpdate;
private System.Windows.Forms.GroupBox groupBox9;
private System.Windows.Forms.PictureBox picDisk;
private System.Windows.Forms.PictureBox picRAM;
private System.Windows.Forms.Label helpVirtMode;
private System.Windows.Forms.GroupBox groupBox10;
private System.Windows.Forms.Label helpIsolationMode;
private System.Windows.Forms.PictureBox picDataMode;
private System.Windows.Forms.PictureBox picIsolatedMode;
private System.Windows.Forms.PictureBox picFullAccess;
private System.Windows.Forms.GroupBox groupBox11;
private System.Windows.Forms.CheckBox cbDatFile;
private System.Windows.Forms.GroupBox line;
private System.Windows.Forms.CheckBox propertyDisplayLogo;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.Panel panelLicense;
private System.Windows.Forms.Label lblNotCommercial;
private System.Windows.Forms.LinkLabel lnkUpgrade;
private System.Windows.Forms.CheckBox propertyScmDirect;
private System.Windows.Forms.CheckBox cbVolatileRegistry;
private System.Windows.Forms.TabPage tabSecurity;
private System.Windows.Forms.GroupBox groupUsageRights;
private System.Windows.Forms.LinkLabel lnkActiveDirectory;
private System.Windows.Forms.GroupBox groupExpiration;
private System.Windows.Forms.DateTimePicker propertyExpirationDatePicker;
private System.Windows.Forms.CheckBox propertyExpiration;
private System.Windows.Forms.CheckBox propertyTtlDays;
private System.Windows.Forms.CheckBox propertyTtlResistRemove;
private System.Windows.Forms.NumericUpDown propertyTtlDaysValue;
private System.Windows.Forms.GroupBox groupEditProtect;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox tbPasswordConfirm;
private System.Windows.Forms.TextBox propertyProtPassword;
private System.Windows.Forms.CheckBox propertyProt;
private System.Windows.Forms.GroupBox groupDataEncrypt;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.TextBox tbEncryptionPwdConfirm;
private System.Windows.Forms.TextBox tbEncryptionPwd;
private System.Windows.Forms.LinkLabel lnkGenerateEncKey;
private System.Windows.Forms.TextBox tbEncryptionKey;
private System.Windows.Forms.RadioButton propertyEncryptUsingPassword;
private System.Windows.Forms.RadioButton propertyEncryptUsingKey;
private System.Windows.Forms.CheckBox propertyEncryption;
private System.Windows.Forms.Panel panel10;
private System.Windows.Forms.LinkLabel lnkEncryptionLearnMore;
private System.Windows.Forms.RadioButton propertyEncryptUserCreatedPassword;
private System.Windows.Forms.LinkLabel lnkExportPwdKey;
private System.Windows.Forms.Panel panel16;
private System.Windows.Forms.LinkLabel lnkImportPwdKey;
private System.Windows.Forms.PictureBox pictureBox2;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Elf.WebApi.Areas.HelpPage.ModelDescriptions;
using Elf.WebApi.Areas.HelpPage.Models;
namespace Elf.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wintellect.PowerCollections;
internal class Events
{
private static readonly StringBuilder Output = new StringBuilder();
private static readonly EventHolder Event = new EventHolder();
public static void Main(string[] args)
{
while (true)
{
var isNextCommandExecutable = ExecuteNextCommand();
if (!isNextCommandExecutable)
{
break;
}
}
Console.WriteLine(Output);
}
private static bool ExecuteNextCommand()
{
string command = Console.ReadLine();
if (command[0] == 'A')
{
AddEvent(command);
return true;
}
if (command[0] == 'D')
{
DeleteEvents(command);
return true;
}
if (command[0] == 'L')
{
ListEvents(command);
return true;
}
if (command[0] == 'E')
{
return false;
}
return false;
}
private static void ListEvents(string command)
{
int pipeIndex = command.IndexOf('|');
DateTime date = GetDate(command, "ListEvents");
string countString = command.Substring(pipeIndex + 1);
int count = int.Parse(countString);
Event.ListEvents(
date,
count);
}
private static void DeleteEvents(string command)
{
string title = command.Substring("DeleteEvents".Length + 1);
Event.DeleteEvents(title);
}
private static void AddEvent(string command)
{
DateTime date;
string title;
string location;
GetParameters(
command,
"AddEvent",
out date,
out title,
out location);
Event.AddEvent(date, title, location);
}
private static void GetParameters(string commandForExecution, string commandType, out DateTime dateAndTime, out string eventTitle, out string eventLocation)
{
dateAndTime = GetDate(commandForExecution, commandType);
int firstPipeIndex = commandForExecution.IndexOf('|');
int lastPipeIndex = commandForExecution.LastIndexOf('|');
if (firstPipeIndex == lastPipeIndex)
{
eventTitle = commandForExecution.Substring(firstPipeIndex + 1).Trim();
eventLocation = string.Empty;
}
else
{
eventTitle = commandForExecution.Substring(
firstPipeIndex + 1,
lastPipeIndex - firstPipeIndex - 1)
.Trim();
eventLocation = commandForExecution.Substring(lastPipeIndex + 1).Trim();
}
}
private static DateTime GetDate(string command, string commandType)
{
DateTime date = DateTime.Parse(
command
.Substring(commandType.Length + 1, 20));
return date;
}
internal static class Messages
{
public static void EventAdded()
{
Output.Append("Event added\n");
}
public static void EventDeleted(int x)
{
if (x == 0)
{
NoEventsFound();
}
else
{
Output.AppendFormat("{0} events deleted\n", x);
}
}
public static void NoEventsFound()
{
Output.Append("No events found\n");
}
public static void PrintEvent(Event eventToPrint)
{
if (eventToPrint != null)
{
Output.Append(eventToPrint + "\n");
}
}
}
internal class EventHolder
{
private readonly MultiDictionary<string, Event> byTitle =
new MultiDictionary<string, Event>(true);
private readonly OrderedBag<Event> byDate = new OrderedBag<Event>();
public void AddEvent(
DateTime date,
string title,
string location)
{
Event newEvent = new Event(
date,
title,
location);
this.byTitle.Add(
title.ToLower(),
newEvent);
this.byDate.Add(newEvent);
Messages.EventAdded();
}
public void DeleteEvents(string titleToDelete)
{
string title = titleToDelete
.ToLower();
int removed = 0;
foreach (var eventToRemove in this.byTitle[title])
{
removed++;
this.byDate.Remove(eventToRemove);
}
this.byTitle.Remove(title);
Messages.EventDeleted(removed);
}
public void ListEvents(DateTime date, int count)
{
OrderedBag<Event>.View eventsToShow =
this.byDate.RangeFrom(new Event(date, string.Empty, string.Empty), true);
int showed = 0;
foreach (var eventToShow in eventsToShow)
{
if (showed == count)
{
break;
}
Messages.PrintEvent(eventToShow);
showed++;
}
if (showed == 0)
{
Messages.NoEventsFound();
}
}
}
}
| |
using System;
using System.Linq;
using UnityEngine;
using UnityEngine.Tilemaps;
using Object = UnityEngine.Object;
namespace UnityEditor
{
[CustomGridBrush(true, false, false, "GameObject Brush")]
public class GameObjectBrush : GridBrushBase
{
[SerializeField]
[HideInInspector]
private BrushCell[] m_Cells;
[SerializeField]
[HideInInspector]
private Vector3Int m_Size;
[SerializeField]
[HideInInspector]
private Vector3Int m_Pivot;
public Vector3Int size { get { return m_Size; } set { m_Size = value; SizeUpdated(); } }
public Vector3Int pivot { get { return m_Pivot; } set { m_Pivot = value; } }
public BrushCell[] cells { get { return m_Cells; } }
public int cellCount { get { return m_Cells != null ? m_Cells.Length : 0; } }
public GameObjectBrush()
{
Init(Vector3Int.one, Vector3Int.zero);
SizeUpdated();
}
public void Init(Vector3Int size)
{
Init(size, Vector3Int.zero);
SizeUpdated();
}
public void Init(Vector3Int size, Vector3Int pivot)
{
m_Size = size;
m_Pivot = pivot;
SizeUpdated();
}
public override void Paint(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
{
// Do not allow editing palettes
if (brushTarget.layer == 31)
return;
Vector3Int min = position - pivot;
BoundsInt bounds = new BoundsInt(min, m_Size);
BoxFill(gridLayout, brushTarget, bounds);
}
private void PaintCell(GridLayout grid, Vector3Int position, Transform parent, BrushCell cell)
{
if (cell.gameObject != null)
{
SetSceneCell(grid, parent, position, cell.gameObject, cell.offset, cell.scale, cell.orientation);
}
}
public override void Erase(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
{
// Do not allow editing palettes
if (brushTarget.layer == 31)
return;
Vector3Int min = position - pivot;
BoundsInt bounds = new BoundsInt(min, m_Size);
BoxErase(gridLayout, brushTarget, bounds);
}
private void EraseCell(GridLayout grid, Vector3Int position, Transform parent)
{
ClearSceneCell(grid, parent, position);
}
public override void BoxFill(GridLayout gridLayout, GameObject brushTarget, BoundsInt position)
{
// Do not allow editing palettes
if (brushTarget.layer == 31)
return;
if (brushTarget == null)
return;
foreach (Vector3Int location in position.allPositionsWithin)
{
Vector3Int local = location - position.min;
BrushCell cell = m_Cells[GetCellIndexWrapAround(local.x, local.y, local.z)];
PaintCell(gridLayout, location, brushTarget.transform, cell);
}
}
public override void BoxErase(GridLayout gridLayout, GameObject brushTarget, BoundsInt position)
{
// Do not allow editing palettes
if (brushTarget.layer == 31)
return;
if (brushTarget == null)
return;
foreach (Vector3Int location in position.allPositionsWithin)
{
EraseCell(gridLayout, location, brushTarget.transform);
}
}
public override void FloodFill(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
{
Debug.LogWarning("FloodFill not supported");
}
public override void Rotate(RotationDirection direction, Grid.CellLayout layout)
{
Vector3Int oldSize = m_Size;
BrushCell[] oldCells = m_Cells.Clone() as BrushCell[];
size = new Vector3Int(oldSize.y, oldSize.x, oldSize.z);
BoundsInt oldBounds = new BoundsInt(Vector3Int.zero, oldSize);
foreach (Vector3Int oldPos in oldBounds.allPositionsWithin)
{
int newX = direction == RotationDirection.Clockwise ? oldSize.y - oldPos.y - 1 : oldPos.y;
int newY = direction == RotationDirection.Clockwise ? oldPos.x : oldSize.x - oldPos.x - 1;
int toIndex = GetCellIndex(newX, newY, oldPos.z);
int fromIndex = GetCellIndex(oldPos.x, oldPos.y, oldPos.z, oldSize.x, oldSize.y, oldSize.z);
m_Cells[toIndex] = oldCells[fromIndex];
}
int newPivotX = direction == RotationDirection.Clockwise ? oldSize.y - pivot.y - 1 : pivot.y;
int newPivotY = direction == RotationDirection.Clockwise ? pivot.x : oldSize.x - pivot.x - 1;
pivot = new Vector3Int(newPivotX, newPivotY, pivot.z);
Matrix4x4 rotation = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0f, 0f, direction == RotationDirection.Clockwise ? 90f : -90f), Vector3.one);
Quaternion orientation = Quaternion.Euler(0f, 0f, direction == RotationDirection.Clockwise ? 90f : -90f);
foreach (BrushCell cell in m_Cells)
{
cell.offset = rotation * cell.offset;
cell.orientation = cell.orientation * orientation;
}
}
public override void Flip(FlipAxis flip, Grid.CellLayout layout)
{
if (flip == FlipAxis.X)
FlipX();
else
FlipY();
}
public override void Pick(GridLayout gridLayout, GameObject brushTarget, BoundsInt position, Vector3Int pickStart)
{
// Do not allow editing palettes
if (brushTarget.layer == 31)
return;
Reset();
UpdateSizeAndPivot(new Vector3Int(position.size.x, position.size.y, 1), new Vector3Int(pickStart.x, pickStart.y, 0));
foreach (Vector3Int pos in position.allPositionsWithin)
{
Vector3Int brushPosition = new Vector3Int(pos.x - position.x, pos.y - position.y, 0);
PickCell(pos, brushPosition, gridLayout, brushTarget.transform);
}
}
private void PickCell(Vector3Int position, Vector3Int brushPosition, GridLayout grid, Transform parent)
{
if (parent != null)
{
Vector3 cellCenter = grid.LocalToWorld(grid.CellToLocalInterpolated(position + new Vector3(.5f, .5f, .5f)));
GameObject go = GetObjectInCell(grid, parent, position);
if (go != null)
{
Object prefab = PrefabUtility.GetPrefabParent(go);
if (prefab)
{
SetGameObject(brushPosition, (GameObject) prefab);
}
else
{
GameObject newInstance = Instantiate(go);
newInstance.hideFlags = HideFlags.HideAndDontSave;
SetGameObject(brushPosition, newInstance);
}
SetOffset(brushPosition, go.transform.position - cellCenter);
SetScale(brushPosition, go.transform.localScale);
SetOrientation(brushPosition, go.transform.localRotation);
}
}
}
public override void MoveStart(GridLayout gridLayout, GameObject brushTarget, BoundsInt position)
{
// Do not allow editing palettes
if (brushTarget.layer == 31)
return;
Reset();
UpdateSizeAndPivot(new Vector3Int(position.size.x, position.size.y, 1), Vector3Int.zero);
if (brushTarget != null)
{
foreach (Vector3Int pos in position.allPositionsWithin)
{
Vector3Int brushPosition = new Vector3Int(pos.x - position.x, pos.y - position.y, 0);
PickCell(pos, brushPosition, gridLayout, brushTarget.transform);
ClearSceneCell(gridLayout, brushTarget.transform, brushPosition);
}
}
}
public override void MoveEnd(GridLayout gridLayout, GameObject brushTarget, BoundsInt position)
{
// Do not allow editing palettes
if (brushTarget.layer == 31)
return;
Paint(gridLayout, brushTarget, position.min);
Reset();
}
public void Reset()
{
foreach (var cell in m_Cells)
{
if (cell.gameObject != null && !EditorUtility.IsPersistent(cell.gameObject))
{
DestroyImmediate(cell.gameObject);
}
}
UpdateSizeAndPivot(Vector3Int.one, Vector3Int.zero);
}
private void FlipX()
{
BrushCell[] oldCells = m_Cells.Clone() as BrushCell[];
BoundsInt oldBounds = new BoundsInt(Vector3Int.zero, m_Size);
foreach (Vector3Int oldPos in oldBounds.allPositionsWithin)
{
int newX = m_Size.x - oldPos.x - 1;
int toIndex = GetCellIndex(newX, oldPos.y, oldPos.z);
int fromIndex = GetCellIndex(oldPos);
m_Cells[toIndex] = oldCells[fromIndex];
}
int newPivotX = m_Size.x - pivot.x - 1;
pivot = new Vector3Int(newPivotX, pivot.y, pivot.z);
Matrix4x4 flip = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(-1f, 1f, 1f));
Quaternion orientation = Quaternion.Euler(0f, 0f, -180f);
foreach (BrushCell cell in m_Cells)
{
Vector3 oldOffset = cell.offset;
cell.offset = flip * oldOffset;
cell.orientation = cell.orientation*orientation;
}
}
private void FlipY()
{
BrushCell[] oldCells = m_Cells.Clone() as BrushCell[];
BoundsInt oldBounds = new BoundsInt(Vector3Int.zero, m_Size);
foreach (Vector3Int oldPos in oldBounds.allPositionsWithin)
{
int newY = m_Size.y - oldPos.y - 1;
int toIndex = GetCellIndex(oldPos.x, newY, oldPos.z);
int fromIndex = GetCellIndex(oldPos);
m_Cells[toIndex] = oldCells[fromIndex];
}
int newPivotY = m_Size.y - pivot.y - 1;
pivot = new Vector3Int(pivot.x, newPivotY, pivot.z);
Matrix4x4 flip = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1f, -1f, 1f));
Quaternion orientation = Quaternion.Euler(0f, 0f, -180f);
foreach (BrushCell cell in m_Cells)
{
Vector3 oldOffset = cell.offset;
cell.offset = flip * oldOffset;
cell.orientation = cell.orientation * orientation;
}
}
public void UpdateSizeAndPivot(Vector3Int size, Vector3Int pivot)
{
m_Size = size;
m_Pivot = pivot;
SizeUpdated();
}
public void SetGameObject(Vector3Int position, GameObject go)
{
if (ValidateCellPosition(position))
m_Cells[GetCellIndex(position)].gameObject = go;
}
public void SetOffset(Vector3Int position, Vector3 offset)
{
if (ValidateCellPosition(position))
m_Cells[GetCellIndex(position)].offset = offset;
}
public void SetOrientation(Vector3Int position, Quaternion orientation)
{
if (ValidateCellPosition(position))
m_Cells[GetCellIndex(position)].orientation = orientation;
}
public void SetScale(Vector3Int position, Vector3 scale)
{
if (ValidateCellPosition(position))
m_Cells[GetCellIndex(position)].scale = scale;
}
public int GetCellIndex(Vector3Int brushPosition)
{
return GetCellIndex(brushPosition.x, brushPosition.y, brushPosition.z);
}
public int GetCellIndex(int x, int y, int z)
{
return x + m_Size.x * y + m_Size.x * m_Size.y * z;
}
public int GetCellIndex(int x, int y, int z, int sizex, int sizey, int sizez)
{
return x + sizex * y + sizex * sizey * z;
}
public int GetCellIndexWrapAround(int x, int y, int z)
{
return (x % m_Size.x) + m_Size.x * (y % m_Size.y) + m_Size.x * m_Size.y * (z % m_Size.z);
}
private static GameObject GetObjectInCell(GridLayout grid, Transform parent, Vector3Int position)
{
int childCount = parent.childCount;
Vector3 min = grid.LocalToWorld(grid.CellToLocalInterpolated(position));
Vector3 max = grid.LocalToWorld(grid.CellToLocalInterpolated(position + Vector3Int.one));
// Infinite bounds on Z for 2D convenience
min = new Vector3(min.x, min.y, float.MinValue);
max = new Vector3(max.x, max.y, float.MaxValue);
Bounds bounds = new Bounds((max + min) * .5f, max - min);
for (int i = 0; i < childCount; i++)
{
Transform child = parent.GetChild(i);
if (bounds.Contains(child.position))
return child.gameObject;
}
return null;
}
private bool ValidateCellPosition(Vector3Int position)
{
var valid =
position.x >= 0 && position.x < size.x &&
position.y >= 0 && position.y < size.y &&
position.z >= 0 && position.z < size.z;
if (!valid)
throw new ArgumentException(string.Format("Position {0} is an invalid cell position. Valid range is between [{1}, {2}).", position, Vector3Int.zero, size));
return valid;
}
private void SizeUpdated()
{
m_Cells = new BrushCell[m_Size.x * m_Size.y * m_Size.z];
BoundsInt bounds = new BoundsInt(Vector3Int.zero, m_Size);
foreach (Vector3Int pos in bounds.allPositionsWithin)
{
m_Cells[GetCellIndex(pos)] = new BrushCell();
}
}
private static void SetSceneCell(GridLayout grid, Transform parent, Vector3Int position, GameObject go, Vector3 offset, Vector3 scale, Quaternion orientation)
{
if (parent == null || go == null)
return;
GameObject instance = null;
if (PrefabUtility.GetPrefabType(go) == PrefabType.Prefab)
{
instance = (GameObject) PrefabUtility.InstantiatePrefab(go);
}
else
{
instance = Instantiate(go);
instance.hideFlags = HideFlags.None;
instance.name = go.name;
}
Undo.RegisterCreatedObjectUndo(instance, "Paint GameObject");
instance.transform.SetParent(parent);
instance.transform.position = grid.LocalToWorld(grid.CellToLocalInterpolated(new Vector3Int(position.x, position.y, position.z) + new Vector3(.5f, .5f, .5f)));
instance.transform.localRotation = orientation;
instance.transform.localScale = scale;
instance.transform.Translate(offset);
}
private static void ClearSceneCell(GridLayout grid, Transform parent, Vector3Int position)
{
if (parent == null)
return;
GameObject erased = GetObjectInCell(grid, parent, new Vector3Int(position.x, position.y, position.z));
if (erased != null)
Undo.DestroyObjectImmediate(erased);
}
public override int GetHashCode()
{
int hash = 0;
unchecked
{
foreach (var cell in cells)
{
hash = hash * 33 + cell.GetHashCode();
}
}
return hash;
}
[Serializable]
public class BrushCell
{
public GameObject gameObject { get { return m_GameObject; } set { m_GameObject = value; } }
public Vector3 offset { get { return m_Offset; } set { m_Offset = value; } }
public Vector3 scale { get { return m_Scale; } set { m_Scale = value; } }
public Quaternion orientation { get { return m_Orientation; } set { m_Orientation = value; } }
[SerializeField]
private GameObject m_GameObject;
[SerializeField]
Vector3 m_Offset = Vector3.zero;
[SerializeField]
Vector3 m_Scale = Vector3.one;
[SerializeField]
Quaternion m_Orientation = Quaternion.identity;
public override int GetHashCode()
{
int hash = 0;
unchecked
{
hash = gameObject != null ? gameObject.GetInstanceID() : 0;
hash = hash * 33 + m_Offset.GetHashCode();
hash = hash * 33 + m_Scale.GetHashCode();
hash = hash * 33 + m_Orientation.GetHashCode();
}
return hash;
}
}
}
[CustomEditor(typeof(GameObjectBrush))]
public class GameObjectBrushEditor : GridBrushEditorBase
{
public GameObjectBrush brush { get { return target as GameObjectBrush; } }
public override void OnPaintSceneGUI(GridLayout gridLayout, GameObject brushTarget, BoundsInt position, GridBrushBase.Tool tool, bool executing)
{
BoundsInt gizmoRect = position;
if (tool == GridBrushBase.Tool.Paint || tool == GridBrushBase.Tool.Erase)
gizmoRect = new BoundsInt(position.min - brush.pivot, brush.size);
base.OnPaintSceneGUI(gridLayout, brushTarget, gizmoRect, tool, executing);
}
public override void OnPaintInspectorGUI()
{
GUILayout.Label("Pick, paint and erase GameObject(s) in the scene.");
GUILayout.Label("Limited to children of the currently selected GameObject.");
}
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="PhotonPlayer.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
// <summary>
// Represents a player, identified by actorID (a.k.a. ActorNumber).
// Caches properties of a player.
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
using System.Collections.Generic;
using ExitGames.Client.Photon;
using UnityEngine;
using Hashtable = ExitGames.Client.Photon.Hashtable;
/// <summary>
/// Summarizes a "player" within a room, identified (in that room) by actorID.
/// </summary>
/// <remarks>
/// Each player has an actorId (or ID), valid for that room. It's -1 until it's assigned by server.
/// Each client can set it's player's custom properties with SetCustomProperties, even before being in a room.
/// They are synced when joining a room.
/// </remarks>
/// \ingroup publicApi
public class PhotonPlayer
{
/// <summary>This player's actorID</summary>
public int ID
{
get { return this.actorID; }
}
/// <summary>Identifier of this player in current room.</summary>
private int actorID = -1;
private string nameField = "";
/// <summary>Nickname of this player.</summary>
/// <remarks>Set the PhotonNetwork.playerName to make the name synchronized in a room.</remarks>
public string name {
get
{
return this.nameField;
}
set
{
if (!isLocal)
{
Debug.LogError("Error: Cannot change the name of a remote player!");
return;
}
if (string.IsNullOrEmpty(value) || value.Equals(this.nameField))
{
return;
}
this.nameField = value;
PhotonNetwork.playerName = value; // this will sync the local player's name in a room
}
}
///// <summary>UserId of the player. Sent when room gets created with RoomOptions.publishUserId = true. Useful for FindFriends and blocking slots in a room for expected players.</summary>
//public string userId { get; internal set; }
/// <summary>Only one player is controlled by each client. Others are not local.</summary>
public readonly bool isLocal = false;
/// <summary>
/// True if this player is the Master Client of the current room.
/// </summary>
/// <remarks>
/// See also: PhotonNetwork.masterClient.
/// </remarks>
public bool isMasterClient
{
get { return (PhotonNetwork.networkingPeer.mMasterClientId == this.ID); }
}
/// <summary>Read-only cache for custom properties of player. Set via PhotonPlayer.SetCustomProperties.</summary>
/// <remarks>
/// Don't modify the content of this Hashtable. Use SetCustomProperties and the
/// properties of this class to modify values. When you use those, the client will
/// sync values with the server.
/// </remarks>
/// <see cref="SetCustomProperties"/>
public Hashtable customProperties { get; internal set; }
/// <summary>Creates a Hashtable with all properties (custom and "well known" ones).</summary>
/// <remarks>If used more often, this should be cached.</remarks>
public Hashtable allProperties
{
get
{
Hashtable allProps = new Hashtable();
allProps.Merge(this.customProperties);
allProps[ActorProperties.PlayerName] = this.name;
return allProps;
}
}
/// <summary>Can be used to store a reference that's useful to know "by player".</summary>
/// <remarks>Example: Set a player's character as Tag by assigning the GameObject on Instantiate.</remarks>
public object TagObject;
/// <summary>
/// Creates a PhotonPlayer instance.
/// </summary>
/// <param name="isLocal">If this is the local peer's player (or a remote one).</param>
/// <param name="actorID">ID or ActorNumber of this player in the current room (a shortcut to identify each player in room)</param>
/// <param name="name">Name of the player (a "well known property").</param>
public PhotonPlayer(bool isLocal, int actorID, string name)
{
this.customProperties = new Hashtable();
this.isLocal = isLocal;
this.actorID = actorID;
this.nameField = name;
}
/// <summary>
/// Internally used to create players from event Join
/// </summary>
internal protected PhotonPlayer(bool isLocal, int actorID, Hashtable properties)
{
this.customProperties = new Hashtable();
this.isLocal = isLocal;
this.actorID = actorID;
this.InternalCacheProperties(properties);
}
/// <summary>
/// Makes PhotonPlayer comparable
/// </summary>
public override bool Equals(object p)
{
PhotonPlayer pp = p as PhotonPlayer;
return (pp != null && this.GetHashCode() == pp.GetHashCode());
}
public override int GetHashCode()
{
return this.ID;
}
/// <summary>
/// Used internally, to update this client's playerID when assigned.
/// </summary>
internal void InternalChangeLocalID(int newID)
{
if (!this.isLocal)
{
Debug.LogError("ERROR You should never change PhotonPlayer IDs!");
return;
}
this.actorID = newID;
}
/// <summary>
/// Caches custom properties for this player.
/// </summary>
internal void InternalCacheProperties(Hashtable properties)
{
if (properties == null || properties.Count == 0 || this.customProperties.Equals(properties))
{
return;
}
if (properties.ContainsKey(ActorProperties.PlayerName))
{
this.nameField = (string)properties[ActorProperties.PlayerName];
}
//if (properties.ContainsKey(ActorProperties.UserId))
//{
// this.userId = (string)properties[ActorProperties.UserId];
//}
if (properties.ContainsKey(ActorProperties.IsInactive))
{
// TODO: implement isinactive
}
this.customProperties.MergeStringKeys(properties);
this.customProperties.StripKeysWithNullValues();
}
/// <summary>
/// Updates the this player's Custom Properties with new/updated key-values.
/// </summary>
/// <remarks>
/// Custom Properties are a key-value set (Hashtable) which is available to all players in a room.
/// They can relate to the room or individual players and are useful when only the current value
/// of something is of interest. For example: The map of a room.
/// All keys must be strings.
///
/// The Room and the PhotonPlayer class both have SetCustomProperties methods.
/// Also, both classes offer access to current key-values by: customProperties.
///
/// Always use SetCustomProperties to change values.
/// To reduce network traffic, set only values that actually changed.
/// New properties are added, existing values are updated.
/// Other values will not be changed, so only provide values that changed or are new.
///
/// To delete a named (custom) property of this room, use null as value.
///
/// Locally, SetCustomProperties will update it's cache without delay.
/// Other clients are updated through Photon (the server) with a fitting operation.
///
/// <b>Check and Swap</b>
///
/// SetCustomProperties have the option to do a server-side Check-And-Swap (CAS):
/// Values only get updated if the expected values are correct.
/// The expectedValues can be different key/values than the propertiesToSet. So you can
/// check some key and set another key's value (if the check succeeds).
///
/// If the client's knowledge of properties is wrong or outdated, it can't set values with CAS.
/// This can be useful to keep players from concurrently setting values. For example: If all players
/// try to pickup some card or item, only one should get it. With CAS, only the first SetProperties
/// gets executed server-side and any other (sent at the same time) fails.
///
/// The server will broadcast successfully changed values and the local "cache" of customProperties
/// only gets updated after a roundtrip (if anything changed).
///
/// You can do a "webForward": Photon will send the changed properties to a WebHook defined
/// for your application.
///
/// <b>OfflineMode</b>
///
/// While PhotonNetwork.offlineMode is true, the expectedValues and webForward parameters are ignored.
/// In OfflineMode, the local customProperties values are immediately updated (without the roundtrip).
/// </remarks>
/// <param name="propertiesToSet">The new properties to be set. </param>
/// <param name="expectedValues">At least one property key/value set to check server-side. Key and value must be correct. Ignored in OfflineMode.</param>
/// <param name="webForward">Set to true, to forward the set properties to a WebHook, defined for this app (in Dashboard). Ignored in OfflineMode.</param>
public void SetCustomProperties(Hashtable propertiesToSet, Hashtable expectedValues = null, bool webForward = false)
{
if (propertiesToSet == null)
{
return;
}
if (this.actorID > 0 && !PhotonNetwork.offlineMode)
{
Hashtable customProps = propertiesToSet.StripToStringKeys() as Hashtable;
Hashtable customPropsToCheck = expectedValues.StripToStringKeys() as Hashtable;
PhotonNetwork.networkingPeer.OpSetPropertiesOfActor(this.actorID, customProps, customPropsToCheck, webForward);
}
else
{
Hashtable customProps = propertiesToSet.StripToStringKeys() as Hashtable;
this.InternalCacheProperties(customProps);
NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerPropertiesChanged, customProps);
}
}
/// <summary>
/// Try to get a specific player by id.
/// </summary>
/// <param name="ID">ActorID</param>
/// <returns>The player with matching actorID or null, if the actorID is not in use.</returns>
public static PhotonPlayer Find(int ID)
{
if (PhotonNetwork.networkingPeer != null)
{
return PhotonNetwork.networkingPeer.GetPlayerWithId(ID);
}
return null;
}
public PhotonPlayer Get(int id)
{
return PhotonPlayer.Find(id);
}
public PhotonPlayer GetNext()
{
return GetNextFor(this.ID);
}
public PhotonPlayer GetNextFor(PhotonPlayer currentPlayer)
{
if (currentPlayer == null)
{
return null;
}
return GetNextFor(currentPlayer.ID);
}
public PhotonPlayer GetNextFor(int currentPlayerId)
{
if (PhotonNetwork.networkingPeer == null || PhotonNetwork.networkingPeer.mActors == null || PhotonNetwork.networkingPeer.mActors.Count < 2)
{
return null;
}
Dictionary<int, PhotonPlayer> players = PhotonNetwork.networkingPeer.mActors;
int nextHigherId = int.MaxValue; // we look for the next higher ID
int lowestId = currentPlayerId; // if we are the player with the highest ID, there is no higher and we return to the lowest player's id
foreach (int playerid in players.Keys)
{
if (playerid < lowestId)
{
lowestId = playerid; // less than any other ID (which must be at least less than this player's id).
}
else if (playerid > currentPlayerId && playerid < nextHigherId)
{
nextHigherId = playerid; // more than our ID and less than those found so far.
}
}
//UnityEngine.Debug.LogWarning("Debug. " + currentPlayerId + " lower: " + lowestId + " higher: " + nextHigherId + " ");
//UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(currentPlayerId));
//UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(lowestId));
//if (nextHigherId != int.MaxValue) UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(nextHigherId));
return (nextHigherId != int.MaxValue) ? players[nextHigherId] : players[lowestId];
}
/// <summary>
/// Brief summary string of the PhotonPlayer. Includes name or player.ID and if it's the Master Client.
/// </summary>
public override string ToString()
{
if (string.IsNullOrEmpty(this.name))
{
return string.Format("#{0:00}{1}", this.ID, this.isMasterClient ? "(master)":"");
}
return string.Format("'{0}'{1}", this.name, this.isMasterClient ? "(master)" : "");
}
/// <summary>
/// String summary of the PhotonPlayer: player.ID, name and all custom properties of this user.
/// </summary>
/// <remarks>
/// Use with care and not every frame!
/// Converts the customProperties to a String on every single call.
/// </remarks>
public string ToStringFull()
{
return string.Format("#{0:00} '{1}' {2}", this.ID, this.name, this.customProperties.ToStringFull());
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using Saltarelle.Compiler.JSModel.Expressions;
namespace Saltarelle.Compiler.Tests {
public class MockRuntimeLibrary : IRuntimeLibrary {
private enum TypeContext {
GenericArgument,
TypeOf,
CastTarget,
GetDefaultValue,
UseStaticMember,
BindBaseCall,
}
private string GetTypeContextShortName(TypeContext c) {
switch (c) {
case TypeContext.GenericArgument: return "ga";
case TypeContext.TypeOf: return "to";
case TypeContext.UseStaticMember: return "sm";
case TypeContext.CastTarget: return "ct";
case TypeContext.GetDefaultValue: return "def";
case TypeContext.BindBaseCall: return "bind";
default: throw new ArgumentException("c");
}
}
public MockRuntimeLibrary() {
GetTypeOf = (t, c) => GetScriptType(t, TypeContext.TypeOf, c.ResolveTypeParameter);
InstantiateType = (t, c) => GetScriptType(t, TypeContext.UseStaticMember, c.ResolveTypeParameter);
InstantiateTypeForUseAsTypeArgumentInInlineCode = (t, c) => GetScriptType(t, TypeContext.GenericArgument, c.ResolveTypeParameter);
TypeIs = (e, s, t, c) => JsExpression.Invocation(JsExpression.Identifier("$TypeIs"), e, GetScriptType(t, TypeContext.CastTarget, c.ResolveTypeParameter));
TryDowncast = (e, s, d, c) => JsExpression.Invocation(JsExpression.Identifier("$TryCast"), e, GetScriptType(d, TypeContext.CastTarget, c.ResolveTypeParameter));
Downcast = (e, s, d, c) => JsExpression.Invocation(JsExpression.Identifier("$Cast"), e, GetScriptType(d, TypeContext.CastTarget, c.ResolveTypeParameter));
Upcast = (e, s, d, c) => JsExpression.Invocation(JsExpression.Identifier("$Upcast"), e, GetScriptType(d, TypeContext.CastTarget, c.ResolveTypeParameter));
ReferenceEquals = (a, b, c) => JsExpression.Invocation(JsExpression.Identifier("$ReferenceEquals"), a, b);
ReferenceNotEquals = (a, b, c) => JsExpression.Invocation(JsExpression.Identifier("$ReferenceNotEquals"), a, b);
InstantiateGenericMethod = (m, a, c) => JsExpression.Invocation(JsExpression.Identifier("$InstantiateGenericMethod"), new[] { m }.Concat(a.Select(x => GetScriptType(x, TypeContext.GenericArgument, c.ResolveTypeParameter))));
MakeException = (e, c) => JsExpression.Invocation(JsExpression.Identifier("$MakeException"), e);
IntegerDivision = (n, d, c) => JsExpression.Invocation(JsExpression.Identifier("$IntDiv"), n, d);
FloatToInt = (e, c) => JsExpression.Invocation(JsExpression.Identifier("$Truncate"), e);
Coalesce = (a, b, c) => JsExpression.Invocation(JsExpression.Identifier("$Coalesce"), a, b);
Lift = (e, c) => JsExpression.Invocation(JsExpression.Identifier("$Lift"), e);
FromNullable = (e, c) => JsExpression.Invocation(JsExpression.Identifier("$FromNullable"), e);
LiftedBooleanAnd = (a, b, c) => JsExpression.Invocation(JsExpression.Identifier("$LiftedBooleanAnd"), a, b);
LiftedBooleanOr = (a, b, c) => JsExpression.Invocation(JsExpression.Identifier("$LiftedBooleanOr"), a, b);
Bind = (f, t, c) => JsExpression.Invocation(JsExpression.Identifier("$Bind"), f, t);
BindFirstParameterToThis = (f, c) => JsExpression.Invocation(JsExpression.Identifier("$BindFirstParameterToThis"), f);
Default = (t, c) => t.Kind == TypeKind.Dynamic ? (JsExpression)JsExpression.Identifier("$DefaultDynamic") : JsExpression.Invocation(JsExpression.Identifier("$Default"), GetScriptType(t, TypeContext.GetDefaultValue, c.ResolveTypeParameter));
CreateArray = (t, dim, c) => JsExpression.Invocation(JsExpression.Identifier("$CreateArray"), new[] { GetScriptType(t, TypeContext.GetDefaultValue, c.ResolveTypeParameter) }.Concat(dim));
CloneDelegate = (e, s, t, c) => JsExpression.Invocation(JsExpression.Identifier("$CloneDelegate"), e);
CallBase = (m, a, c) => JsExpression.Invocation(JsExpression.Identifier("$CallBase"), new[] { GetScriptType(m.DeclaringType, TypeContext.BindBaseCall, c.ResolveTypeParameter), JsExpression.String("$" + m.Name), JsExpression.ArrayLiteral(m is SpecializedMethod ? ((SpecializedMethod)m).TypeArguments.Select(x => GetScriptType(x, TypeContext.GenericArgument, c.ResolveTypeParameter)) : new JsExpression[0]), JsExpression.ArrayLiteral(a) });
BindBaseCall = (m, a, c) => JsExpression.Invocation(JsExpression.Identifier("$BindBaseCall"), new[] { GetScriptType(m.DeclaringType, TypeContext.BindBaseCall, c.ResolveTypeParameter), JsExpression.String("$" + m.Name), JsExpression.ArrayLiteral(m is SpecializedMethod ? ((SpecializedMethod)m).TypeArguments.Select(x => GetScriptType(x, TypeContext.GenericArgument, c.ResolveTypeParameter)) : new JsExpression[0]), a });
MakeEnumerator = (yt, mn, gc, d, c) => JsExpression.Invocation(JsExpression.Identifier("$MakeEnumerator"), new[] { GetScriptType(yt, TypeContext.GenericArgument, c.ResolveTypeParameter), mn, gc, d ?? JsExpression.Null });
MakeEnumerable = (yt, ge, c) => JsExpression.Invocation(JsExpression.Identifier("$MakeEnumerable"), new[] { GetScriptType(yt, TypeContext.GenericArgument, c.ResolveTypeParameter), ge });
GetMultiDimensionalArrayValue = (a, i, c) => JsExpression.Invocation(JsExpression.Identifier("$MultidimArrayGet"), new[] { a }.Concat(i));
SetMultiDimensionalArrayValue = (a, i, v, c) => JsExpression.Invocation(JsExpression.Identifier("$MultidimArraySet"), new[] { a }.Concat(i).Concat(new[] { v }));
CreateTaskCompletionSource = (t, c) => JsExpression.Invocation(JsExpression.Identifier("$CreateTaskCompletionSource"), t != null ? GetScriptType(t, TypeContext.GenericArgument, c.ResolveTypeParameter) : JsExpression.String("non-generic"));
SetAsyncResult = (t, v, c) => JsExpression.Invocation(JsExpression.Identifier("$SetAsyncResult"), t, v ?? JsExpression.String("<<null>>"));
SetAsyncException = (t, e, c) => JsExpression.Invocation(JsExpression.Identifier("$SetAsyncException"), t, e);
GetTaskFromTaskCompletionSource = (t, c) => JsExpression.Invocation(JsExpression.Identifier("$GetTask"), t);
ApplyConstructor = (c, a, x) => JsExpression.Invocation(JsExpression.Identifier("$ApplyConstructor"), c, a);
ShallowCopy = (s, t, c) => JsExpression.Invocation(JsExpression.Identifier("$ShallowCopy"), s, t);
GetMember = (m, c) => JsExpression.Invocation(JsExpression.Identifier("$GetMember"), GetScriptType(m.DeclaringType, TypeContext.TypeOf, c.ResolveTypeParameter), JsExpression.String(m.Name));
GetExpressionForLocal = (n, a, t, c) => JsExpression.Invocation(JsExpression.Identifier("$Local"), JsExpression.String(n), GetScriptType(t, TypeContext.TypeOf, c.ResolveTypeParameter), a);
CloneValueType = (v, t, c) => JsExpression.Invocation(JsExpression.Identifier("$Clone"), v, GetScriptType(t, TypeContext.TypeOf, c.ResolveTypeParameter));
}
public Func<IType, IRuntimeContext, JsExpression> GetTypeOf { get; set; }
public Func<IType, IRuntimeContext, JsExpression> InstantiateType { get; set; }
public Func<IType, IRuntimeContext, JsExpression> InstantiateTypeForUseAsTypeArgumentInInlineCode { get; set; }
public Func<JsExpression, IType, IType, IRuntimeContext, JsExpression> TypeIs { get; set; }
public Func<JsExpression, IType, IType, IRuntimeContext, JsExpression> TryDowncast { get; set; }
public Func<JsExpression, IType, IType, IRuntimeContext, JsExpression> Downcast { get; set; }
public Func<JsExpression, IType, IType, IRuntimeContext, JsExpression> Upcast { get; set; }
public Func<JsExpression, IEnumerable<IType>, IRuntimeContext, JsExpression> InstantiateGenericMethod { get; set; }
new public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> ReferenceEquals { get; set; }
public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> ReferenceNotEquals { get; set; }
public Func<JsExpression, IRuntimeContext, JsExpression> MakeException { get; set; }
public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> IntegerDivision { get; set; }
public Func<JsExpression, IRuntimeContext, JsExpression> FloatToInt { get; set; }
public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> Coalesce { get; set; }
public Func<JsExpression, IRuntimeContext, JsExpression> Lift { get; set; }
public Func<JsExpression, IRuntimeContext, JsExpression> FromNullable { get; set; }
public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> LiftedBooleanAnd { get; set; }
public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> LiftedBooleanOr { get; set; }
public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> Bind { get; set; }
public Func<JsExpression, IRuntimeContext, JsExpression> BindFirstParameterToThis { get; set; }
public Func<IType, IRuntimeContext, JsExpression> Default { get; set; }
public Func<IType, IEnumerable<JsExpression>, IRuntimeContext, JsExpression> CreateArray { get; set; }
public Func<JsExpression, IType, IType, IRuntimeContext, JsExpression> CloneDelegate { get; set; }
public Func<IMethod, IEnumerable<JsExpression>, IRuntimeContext, JsExpression> CallBase { get; set; }
public Func<IMethod, JsExpression, IRuntimeContext, JsExpression> BindBaseCall { get; set; }
public Func<IType, JsExpression, JsExpression, JsExpression, IRuntimeContext, JsExpression> MakeEnumerator { get; set; }
public Func<IType, JsExpression, IRuntimeContext, JsExpression> MakeEnumerable { get; set; }
public Func<JsExpression, IEnumerable<JsExpression>, IRuntimeContext, JsExpression> GetMultiDimensionalArrayValue { get; set; }
public Func<JsExpression, IEnumerable<JsExpression>, JsExpression, IRuntimeContext, JsExpression> SetMultiDimensionalArrayValue { get; set; }
public Func<IType, IRuntimeContext, JsExpression> CreateTaskCompletionSource { get; set; }
public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> SetAsyncResult { get; set; }
public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> SetAsyncException { get; set; }
public Func<JsExpression, IRuntimeContext, JsExpression> GetTaskFromTaskCompletionSource { get; set; }
public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> ApplyConstructor { get; set; }
public Func<JsExpression, JsExpression, IRuntimeContext, JsExpression> ShallowCopy { get; set; }
public Func<IMember, IRuntimeContext, JsExpression> GetMember { get; set; }
public Func<string, JsExpression, IType, IRuntimeContext, JsExpression> GetExpressionForLocal { get; set; }
public Func<JsExpression, IType, IRuntimeContext, JsExpression> CloneValueType { get; set; }
private JsExpression GetScriptType(IType type, TypeContext context, Func<ITypeParameter, JsExpression> resolveTypeParameter) {
string contextName = GetTypeContextShortName(context);
if (type is ParameterizedType) {
var pt = (ParameterizedType)type;
return JsExpression.Invocation(JsExpression.Identifier(contextName + "_$InstantiateGenericType"), new[] { new JsTypeReferenceExpression(Common.CreateMockTypeDefinition(type.Name, Common.CreateMockAssembly())) }.Concat(pt.TypeArguments.Select(a => GetScriptType(a, TypeContext.GenericArgument, resolveTypeParameter))));
}
else if (type.TypeParameterCount > 0) {
// This handles open generic types ( typeof(C<,>) )
return new JsTypeReferenceExpression(Common.CreateMockTypeDefinition(contextName + "_" + type.GetDefinition().Name, Common.CreateMockAssembly()));
}
else if (type.Kind == TypeKind.Array) {
return JsExpression.Invocation(JsExpression.Identifier(contextName + "_$Array"), GetScriptType(((ArrayType)type).ElementType, TypeContext.GenericArgument, resolveTypeParameter));
}
else if (type.Kind == TypeKind.Anonymous) {
return JsExpression.Identifier(contextName + "_$Anonymous");
}
else if (type is ITypeDefinition) {
return new JsTypeReferenceExpression(Common.CreateMockTypeDefinition(contextName + "_" + type.Name, Common.CreateMockAssembly()));
}
else if (type is ITypeParameter) {
return resolveTypeParameter((ITypeParameter)type);
}
else {
throw new ArgumentException("Unsupported type + " + type);
}
}
JsExpression IRuntimeLibrary.TypeOf(IType type, IRuntimeContext context) {
return GetTypeOf(type, context);
}
JsExpression IRuntimeLibrary.InstantiateType(IType type, IRuntimeContext context) {
return InstantiateType(type, context);
}
JsExpression IRuntimeLibrary.InstantiateTypeForUseAsTypeArgumentInInlineCode(IType type, IRuntimeContext context) {
return InstantiateTypeForUseAsTypeArgumentInInlineCode(type, context);
}
JsExpression IRuntimeLibrary.TypeIs(JsExpression expression, IType sourceType, IType targetType, IRuntimeContext context) {
return TypeIs(expression, sourceType, targetType, context);
}
JsExpression IRuntimeLibrary.TryDowncast(JsExpression expression, IType sourceType, IType targetType, IRuntimeContext context) {
return TryDowncast(expression, sourceType, targetType, context);
}
JsExpression IRuntimeLibrary.Downcast(JsExpression expression, IType sourceType, IType targetType, IRuntimeContext context) {
return Downcast(expression, sourceType, targetType, context);
}
JsExpression IRuntimeLibrary.Upcast(JsExpression expression, IType sourceType, IType targetType, IRuntimeContext context) {
return Upcast(expression, sourceType, targetType, context);
}
JsExpression IRuntimeLibrary.ReferenceEquals(JsExpression a, JsExpression b, IRuntimeContext context) {
return ReferenceEquals(a, b, context);
}
JsExpression IRuntimeLibrary.ReferenceNotEquals(JsExpression a, JsExpression b, IRuntimeContext context) {
return ReferenceNotEquals(a, b, context);
}
JsExpression IRuntimeLibrary.InstantiateGenericMethod(JsExpression type, IEnumerable<IType> typeArguments, IRuntimeContext context) {
return InstantiateGenericMethod(type, typeArguments, context);
}
JsExpression IRuntimeLibrary.MakeException(JsExpression operand, IRuntimeContext context) {
return MakeException(operand, context);
}
JsExpression IRuntimeLibrary.IntegerDivision(JsExpression numerator, JsExpression denominator, IRuntimeContext context) {
return IntegerDivision(numerator, denominator, context);
}
JsExpression IRuntimeLibrary.FloatToInt(JsExpression operand, IRuntimeContext context) {
return FloatToInt(operand, context);
}
JsExpression IRuntimeLibrary.Coalesce(JsExpression a, JsExpression b, IRuntimeContext context) {
return Coalesce(a, b, context);
}
JsExpression IRuntimeLibrary.Lift(JsExpression expression, IRuntimeContext context) {
return Lift(expression, context);
}
JsExpression IRuntimeLibrary.FromNullable(JsExpression expression, IRuntimeContext context) {
return FromNullable(expression, context);
}
JsExpression IRuntimeLibrary.LiftedBooleanAnd(JsExpression a, JsExpression b, IRuntimeContext context) {
return LiftedBooleanAnd(a, b, context);
}
JsExpression IRuntimeLibrary.LiftedBooleanOr(JsExpression a, JsExpression b, IRuntimeContext context) {
return LiftedBooleanOr(a, b, context);
}
JsExpression IRuntimeLibrary.Bind(JsExpression function, JsExpression target, IRuntimeContext context) {
return Bind(function, target, context);
}
JsExpression IRuntimeLibrary.BindFirstParameterToThis(JsExpression function, IRuntimeContext context) {
return BindFirstParameterToThis(function, context);
}
JsExpression IRuntimeLibrary.Default(IType type, IRuntimeContext context) {
return Default(type, context);
}
JsExpression IRuntimeLibrary.CreateArray(IType elementType, IEnumerable<JsExpression> size, IRuntimeContext context) {
return CreateArray(elementType, size, context);
}
JsExpression IRuntimeLibrary.CloneDelegate(JsExpression source, IType sourceType, IType targetType, IRuntimeContext context) {
return CloneDelegate(source, sourceType, targetType, context);
}
JsExpression IRuntimeLibrary.CallBase(IMethod method, IEnumerable<JsExpression> thisAndArguments, IRuntimeContext context) {
return CallBase(method, thisAndArguments, context);
}
JsExpression IRuntimeLibrary.BindBaseCall(IMethod method, JsExpression @this, IRuntimeContext context) {
return BindBaseCall(method, @this, context);
}
JsExpression IRuntimeLibrary.MakeEnumerator(IType yieldType, JsExpression moveNext, JsExpression getCurrent, JsExpression dispose, IRuntimeContext context) {
return MakeEnumerator(yieldType, moveNext, getCurrent, dispose, context);
}
JsExpression IRuntimeLibrary.MakeEnumerable(IType yieldType, JsExpression getEnumerator, IRuntimeContext context) {
return MakeEnumerable(yieldType, getEnumerator, context);
}
JsExpression IRuntimeLibrary.GetMultiDimensionalArrayValue(JsExpression array, IEnumerable<JsExpression> indices, IRuntimeContext context) {
return GetMultiDimensionalArrayValue(array, indices, context);
}
JsExpression IRuntimeLibrary.SetMultiDimensionalArrayValue(JsExpression array, IEnumerable<JsExpression> indices, JsExpression value, IRuntimeContext context) {
return SetMultiDimensionalArrayValue(array, indices, value, context);
}
JsExpression IRuntimeLibrary.CreateTaskCompletionSource(IType taskGenericArgument, IRuntimeContext context) {
return CreateTaskCompletionSource(taskGenericArgument, context);
}
JsExpression IRuntimeLibrary.SetAsyncResult(JsExpression taskCompletionSource, JsExpression value, IRuntimeContext context) {
return SetAsyncResult(taskCompletionSource, value, context);
}
JsExpression IRuntimeLibrary.SetAsyncException(JsExpression taskCompletionSource, JsExpression exception, IRuntimeContext context) {
return SetAsyncException(taskCompletionSource, exception, context);
}
JsExpression IRuntimeLibrary.GetTaskFromTaskCompletionSource(JsExpression taskCompletionSource, IRuntimeContext context) {
return GetTaskFromTaskCompletionSource(taskCompletionSource, context);
}
JsExpression IRuntimeLibrary.ApplyConstructor(JsExpression constructor, JsExpression argumentsArray, IRuntimeContext context) {
return ApplyConstructor(constructor, argumentsArray, context);
}
JsExpression IRuntimeLibrary.ShallowCopy(JsExpression source, JsExpression target, IRuntimeContext context) {
return ShallowCopy(source, target, context);
}
JsExpression IRuntimeLibrary.GetMember(IMember member, IRuntimeContext context) {
return GetMember(member, context);
}
JsExpression IRuntimeLibrary.GetExpressionForLocal(string name, JsExpression accessor, IType type, IRuntimeContext context) {
return GetExpressionForLocal(name, accessor, type, context);
}
JsExpression IRuntimeLibrary.CloneValueType(JsExpression value, IType type, IRuntimeContext context) {
return CloneValueType(value, type, context);
}
}
}
| |
// 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.Xml;
using System.Collections;
namespace System.Data.Common
{
internal sealed class TimeSpanStorage : DataStorage
{
private static readonly TimeSpan s_defaultValue = TimeSpan.Zero;
private TimeSpan[] _values;
public TimeSpanStorage(DataColumn column)
: base(column, typeof(TimeSpan), s_defaultValue, StorageType.TimeSpan)
{
}
public override object Aggregate(int[] records, AggregateType kind)
{
bool hasData = false;
try
{
switch (kind)
{
case AggregateType.Min:
TimeSpan min = TimeSpan.MaxValue;
for (int i = 0; i < records.Length; i++)
{
int record = records[i];
if (IsNull(record))
continue;
min = (TimeSpan.Compare(_values[record], min) < 0) ? _values[record] : min;
hasData = true;
}
if (hasData)
{
return min;
}
return _nullValue;
case AggregateType.Max:
TimeSpan max = TimeSpan.MinValue;
for (int i = 0; i < records.Length; i++)
{
int record = records[i];
if (IsNull(record))
continue;
max = (TimeSpan.Compare(_values[record], max) >= 0) ? _values[record] : max;
hasData = true;
}
if (hasData)
{
return max;
}
return _nullValue;
case AggregateType.First:
if (records.Length > 0)
{
return _values[records[0]];
}
return null;
case AggregateType.Count:
return base.Aggregate(records, kind);
case AggregateType.Sum:
{
decimal sum = 0;
foreach (int record in records)
{
if (IsNull(record))
continue;
sum += _values[record].Ticks;
hasData = true;
}
if (hasData)
{
return TimeSpan.FromTicks((long)Math.Round(sum));
}
return null;
}
case AggregateType.Mean:
{
decimal meanSum = 0;
int meanCount = 0;
foreach (int record in records)
{
if (IsNull(record))
continue;
meanSum += _values[record].Ticks;
meanCount++;
}
if (meanCount > 0)
{
return TimeSpan.FromTicks((long)Math.Round(meanSum / meanCount));
}
return null;
}
case AggregateType.StDev:
{
int count = 0;
decimal meanSum = 0;
foreach (int record in records)
{
if (IsNull(record))
continue;
meanSum += _values[record].Ticks;
count++;
}
if (count > 1)
{
double varSum = 0;
decimal mean = meanSum / count;
foreach (int record in records)
{
if (IsNull(record))
continue;
double x = (double)(_values[record].Ticks - mean);
varSum += x * x;
}
ulong stDev = (ulong)Math.Round(Math.Sqrt(varSum / (count - 1)));
if (stDev > long.MaxValue)
{
stDev = long.MaxValue;
}
return TimeSpan.FromTicks((long)stDev);
}
return null;
}
}
}
catch (OverflowException)
{
throw ExprException.Overflow(typeof(TimeSpan));
}
throw ExceptionBuilder.AggregateException(kind, _dataType);
}
public override int Compare(int recordNo1, int recordNo2)
{
TimeSpan valueNo1 = _values[recordNo1];
TimeSpan valueNo2 = _values[recordNo2];
if (valueNo1 == s_defaultValue || valueNo2 == s_defaultValue)
{
int bitCheck = CompareBits(recordNo1, recordNo2);
if (0 != bitCheck)
return bitCheck;
}
return TimeSpan.Compare(valueNo1, valueNo2);
}
public override int CompareValueTo(int recordNo, object value)
{
System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record");
System.Diagnostics.Debug.Assert(null != value, "null value");
if (_nullValue == value)
{
if (IsNull(recordNo))
{
return 0;
}
return 1;
}
TimeSpan valueNo1 = _values[recordNo];
if ((s_defaultValue == valueNo1) && IsNull(recordNo))
{
return -1;
}
return valueNo1.CompareTo((TimeSpan)value);
}
private static TimeSpan ConvertToTimeSpan(object value)
{
// Do not change these checks
Type typeofValue = value.GetType();
if (typeofValue == typeof(string))
{
return TimeSpan.Parse((string)value);
}
else if (typeofValue == typeof(int))
{
return new TimeSpan((int)value);
}
else if (typeofValue == typeof(long))
{
return new TimeSpan((long)value);
}
else
{
return (TimeSpan)value;
}
}
public override object ConvertValue(object value)
{
if (_nullValue != value)
{
if (null != value)
{
value = ConvertToTimeSpan(value);
}
else
{
value = _nullValue;
}
}
return value;
}
public override void Copy(int recordNo1, int recordNo2)
{
CopyBits(recordNo1, recordNo2);
_values[recordNo2] = _values[recordNo1];
}
public override object Get(int record)
{
TimeSpan value = _values[record];
if (value != s_defaultValue)
{
return value;
}
return GetBits(record);
}
public override void Set(int record, object value)
{
System.Diagnostics.Debug.Assert(null != value, "null value");
if (_nullValue == value)
{
_values[record] = s_defaultValue;
SetNullBit(record, true);
}
else
{
_values[record] = ConvertToTimeSpan(value);
SetNullBit(record, false);
}
}
public override void SetCapacity(int capacity)
{
TimeSpan[] newValues = new TimeSpan[capacity];
if (null != _values)
{
Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length));
}
_values = newValues;
base.SetCapacity(capacity);
}
public override object ConvertXmlToObject(string s)
{
return XmlConvert.ToTimeSpan(s);
}
public override string ConvertObjectToXml(object value)
{
return XmlConvert.ToString((TimeSpan)value);
}
protected override object GetEmptyStorage(int recordCount)
{
return new TimeSpan[recordCount];
}
protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex)
{
TimeSpan[] typedStore = (TimeSpan[])store;
typedStore[storeIndex] = _values[record];
nullbits.Set(storeIndex, IsNull(record));
}
protected override void SetStorage(object store, BitArray nullbits)
{
_values = (TimeSpan[])store;
SetNullStorage(nullbits);
}
}
}
| |
#if UNITY_ANDROID && !UNITY_EDITOR
#define OVR_ANDROID_MRC
#endif
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OVRMixedRealityCaptureTest : MonoBehaviour {
bool inited = false;
enum CameraMode
{
Normal = 0,
OverrideFov,
ThirdPerson,
}
CameraMode currentMode = CameraMode.Normal;
public Camera defaultExternalCamera;
OVRPlugin.Fovf defaultFov;
// Use this for initialization
void Start () {
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || OVR_ANDROID_MRC
if (!defaultExternalCamera)
{
Debug.LogWarning("defaultExternalCamera undefined");
}
#if !OVR_ANDROID_MRC
// On Quest, we enable MRC automatically through the configuration
if (!OVRManager.instance.enableMixedReality)
{
OVRManager.instance.enableMixedReality = true;
}
#endif
#endif
}
void Initialize()
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || OVR_ANDROID_MRC
if (inited)
return;
#if OVR_ANDROID_MRC
if (!OVRPlugin.Media.GetInitialized())
return;
#else
if (!OVRPlugin.IsMixedRealityInitialized())
return;
#endif
OVRPlugin.ResetDefaultExternalCamera();
Debug.LogFormat("GetExternalCameraCount before adding manual external camera {0}", OVRPlugin.GetExternalCameraCount());
UpdateDefaultExternalCamera();
Debug.LogFormat("GetExternalCameraCount after adding manual external camera {0}", OVRPlugin.GetExternalCameraCount());
// obtain default FOV
{
OVRPlugin.CameraIntrinsics cameraIntrinsics;
OVRPlugin.CameraExtrinsics cameraExtrinsics;
OVRPlugin.Posef calibrationRawPose;
OVRPlugin.GetMixedRealityCameraInfo(0, out cameraExtrinsics, out cameraIntrinsics, out calibrationRawPose);
defaultFov = cameraIntrinsics.FOVPort;
}
inited = true;
#endif
}
void UpdateDefaultExternalCamera()
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || OVR_ANDROID_MRC
// always build a 1080p external camera
const int cameraPixelWidth = 1920;
const int cameraPixelHeight = 1080;
const float cameraAspect = (float)cameraPixelWidth / cameraPixelHeight;
string cameraName = "UnityExternalCamera";
OVRPlugin.CameraIntrinsics cameraIntrinsics = new OVRPlugin.CameraIntrinsics();
OVRPlugin.CameraExtrinsics cameraExtrinsics = new OVRPlugin.CameraExtrinsics();
// intrinsics
cameraIntrinsics.IsValid = OVRPlugin.Bool.True;
cameraIntrinsics.LastChangedTimeSeconds = Time.time;
float vFov = defaultExternalCamera.fieldOfView * Mathf.Deg2Rad;
float hFov = Mathf.Atan(Mathf.Tan(vFov * 0.5f) * cameraAspect) * 2.0f;
OVRPlugin.Fovf fov = new OVRPlugin.Fovf();
fov.UpTan = fov.DownTan = Mathf.Tan(vFov * 0.5f);
fov.LeftTan = fov.RightTan = Mathf.Tan(hFov * 0.5f);
cameraIntrinsics.FOVPort = fov;
cameraIntrinsics.VirtualNearPlaneDistanceMeters = defaultExternalCamera.nearClipPlane;
cameraIntrinsics.VirtualFarPlaneDistanceMeters = defaultExternalCamera.farClipPlane;
cameraIntrinsics.ImageSensorPixelResolution.w = cameraPixelWidth;
cameraIntrinsics.ImageSensorPixelResolution.h = cameraPixelHeight;
// extrinsics
cameraExtrinsics.IsValid = OVRPlugin.Bool.True;
cameraExtrinsics.LastChangedTimeSeconds = Time.time;
cameraExtrinsics.CameraStatusData = OVRPlugin.CameraStatus.CameraStatus_Calibrated;
cameraExtrinsics.AttachedToNode = OVRPlugin.Node.None;
Camera mainCamera = Camera.main;
OVRCameraRig cameraRig = mainCamera.GetComponentInParent<OVRCameraRig>();
if (cameraRig)
{
Transform trackingSpace = cameraRig.trackingSpace;
OVRPose trackingSpacePose = trackingSpace.ToOVRPose(false);
OVRPose cameraPose = defaultExternalCamera.transform.ToOVRPose(false);
OVRPose relativePose = trackingSpacePose.Inverse() * cameraPose;
cameraExtrinsics.RelativePose = relativePose.ToPosef();
}
else
{
cameraExtrinsics.RelativePose = OVRPlugin.Posef.identity;
}
if (!OVRPlugin.SetDefaultExternalCamera(cameraName, ref cameraIntrinsics, ref cameraExtrinsics))
{
Debug.LogError("SetDefaultExternalCamera() failed");
}
#endif
}
// Update is called once per frame
void Update () {
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || OVR_ANDROID_MRC
if (!inited)
{
Initialize();
return;
}
if (!defaultExternalCamera)
{
return;
}
#if OVR_ANDROID_MRC
if (!OVRPlugin.Media.GetInitialized())
{
return;
}
#else
if (!OVRPlugin.IsMixedRealityInitialized())
{
return;
}
#endif
if (OVRInput.GetDown(OVRInput.Button.One))
{
if (currentMode == CameraMode.ThirdPerson)
{
currentMode = CameraMode.Normal;
}
else
{
currentMode = currentMode + 1;
}
Debug.LogFormat("Camera mode change to {0}", currentMode);
}
if (currentMode == CameraMode.Normal)
{
UpdateDefaultExternalCamera();
OVRPlugin.OverrideExternalCameraFov(0, false, new OVRPlugin.Fovf());
OVRPlugin.OverrideExternalCameraStaticPose(0, false, OVRPlugin.Posef.identity);
}
else if (currentMode == CameraMode.OverrideFov)
{
OVRPlugin.Fovf fov = defaultFov;
OVRPlugin.Fovf newFov = new OVRPlugin.Fovf();
newFov.LeftTan = fov.LeftTan * 2.0f;
newFov.RightTan = fov.RightTan * 2.0f;
newFov.UpTan = fov.UpTan * 2.0f;
newFov.DownTan = fov.DownTan * 2.0f;
OVRPlugin.OverrideExternalCameraFov(0, true, newFov);
OVRPlugin.OverrideExternalCameraStaticPose(0, false, OVRPlugin.Posef.identity);
if (!OVRPlugin.GetUseOverriddenExternalCameraFov(0))
{
Debug.LogWarning("FOV not overridden");
}
}
else if (currentMode == CameraMode.ThirdPerson)
{
Camera camera = GetComponent<Camera>();
if (camera == null)
{
return;
}
float vFov = camera.fieldOfView * Mathf.Deg2Rad;
float hFov = Mathf.Atan(Mathf.Tan(vFov * 0.5f) * camera.aspect) * 2.0f;
OVRPlugin.Fovf fov = new OVRPlugin.Fovf();
fov.UpTan = fov.DownTan = Mathf.Tan(vFov * 0.5f);
fov.LeftTan = fov.RightTan = Mathf.Tan(hFov * 0.5f);
OVRPlugin.OverrideExternalCameraFov(0, true, fov);
Camera mainCamera = Camera.main;
OVRCameraRig cameraRig = mainCamera.GetComponentInParent<OVRCameraRig>();
if (cameraRig)
{
Transform trackingSpace = cameraRig.trackingSpace;
OVRPose trackingSpacePose = trackingSpace.ToOVRPose(false);
OVRPose cameraPose = transform.ToOVRPose(false);
OVRPose relativePose = trackingSpacePose.Inverse() * cameraPose;
OVRPlugin.Posef relativePosef = relativePose.ToPosef();
OVRPlugin.OverrideExternalCameraStaticPose(0, true, relativePosef);
}
else
{
OVRPlugin.OverrideExternalCameraStaticPose(0, false, OVRPlugin.Posef.identity);
}
if (!OVRPlugin.GetUseOverriddenExternalCameraFov(0))
{
Debug.LogWarning("FOV not overridden");
}
if (!OVRPlugin.GetUseOverriddenExternalCameraStaticPose(0))
{
Debug.LogWarning("StaticPose not overridden");
}
}
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// HashRepartitionEnumerator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
namespace System.Linq.Parallel
{
/// <summary>
/// This enumerator handles the actual coordination among partitions required to
/// accomplish the repartitioning operation, as explained above.
/// </summary>
/// <typeparam name="TInputOutput">The kind of elements.</typeparam>
/// <typeparam name="THashKey">The key used to distribute elements.</typeparam>
/// <typeparam name="TIgnoreKey">The kind of keys found in the source (ignored).</typeparam>
internal class HashRepartitionEnumerator<TInputOutput, THashKey, TIgnoreKey> : QueryOperatorEnumerator<Pair, int>
{
private const int ENUMERATION_NOT_STARTED = -1; // Sentinel to note we haven't begun enumerating yet.
private readonly int _partitionCount; // The number of partitions.
private readonly int _partitionIndex; // Our unique partition index.
private readonly Func<TInputOutput, THashKey> _keySelector; // A key-selector function.
private readonly HashRepartitionStream<TInputOutput, THashKey, int> _repartitionStream; // A repartitioning stream.
private readonly ListChunk<Pair>[][] _valueExchangeMatrix; // Matrix to do inter-task communication.
private readonly QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; // The immediate source of data.
private CountdownEvent _barrier; // Used to signal and wait for repartitions to complete.
private readonly CancellationToken _cancellationToken; // A token for canceling the process.
private Mutables _mutables; // Mutable fields for this enumerator.
class Mutables
{
internal int _currentBufferIndex; // Current buffer index.
internal ListChunk<Pair> _currentBuffer; // The buffer we're currently enumerating.
internal int _currentIndex; // Current index into the buffer.
internal Mutables()
{
_currentBufferIndex = ENUMERATION_NOT_STARTED;
}
}
//---------------------------------------------------------------------------------------
// Creates a new repartitioning enumerator.
//
// Arguments:
// source - the data stream from which to pull elements
// useOrdinalOrderPreservation - whether order preservation is required
// partitionCount - total number of partitions
// partitionIndex - this operator's unique partition index
// repartitionStream - the stream object to use for partition selection
// barrier - a latch used to signal task completion
// buffers - a set of buffers for inter-task communication
//
internal HashRepartitionEnumerator(
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, int partitionCount, int partitionIndex,
Func<TInputOutput, THashKey> keySelector, HashRepartitionStream<TInputOutput, THashKey, int> repartitionStream,
CountdownEvent barrier, ListChunk<Pair>[][] valueExchangeMatrix, CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(keySelector != null || typeof(THashKey) == typeof(NoKeyMemoizationRequired));
Debug.Assert(repartitionStream != null);
Debug.Assert(barrier != null);
Debug.Assert(valueExchangeMatrix != null);
Debug.Assert(valueExchangeMatrix.GetLength(0) == partitionCount, "expected square matrix of buffers (NxN)");
Debug.Assert(partitionCount > 0 && valueExchangeMatrix[0].Length == partitionCount, "expected square matrix of buffers (NxN)");
Debug.Assert(0 <= partitionIndex && partitionIndex < partitionCount);
_source = source;
_partitionCount = partitionCount;
_partitionIndex = partitionIndex;
_keySelector = keySelector;
_repartitionStream = repartitionStream;
_barrier = barrier;
_valueExchangeMatrix = valueExchangeMatrix;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Retrieves the next element from this partition. All repartitioning operators across
// all partitions cooperate in a barrier-style algorithm. The first time an element is
// requested, the repartitioning operator will enter the 1st phase: during this phase, it
// scans its entire input and compute the destination partition for each element. During
// the 2nd phase, each partition scans the elements found by all other partitions for
// it, and yield this to callers. The only synchronization required is the barrier itself
// -- all other parts of this algorithm are synchronization-free.
//
// Notes: One rather large penalty that this algorithm incurs is higher memory usage and a
// larger time-to-first-element latency, at least compared with our old implementation; this
// happens because all input elements must be fetched before we can produce a single output
// element. In many cases this isn't too terrible: e.g. a GroupBy requires this to occur
// anyway, so having the repartitioning operator do so isn't complicating matters much at all.
//
internal override bool MoveNext(ref Pair currentElement, ref int currentKey)
{
if (_partitionCount == 1)
{
// If there's only one partition, no need to do any sort of exchanges.
TIgnoreKey keyUnused = default(TIgnoreKey);
TInputOutput current = default(TInputOutput);
#if DEBUG
currentKey = unchecked((int)0xdeadbeef);
#endif
if (_source.MoveNext(ref current, ref keyUnused))
{
currentElement = new Pair(
current, _keySelector == null ? default(THashKey) : _keySelector(current));
return true;
}
return false;
}
Mutables mutables = _mutables;
if (mutables == null)
mutables = _mutables = new Mutables();
// If we haven't enumerated the source yet, do that now. This is the first phase
// of a two-phase barrier style operation.
if (mutables._currentBufferIndex == ENUMERATION_NOT_STARTED)
{
EnumerateAndRedistributeElements();
Debug.Assert(mutables._currentBufferIndex != ENUMERATION_NOT_STARTED);
}
// Once we've enumerated our contents, we can then go back and walk the buffers that belong
// to the current partition. This is phase two. Note that we slyly move on to the first step
// of phase two before actually waiting for other partitions. That's because we can enumerate
// the buffer we wrote to above, as already noted.
while (mutables._currentBufferIndex < _partitionCount)
{
// If the queue is non-null and still has elements, yield them.
if (mutables._currentBuffer != null)
{
if (++mutables._currentIndex < mutables._currentBuffer.Count)
{
// Return the current element.
currentElement = mutables._currentBuffer._chunk[mutables._currentIndex];
return true;
}
else
{
// If the chunk is empty, advance to the next one (if any).
mutables._currentIndex = ENUMERATION_NOT_STARTED;
mutables._currentBuffer = mutables._currentBuffer.Next;
Debug.Assert(mutables._currentBuffer == null || mutables._currentBuffer.Count > 0);
continue; // Go back around and invoke this same logic.
}
}
// We're done with the current partition. Slightly different logic depending on whether
// we're on our own buffer or one that somebody else found for us.
if (mutables._currentBufferIndex == _partitionIndex)
{
// We now need to wait at the barrier, in case some other threads aren't done.
// Once we wake up, we reset our index and will increment it immediately after.
_barrier.Wait(_cancellationToken);
mutables._currentBufferIndex = ENUMERATION_NOT_STARTED;
}
// Advance to the next buffer.
mutables._currentBufferIndex++;
mutables._currentIndex = ENUMERATION_NOT_STARTED;
if (mutables._currentBufferIndex == _partitionIndex)
{
// Skip our current buffer (since we already enumerated it).
mutables._currentBufferIndex++;
}
// Assuming we're within bounds, retrieve the next buffer object.
if (mutables._currentBufferIndex < _partitionCount)
{
mutables._currentBuffer = _valueExchangeMatrix[mutables._currentBufferIndex][_partitionIndex];
}
}
// We're done. No more buffers to enumerate.
return false;
}
//---------------------------------------------------------------------------------------
// Called when this enumerator is first enumerated; it must walk through the source
// and redistribute elements to their slot in the exchange matrix.
//
private void EnumerateAndRedistributeElements()
{
Mutables mutables = _mutables;
Debug.Assert(mutables != null);
ListChunk<Pair>[] privateBuffers = new ListChunk<Pair>[_partitionCount];
TInputOutput element = default(TInputOutput);
TIgnoreKey ignoreKey = default(TIgnoreKey);
int loopCount = 0;
while (_source.MoveNext(ref element, ref ignoreKey))
{
if ((loopCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Calculate the element's destination partition index, placing it into the
// appropriate buffer from which partitions will later enumerate.
int destinationIndex;
THashKey elementHashKey = default(THashKey);
if (_keySelector != null)
{
elementHashKey = _keySelector(element);
destinationIndex = _repartitionStream.GetHashCode(elementHashKey) % _partitionCount;
}
else
{
Debug.Assert(typeof(THashKey) == typeof(NoKeyMemoizationRequired));
destinationIndex = _repartitionStream.GetHashCode(element) % _partitionCount;
}
Debug.Assert(0 <= destinationIndex && destinationIndex < _partitionCount,
"destination partition outside of the legal range of partitions");
// Get the buffer for the destnation partition, lazily allocating if needed. We maintain
// this list in our own private cache so that we avoid accessing shared memory locations
// too much. In the original implementation, we'd access the buffer in the matrix ([N,M],
// where N is the current partition and M is the destination), but some rudimentary
// performance profiling indicates copying at the end performs better.
ListChunk<Pair> buffer = privateBuffers[destinationIndex];
if (buffer == null)
{
const int INITIAL_PRIVATE_BUFFER_SIZE = 128;
privateBuffers[destinationIndex] = buffer = new ListChunk<Pair>(INITIAL_PRIVATE_BUFFER_SIZE);
}
buffer.Add(new Pair(element, elementHashKey));
}
// Copy the local buffers to the shared space and then signal to other threads that
// we are done. We can then immediately move on to enumerating the elements we found
// for the current partition before waiting at the barrier. If we found a lot, we will
// hopefully never have to physically wait.
for (int i = 0; i < _partitionCount; i++)
{
_valueExchangeMatrix[_partitionIndex][i] = privateBuffers[i];
}
_barrier.Signal();
// Begin at our own buffer.
mutables._currentBufferIndex = _partitionIndex;
mutables._currentBuffer = privateBuffers[_partitionIndex];
mutables._currentIndex = ENUMERATION_NOT_STARTED;
}
protected override void Dispose(bool disposed)
{
if (_barrier != null)
{
// Since this enumerator is being disposed, we will decrement the barrier,
// in case other enumerators will wait on the barrier.
if (_mutables == null || (_mutables._currentBufferIndex == ENUMERATION_NOT_STARTED))
{
_barrier.Signal();
_barrier = null;
}
_source.Dispose();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Test.ModuleCore;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.Threading;
using XmlCoreTest.Common;
namespace CoreXml.Test.XLinq
{
public partial class XNodeBuilderFunctionalTests : TestModule
{
public partial class XNodeBuilderTests : XLinqTestCase
{
public partial class OmitAnotation : XLinqTestCase
{
private static string s_MyPath = Path.Combine(FilePathUtil.GetTestDataPath(), @"Xlinq\DuplicateNamespaces");
private static XContainer GetContainer(string filename, Type type)
{
switch (type.Name)
{
case "XElement":
return XElement.Load(FilePathUtil.getStream(filename));
case "XDocument":
return XDocument.Load(FilePathUtil.getStream(filename));
default:
throw new TestFailedException("Type not recognized");
}
}
private static XContainer GetContainer(Stream stream, Type type)
{
switch (type.Name)
{
case "XElement":
return XElement.Load(stream);
case "XDocument":
return XDocument.Load(stream);
default:
throw new TestFailedException("Type not recognized");
}
}
//[Variation(Priority = 0, Desc = "No annotation - element", Params = new object[] { typeof(XElement), "Simple.xml" })]
//[Variation(Priority = 0, Desc = "No annotation - document", Params = new object[] { typeof(XDocument), "Simple.xml" })]
public void NoAnnotation()
{
Type t = CurrentChild.Params[0] as Type;
string fileName = Path.Combine(s_MyPath, CurrentChild.Params[1] as string);
// create normal reader for comparison
using (XmlReader r1 = XmlReader.Create(FilePathUtil.getStream(fileName), new XmlReaderSettings() { IgnoreWhitespace = true, DtdProcessing = DtdProcessing.Ignore }))
{
// create reader from Xlinq
XContainer c = GetContainer(fileName, t);
using (XmlReader r2 = c.CreateReader())
{
ReaderDiff.Compare(r1, r2);
}
}
}
//[Variation(Priority = 2, Desc = "Annotation on document without omit - None", Params = new object[] { typeof(XDocument), "Simple.xml", SaveOptions.None })]
//[Variation(Priority = 2, Desc = "Annotation on document without omit - DisableFormating", Params = new object[] { typeof(XDocument), "Simple.xml", SaveOptions.DisableFormatting })]
//[Variation(Priority = 2, Desc = "Annotation on element without omit - None", Params = new object[] { typeof(XElement), "Simple.xml", SaveOptions.None })]
//[Variation(Priority = 2, Desc = "Annotation on element without omit - DisableFormating", Params = new object[] { typeof(XElement), "Simple.xml", SaveOptions.DisableFormatting })]
public void AnnotationWithoutTheOmitDuplicates()
{
Type t = CurrentChild.Params[0] as Type;
string fileName = Path.Combine(s_MyPath, CurrentChild.Params[1] as string);
SaveOptions so = (SaveOptions)CurrentChild.Params[2];
using (XmlReader r1 = XmlReader.Create(FilePathUtil.getStream(fileName), new XmlReaderSettings() { IgnoreWhitespace = true, DtdProcessing = DtdProcessing.Ignore }))
{
XContainer doc = GetContainer(fileName, t);
doc.AddAnnotation(so);
using (XmlReader r2 = doc.CreateReader())
{
ReaderDiff.Compare(r1, r2);
}
}
}
//[Variation(Priority = 0, Desc = "Annotation on document - Omit", Params = new object[] { typeof(XDocument), "Simple.xml", SaveOptions.OmitDuplicateNamespaces })]
//[Variation(Priority = 1, Desc = "Annotation on document - Omit + Disable", Params = new object[] { typeof(XDocument), "Simple.xml", SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting })]
//[Variation(Priority = 0, Desc = "Annotation on element - Omit", Params = new object[] { typeof(XElement), "Simple.xml", SaveOptions.OmitDuplicateNamespaces })]
//[Variation(Priority = 1, Desc = "Annotation on element - Omit + Disable", Params = new object[] { typeof(XElement), "Simple.xml", SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting })]
public void XDocAnnotation()
{
Type t = CurrentChild.Params[0] as Type;
string fileName = Path.Combine(s_MyPath, CurrentChild.Params[1] as string);
SaveOptions so = (SaveOptions)CurrentChild.Params[2];
using (MemoryStream ms = new MemoryStream())
{
XDocument toClean = XDocument.Load(FilePathUtil.getStream(fileName));
using (XmlWriter w = XmlWriter.Create(ms, new XmlWriterSettings() { OmitXmlDeclaration = true, NamespaceHandling = NamespaceHandling.OmitDuplicates }))
{
toClean.Save(w);
}
ms.Position = 0;
using (XmlReader r1 = XmlReader.Create(ms, new XmlReaderSettings() { IgnoreWhitespace = true, DtdProcessing = DtdProcessing.Ignore }))
{
XContainer doc = GetContainer(fileName, t);
doc.AddAnnotation(so);
using (XmlReader r2 = doc.CreateReader())
{
ReaderDiff.Compare(r1, r2);
}
}
}
}
//[Variation(Priority = 0, Desc = "Annotation on the parent nodes, XElement", Params = new object[] { typeof(XElement), "simple.xml" })]
//[Variation(Priority = 0, Desc = "Annotation on the parent nodes, XDocument", Params = new object[] { typeof(XDocument), "simple.xml" })]
public void AnnotationOnParent1()
{
Type t = CurrentChild.Params[0] as Type;
string fileName = Path.Combine(s_MyPath, CurrentChild.Params[1] as string);
var orig = GetContainer(fileName, t).DescendantNodes().ToArray();
var test = GetContainer(fileName, t).DescendantNodes().ToArray();
for (int i = 0; i < test.Count(); i++)
{
XNode n = test[i];
XNode parent = n; // verify parent and self
while (parent != null)
{ // for all parents
// verify original version
TestLog.Compare(n.ToString(), n.ToString(SaveOptions.None), "Initial value");
TestLog.Compare(n.ToString(), orig[i].ToString(), "Initial value, via orig");
ReaderDiff.Compare(orig[i].CreateReader(), n.CreateReader());
// add annotation on parent
parent.AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
// verify with annotation
TestLog.Compare(n.ToString(), n.ToString(SaveOptions.OmitDuplicateNamespaces), "with the annotation, normal");
ReaderDiffNSAware.CompareNamespaceAware(orig[i].CreateReader(), n.CreateReader());
// removeannotation
parent.RemoveAnnotations(typeof(SaveOptions));
// verify after removal
TestLog.Compare(n.ToString(), n.ToString(SaveOptions.None), "after removed annotation value");
TestLog.Compare(n.ToString(), orig[i].ToString(), "after removed annotation, via orig");
ReaderDiff.Compare(orig[i].CreateReader(), n.CreateReader());
// move parent
if (parent is XDocument) break;
parent = parent.Parent ?? parent.Document as XNode;
}
}
}
//[Variation(Priority = 0, Desc = "Multiple annotations in the tree - both up - XElement", Param = typeof(XElement))]
//[Variation(Priority = 0, Desc = "Multiple annotations in the tree - both up - XDocument", Param = typeof(XDocument))]
public void MultipleAnnotationsInTree()
{
Type t = CurrentChild.Param as Type;
string xml = @"<A xmlns:p='a1'><B xmlns:q='a2'><C xmlns:p='a1'><D xmlns:q='a2' ><E xmlns:p='a1' /></D></C></B></A>";
XContainer reF = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer); // I want dynamics!!!
SaveOptions[] options = new SaveOptions[] { SaveOptions.None, SaveOptions.DisableFormatting, SaveOptions.OmitDuplicateNamespaces, SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces };
foreach (SaveOptions[] opts in Tuples2(options))
{
XContainer gp = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer);
gp.AddAnnotation(opts[0]);
gp.FirstNode.AddAnnotation(opts[1]);
TestLog.Compare(reF.Descendants("C").First().ToString(opts[1]), gp.Descendants("C").First().ToString(), "On C - ToString()");
ReaderDiffNSAware.CompareNamespaceAware(opts[1], reF.Descendants("C").First().CreateReader(), gp.Descendants("C").First().CreateReader());
TestLog.Compare(reF.Descendants("B").First().ToString(opts[1]), gp.Descendants("B").First().ToString(), "On C - ToString()");
ReaderDiffNSAware.CompareNamespaceAware(opts[1], reF.Descendants("B").First().CreateReader(), gp.Descendants("B").First().CreateReader());
}
}
//[Variation(Priority = 0, Desc = "Multiple annotations in the tree - up/down - XElement", Param = typeof(XElement))]
//[Variation(Priority = 0, Desc = "Multiple annotations in the tree - up/down - XDocument", Param = typeof(XDocument))]
public void MultipleAnnotationsInTree2()
{
Type t = CurrentChild.Param as Type;
string xml = @"<A xmlns:p='a1'><B xmlns:q='a2'><C xmlns:p='a1'><D xmlns:q='a2' ><E xmlns:p='a1' /></D></C></B></A>";
XContainer reF = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer); // I want dynamics!!!
SaveOptions[] options = new SaveOptions[] { SaveOptions.None, SaveOptions.DisableFormatting, SaveOptions.OmitDuplicateNamespaces, SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces };
foreach (SaveOptions[] opts in Tuples2(options))
{
XContainer gp = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer);
gp.AddAnnotation(opts[0]);
gp.Descendants("C").First().AddAnnotation(opts[1]);
TestLog.Compare(reF.ToString(opts[0]), gp.ToString(), "On root - ToString()");
ReaderDiffNSAware.CompareNamespaceAware(opts[0], reF.CreateReader(), gp.CreateReader());
TestLog.Compare(reF.Descendants("B").First().ToString(opts[0]), gp.Descendants("B").First().ToString(), "On C - ToString()");
ReaderDiffNSAware.CompareNamespaceAware(opts[0], reF.Descendants("B").First().CreateReader(), gp.Descendants("B").First().CreateReader());
}
}
//[Variation(Priority = 0, Desc = "Multiple annotations on node - XDocument", Param = typeof(XDocument))]
//[Variation(Priority = 0, Desc = "Multiple annotations on node - XElement", Param = typeof(XElement))]
public void MultipleAnnotationsOnElement()
{
Type t = CurrentChild.Param as Type;
string xml = @"<A xmlns:p='a1'><B xmlns:q='a2'><C xmlns:p='a1'><D xmlns:q='a2' ><E xmlns:p='a1' /></D></C></B></A>";
XContainer reF = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer); // I want dynamics!!!
SaveOptions[] options = new SaveOptions[] { SaveOptions.None, SaveOptions.DisableFormatting, SaveOptions.OmitDuplicateNamespaces, SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces };
foreach (SaveOptions[] opts in Tuples2(options))
{
XContainer gp = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer);
foreach (SaveOptions o in opts)
{
gp.AddAnnotation(o);
}
TestLog.Compare(reF.ToString(opts[0]), gp.ToString(), "On root - ToString()");
ReaderDiffNSAware.CompareNamespaceAware(opts[0], reF.CreateReader(), gp.CreateReader());
}
}
static IEnumerable<T[]> Tuples2<T>(T[] array)
{
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
if (i != j) yield return new T[] { array[i], array[j] };
}
}
}
//[Variation(Priority = 2, Desc = "On other node types - attributes", Param = typeof(XElement))]
public void OnOtherNodesAttrs()
{
string fileName = Path.Combine(s_MyPath, "attributes.xml");
TestLog.WriteLineIgnore("Loading: .... " + fileName);
XElement reF = XElement.Load(FilePathUtil.getStream(fileName));
XElement e = XElement.Load(FilePathUtil.getStream(fileName));
e.AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
XAttribute[] refAttrs = reF.DescendantsAndSelf().Attributes().ToArray();
XAttribute[] eAttrs = e.DescendantsAndSelf().Attributes().ToArray();
for (int i = 0; i < refAttrs.Length; i++)
{
TestLog.Compare(refAttrs[i].ToString(), eAttrs[i].ToString(), "without annotation on attribute");
eAttrs[i].AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
TestLog.Compare(refAttrs[i].ToString(), eAttrs[i].ToString(), "with annotation on attribute");
}
}
private static XElement CreateVBSample()
{
XElement e1 = new XElement("{ns1}A", new XAttribute("xmlns", "ns1"));
XElement c1 = new XElement("{ns1}B", new XAttribute("xmlns", "ns1"));
XElement c2 = new XElement("{ns1}C", new XAttribute("xmlns", "ns1"));
e1.Add(c1, c2);
e1.AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
return e1;
}
//[Variation(Priority = 0, Desc = "Simulate the VB behavior - Save")]
public void SimulateVb1()
{
string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<A xmlns=\"ns1\">\n <B />\n <C />\n</A>";
XElement e1 = CreateVBSample();
StringBuilder sb = new StringBuilder();
e1.Save(new StringWriter(sb));
ReaderDiff.Compare(sb.ToString(), expected);
}
//[Variation(Priority = 0, Desc = "Simulate the VB behavior - Reader")]
public void SimulateVb2()
{
string expected = "<A xmlns=\"ns1\"><B /><C /></A>";
XElement e1 = CreateVBSample();
using (XmlReader r1 = XmlReader.Create(new StringReader(expected)))
{
using (XmlReader r2 = e1.CreateReader())
{
ReaderDiff.Compare(r1, r2);
}
}
}
//[Variation(Priority = 0, Desc = "Local settings override annotation")]
public void LocalOverride()
{
string expected = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<A xmlns=\"ns1\">\n <B xmlns=\"ns1\"/>\n <C xmlns=\"ns1\"/>\n</A>";
XElement e1 = CreateVBSample();
StringBuilder sb = new StringBuilder();
e1.Save(new StringWriter(sb), SaveOptions.None);
ReaderDiff.Compare(sb.ToString(), expected);
}
//[Variation(Priority = 0, Desc = "XDocument - ReaderOptions.None", Params = new object[] { typeof(XDocument), "simple.xml", ReaderOptions.None })]
//[Variation(Priority = 0, Desc = "XDocument - ReaderOptions.OmitDuplicateNamespaces", Params = new object[] { typeof(XDocument), "simple.xml", ReaderOptions.OmitDuplicateNamespaces })]
//[Variation(Priority = 0, Desc = "XElement - ReaderOptions.None", Params= new object [] {typeof(XElement), "simple.xml", ReaderOptions.None })]
//[Variation(Priority = 0, Desc = "XElement - ReaderOptions.OmitDuplicateNamespaces", Params = new object[] { typeof(XElement), "simple.xml", ReaderOptions.OmitDuplicateNamespaces })]
public void ReaderOptionsSmoke()
{
Type t = CurrentChild.Params[0] as Type;
string fileName = Path.Combine(s_MyPath, CurrentChild.Params[1] as string);
ReaderOptions ro = (ReaderOptions)CurrentChild.Params[2];
var original = GetContainer(fileName, t).DescendantNodes().ToArray();
var clone = GetContainer(fileName, t).DescendantNodes().ToArray();
TestLog.Compare(original.Length, clone.Length, "original.Length != clone.Length"); // assert
Action<XmlReader, XmlReader> compareDelegate = ro == ReaderOptions.None ? (Action<XmlReader, XmlReader>)ReaderDiff.Compare : (Action<XmlReader, XmlReader>)ReaderDiffNSAware.CompareNamespaceAware;
foreach (int i in Enumerable.Range(0, original.Length))
{
// no annotation
compareDelegate(original[i].CreateReader(), clone[i].CreateReader(ro));
// annotation on self
foreach (SaveOptions so in new SaveOptions[] { SaveOptions.None, SaveOptions.OmitDuplicateNamespaces })
{
clone[i].AddAnnotation(so);
compareDelegate(original[i].CreateReader(), clone[i].CreateReader(ro));
clone[i].RemoveAnnotations(typeof(object));
}
// annotation on parents
foreach (SaveOptions so in new SaveOptions[] { SaveOptions.None, SaveOptions.OmitDuplicateNamespaces })
{
foreach (XNode anc in clone[i].Ancestors())
{
anc.AddAnnotation(so);
compareDelegate(original[i].CreateReader(), clone[i].CreateReader(ro));
anc.RemoveAnnotations(typeof(object));
}
}
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Joins;
using System.Reactive.Subjects;
using System.Threading;
namespace System.Reactive.Linq
{
public static partial class Observable
{
public static IObservable<IList<TSource>> Buffer<TSource, TBufferClosing> (
this IObservable<TSource> source,
Func<IObservable<TBufferClosing>> bufferClosingSelector)
{
return Buffer<TSource, int, TBufferClosing> (source, Range (0, int.MaxValue), l => bufferClosingSelector ());
}
public static IObservable<IList<TSource>> Buffer<TSource> (
this IObservable<TSource> source,
int count)
{
return source.Buffer (TimeSpan.MaxValue, count);
}
public static IObservable<IList<TSource>> Buffer<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan)
{
return Buffer<TSource> (source, timeSpan, Scheduler.ThreadPool);
}
struct ListCountContext<TSource>
{
public ListCountContext (int start, List<TSource> list)
{
this.start = start;
this.list = list;
}
readonly int start;
readonly List<TSource> list;
public int Start {
get { return start; }
}
public List<TSource> List {
get { return list; }
}
}
public static IObservable<IList<TSource>> Buffer<TSource> (
this IObservable<TSource> source,
int count,
int skip)
{
if (source == null)
throw new ArgumentNullException ("source");
return new ColdObservableEach<IList<TSource>> (sub => {
// ----
var lists = new List<ListCountContext<TSource>> ();
int current = 0;
int nextStart = 0;
Action cleanup = () => { foreach (var lc in lists) sub.OnNext (lc.List); };
var dis = source.Subscribe (Observer.Create<TSource> (v => {
if (current == nextStart) {
var lc = new ListCountContext<TSource> (current, new List<TSource> ());
lists.Add (lc);
nextStart += skip;
}
for (int x = 0; x < lists.Count; ) {
if (current - lists [x].Start == count) {
sub.OnNext (lists [x].List);
lists.RemoveAt (x);
}
else
lists [x++].List.Add (v);
}
current++;
}, ex => { cleanup (); throw ex; }, () => { cleanup (); sub.OnCompleted (); }));
return dis;
// ----
}, DefaultColdScheduler);
}
public static IObservable<IList<TSource>> Buffer<TSource, TBufferOpening, TBufferClosing> (
this IObservable<TSource> source,
IObservable<TBufferOpening> bufferOpenings,
Func<TBufferOpening, IObservable<TBufferClosing>> bufferClosingSelector)
{
if (source == null)
throw new ArgumentNullException ("source");
if (bufferOpenings == null)
throw new ArgumentNullException ("bufferOpenings");
if (bufferClosingSelector == null)
throw new ArgumentNullException ("bufferClosingSelector");
return new ColdObservableEach<IList<TSource>> (sub => {
// ----
var l = new List<TSource> ();
var dis = new CompositeDisposable ();
var disClosing = new CompositeDisposable ();
dis.Add (bufferOpenings.Subscribe (Observer.Create<TBufferOpening> (
s => {
var closing = bufferClosingSelector (s);
disClosing.Add (closing.Subscribe (c => {
sub.OnNext (l);
l = new List<TSource> ();
}));
}, () => disClosing.Dispose ())));
dis.Add (source.Subscribe (
s => l.Add (s), ex => sub.OnError (ex), () => {
if (l.Count > 0)
sub.OnNext (l);
sub.OnCompleted ();
}));
return dis;
// ----
}, DefaultColdScheduler);
}
public static IObservable<IList<TSource>> Buffer<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan,
int count)
{
return Buffer<TSource> (source, timeSpan, count, Scheduler.ThreadPool);
}
public static IObservable<IList<TSource>> Buffer<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan,
IScheduler scheduler)
{
return source.Buffer (timeSpan, int.MaxValue, scheduler);
}
public static IObservable<IList<TSource>> Buffer<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan,
TimeSpan timeShift)
{
return Buffer<TSource> (source, timeSpan, timeShift, Scheduler.ThreadPool);
}
public static IObservable<IList<TSource>> Buffer<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan,
int count,
IScheduler scheduler)
{
if (source == null)
throw new ArgumentNullException ("source");
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
return new ColdObservableEach<IList<TSource>> (sub => {
// ----
var counter = new Subject<Unit> ();
var l = new List<TSource> ();
var dis = new CompositeDisposable ();
var buffer = new TimeOrCountObservable (timeSpan, counter, count, scheduler);
dis.Add (buffer.Subscribe (
u => {
var n = l;
l = new List<TSource> ();
sub.OnNext (n);
},
ex => sub.OnError (ex),
() => {}));
dis.Add (source.Subscribe (
v => { l.Add (v); counter.OnNext (Unit.Default); },
ex => sub.OnError (ex),
() => { if (l.Count > 0) sub.OnNext (l); sub.OnCompleted (); }));
return dis;
// ----
}, scheduler);
}
struct ListTimeShiftContext<TSource>
{
public ListTimeShiftContext (DateTimeOffset start, List<TSource> list)
{
this.start = start;
this.list = list;
}
readonly DateTimeOffset start;
readonly List<TSource> list;
public DateTimeOffset Start {
get { return start; }
}
public List<TSource> List {
get { return list; }
}
}
public static IObservable<IList<TSource>> Buffer<TSource> (
this IObservable<TSource> source,
TimeSpan timeSpan,
TimeSpan timeShift,
IScheduler scheduler)
{
if (source == null)
throw new ArgumentNullException ("source");
if (scheduler == null)
throw new ArgumentNullException ("scheduler");
if (timeSpan < TimeSpan.Zero)
throw new ArgumentOutOfRangeException ("timeSpan");
if (timeShift < TimeSpan.Zero)
throw new ArgumentOutOfRangeException ("timeShift");
return new ColdObservableEach<IList<TSource>> (sub => {
// ----
var lists = new List<ListTimeShiftContext<TSource>> ();
Action cleanup = () => { foreach (var lc in lists) sub.OnNext (lc.List); };
DateTimeOffset nextStart = scheduler.Now;
var dis = source.Subscribe (Observer.Create<TSource> (v => {
if (nextStart <= scheduler.Now) {
var lc = new ListTimeShiftContext<TSource> (nextStart, new List<TSource> ());
lists.Add (lc);
nextStart += timeShift;
}
for (int x = 0; x < lists.Count; ) {
if (scheduler.Now - lists [x].Start >= timeSpan) {
sub.OnNext (lists [x].List);
lists.RemoveAt (x);
}
else
lists [x++].List.Add (v);
}
}, ex => { cleanup (); throw ex; }, () => { cleanup (); sub.OnCompleted (); }));
return dis;
// ----
}, DefaultColdScheduler);
}
}
}
| |
// *********************************
// Message from Original Author:
//
// 2008 Jose Menendez Poo
// Please give me credit if you use this code. It's all I ask.
// Contact me for more info: menendezpoo@gmail.com
// *********************************
//
// Original project from http://ribbon.codeplex.com/
// Continue to support and maintain by http://officeribbon.codeplex.com/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using System.Reflection;
using System.ComponentModel;
namespace System.Windows.Forms.RibbonHelpers
{
public class GlobalHook
: IDisposable
{
#region Subclasses
/// <summary>
/// Types of available hooks
/// </summary>
public enum HookTypes
{
/// <summary>
/// Installs a mouse hook
/// </summary>
Mouse,
/// <summary>
/// Installs a keyboard hook
/// </summary>
Keyboard
}
#endregion
#region Fields
private HookProcCallBack _HookProc;
private int _hHook;
private HookTypes _hookType;
#endregion
#region Events
/// <summary>
/// Occours when the hook captures a mouse click
/// </summary>
public event MouseEventHandler MouseClick;
/// <summary>
/// Occours when the hook captures a mouse double click
/// </summary>
public event MouseEventHandler MouseDoubleClick;
/// <summary>
/// Occours when the hook captures the mouse wheel
/// </summary>
public event MouseEventHandler MouseWheel;
/// <summary>
/// Occours when the hook captures the press of a mouse button
/// </summary>
public event MouseEventHandler MouseDown;
/// <summary>
/// Occours when the hook captures the release of a mouse button
/// </summary>
public event MouseEventHandler MouseUp;
/// <summary>
/// Occours when the hook captures the mouse moving over the screen
/// </summary>
public event MouseEventHandler MouseMove;
/// <summary>
/// Occours when a key is pressed
/// </summary>
public event KeyEventHandler KeyDown;
/// <summary>
/// Occours when a key is released
/// </summary>
public event KeyEventHandler KeyUp;
/// <summary>
/// Occours when a key is pressed
/// </summary>
public event KeyPressEventHandler KeyPress;
#endregion
#region Delegates
/// <summary>
/// Delegate used to recieve HookProc
/// </summary>
/// <param name="nCode"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
internal delegate int HookProcCallBack(int nCode, IntPtr wParam, IntPtr lParam);
#endregion
#region Ctor
/// <summary>
/// Creates a new Hook of the specified type
/// </summary>
/// <param name="hookType"></param>
public GlobalHook(HookTypes hookType)
{
_hookType = hookType;
InstallHook();
}
~GlobalHook()
{
if (Handle != 0)
{
Unhook();
}
}
#endregion
#region Properties
/// <summary>
/// Gets the type of this hook
/// </summary>
public HookTypes HookType
{
get { return _hookType; }
}
/// <summary>
/// Gets the handle of the hook
/// </summary>
public int Handle
{
get { return _hHook; }
}
#endregion
#region Event Triggers
/// <summary>
/// Raises the <see cref="MouseClick"/> event
/// </summary>
/// <param name="e"></param>
protected virtual void OnMouseClick(MouseEventArgs e)
{
if (MouseClick != null)
{
MouseClick(this, e);
}
}
/// <summary>
/// Raises the <see cref="MouseDoubleClick"/> event
/// </summary>
/// <param name="e"></param>
protected virtual void OnMouseDoubleClick(MouseEventArgs e)
{
if (MouseDoubleClick != null)
{
MouseDoubleClick(this, e);
}
}
/// <summary>
/// Raises the <see cref="MouseWheel"/> event
/// </summary>
/// <param name="e"></param>
protected virtual void OnMouseWheel(MouseEventArgs e)
{
if (MouseWheel != null)
{
MouseWheel(this, e);
}
}
/// <summary>
/// Raises the <see cref="MouseDown"/> event
/// </summary>
/// <param name="e"></param>
protected virtual void OnMouseDown(MouseEventArgs e)
{
if (MouseDown != null)
{
MouseDown(this, e);
}
}
/// <summary>
/// Raises the <see cref="MouseUp"/> event
/// </summary>
/// <param name="e"></param>
protected virtual void OnMouseUp(MouseEventArgs e)
{
if (MouseUp != null)
{
MouseUp(this, e);
}
}
/// <summary>
/// Raises the <see cref="MouseMove"/> event
/// </summary>
/// <param name="e"></param>
protected virtual void OnMouseMove(MouseEventArgs e)
{
if (MouseMove != null)
{
MouseMove(this, e);
}
}
/// <summary>
/// Raises the <see cref="KeyDown"/> event
/// </summary>
/// <param name="e">Event Data</param>
protected virtual void OnKeyDown(KeyEventArgs e)
{
if (KeyDown != null)
{
KeyDown(this, e);
}
}
/// <summary>
/// Raises the <see cref="KeyUp"/> event
/// </summary>
/// <param name="e">Event Data</param>
protected virtual void OnKeyUp(KeyEventArgs e)
{
if (KeyUp != null)
{
KeyUp(this, e);
}
}
/// <summary>
/// Raises the <see cref="KeyPress"/> event
/// </summary>
/// <param name="e">Event Data</param>
protected virtual void OnKeyPress(KeyPressEventArgs e)
{
if (KeyPress != null)
{
KeyPress(this, e);
}
}
#endregion
#region Methods
/// <summary>
/// Recieves the actual unsafe mouse hook procedure
/// </summary>
/// <param name="nCode"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
private int HookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0)
{
return WinApi.CallNextHookEx(Handle, code, wParam, lParam);
}
else
{
switch (HookType)
{
case HookTypes.Mouse:
return MouseProc(code, wParam, lParam);
case HookTypes.Keyboard:
return KeyboardProc(code, wParam, lParam);
default:
throw new Exception("HookType not supported");
}
}
}
/// <summary>
/// Recieves the actual unsafe keyboard hook procedure
/// </summary>
/// <param name="code"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
private int KeyboardProc(int code, IntPtr wParam, IntPtr lParam)
{
WinApi.KeyboardLLHookStruct hookStruct = (WinApi.KeyboardLLHookStruct)Marshal.PtrToStructure(lParam, typeof(WinApi.KeyboardLLHookStruct));
int msg = wParam.ToInt32();
bool handled = false;
if (msg == WinApi.WM_KEYDOWN || msg == WinApi.WM_SYSKEYDOWN)
{
KeyEventArgs e = new KeyEventArgs((Keys)hookStruct.vkCode);
OnKeyDown(e);
handled = e.Handled;
}
else if (msg == WinApi.WM_KEYUP || msg == WinApi.WM_SYSKEYUP)
{
KeyEventArgs e = new KeyEventArgs((Keys)hookStruct.vkCode);
OnKeyUp(e);
handled = e.Handled;
}
if (msg == WinApi.WM_KEYDOWN && KeyPress != null)
{
byte[] keyState = new byte[256];
byte[] buffer = new byte[2];
WinApi.GetKeyboardState(keyState);
int conversion = WinApi.ToAscii(hookStruct.vkCode, hookStruct.scanCode, keyState, buffer, hookStruct.flags);
if (conversion == 1 || conversion == 2)
{
bool shift = (WinApi.GetKeyState(WinApi.VK_SHIFT) & 0x80) == 0x80;
bool capital = WinApi.GetKeyState(WinApi.VK_CAPITAL) != 0;
char c = (char)buffer[0];
if ((shift ^ capital) && Char.IsLetter(c))
{
c = Char.ToUpper(c);
}
KeyPressEventArgs e = new KeyPressEventArgs(c);
OnKeyPress(e);
handled |= e.Handled;
}
}
return handled ? 1 : WinApi.CallNextHookEx(Handle, code, wParam, lParam);
}
/// <summary>
/// Processes Mouse Procedures
/// </summary>
/// <param name="code"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
private int MouseProc(int code, IntPtr wParam, IntPtr lParam)
{
WinApi.MouseLLHookStruct hookStruct = (WinApi.MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(WinApi.MouseLLHookStruct));
int msg = wParam.ToInt32();
int x = hookStruct.pt.x;
int y = hookStruct.pt.y;
int delta = (short)((hookStruct.mouseData >> 16) & 0xffff);
if (msg == WinApi.WM_MOUSEWHEEL)
{
OnMouseWheel(new MouseEventArgs(MouseButtons.None, 0, x, y, delta));
}
else if (msg == WinApi.WM_MOUSEMOVE)
{
OnMouseMove(new MouseEventArgs(MouseButtons.None, 0, x, y, delta));
}
else if (msg == WinApi.WM_LBUTTONDBLCLK)
{
OnMouseDoubleClick(new MouseEventArgs(MouseButtons.Left, 0, x, y, delta));
}
else if (msg == WinApi.WM_LBUTTONDOWN)
{
OnMouseDown(new MouseEventArgs(MouseButtons.Left, 0, x, y, delta));
}
else if (msg == WinApi.WM_LBUTTONUP)
{
OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, x, y, delta));
OnMouseClick(new MouseEventArgs(MouseButtons.Left, 0, x, y, delta));
}
else if (msg == WinApi.WM_MBUTTONDBLCLK)
{
OnMouseDoubleClick(new MouseEventArgs(MouseButtons.Middle, 0, x, y, delta));
}
else if (msg == WinApi.WM_MBUTTONDOWN)
{
OnMouseDown(new MouseEventArgs(MouseButtons.Middle, 0, x, y, delta));
}
else if (msg == WinApi.WM_MBUTTONUP)
{
OnMouseUp(new MouseEventArgs(MouseButtons.Middle, 0, x, y, delta));
}
else if (msg == WinApi.WM_RBUTTONDBLCLK)
{
OnMouseDoubleClick(new MouseEventArgs(MouseButtons.Right, 0, x, y, delta));
}
else if (msg == WinApi.WM_RBUTTONDOWN)
{
OnMouseDown(new MouseEventArgs(MouseButtons.Right, 0, x, y, delta));
}
else if (msg == WinApi.WM_RBUTTONUP)
{
OnMouseUp(new MouseEventArgs(MouseButtons.Right, 0, x, y, delta));
}
else if (msg == WinApi.WM_XBUTTONDBLCLK)
{
OnMouseDoubleClick(new MouseEventArgs(MouseButtons.XButton1, 0, x, y, delta));
}
else if (msg == WinApi.WM_XBUTTONDOWN)
{
OnMouseDown(new MouseEventArgs(MouseButtons.XButton1, 0, x, y, delta));
}
else if (msg == WinApi.WM_XBUTTONUP)
{
OnMouseUp(new MouseEventArgs(MouseButtons.XButton1, 0, x, y, delta));
}
return WinApi.CallNextHookEx(Handle, code, wParam, lParam);
}
/// <summary>
/// Installs the actual unsafe hook
/// </summary>
private void InstallHook()
{
/// Error check
if (Handle != 0) throw new Exception("Hook is already installed");
#region htype
int htype = 0;
switch (HookType)
{
case HookTypes.Mouse:
htype = WinApi.WH_MOUSE_LL;
break;
case HookTypes.Keyboard:
htype = WinApi.WH_KEYBOARD_LL;
break;
default:
throw new Exception("HookType is not supported");
}
#endregion
/// Delegate to recieve message
_HookProc = new HookProcCallBack(HookProc);
/// Hook
/// Ed Obeda suggestion for .net 4.0
//_hHook = WinApi.SetWindowsHookEx(htype, _HookProc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
_hHook = WinApi.SetWindowsHookEx(htype, _HookProc, System.Diagnostics.Process.GetCurrentProcess().MainModule.BaseAddress, 0);
/// Error check
if (Handle == 0) throw new Win32Exception(Marshal.GetLastWin32Error());
}
/// <summary>
/// Unhooks the hook
/// </summary>
private void Unhook()
{
if (Handle != 0)
{
//bool ret = WinApi.UnhookWindowsHookEx(Handle);
//if (ret == false)
// throw new Win32Exception(Marshal.GetLastWin32Error());
//_hHook = 0;
try
{
//Fix submitted by Simon Dallmair to handle win32 error when closing the form in vista
if (!WinApi.UnhookWindowsHookEx(Handle))
{
Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
if (ex.NativeErrorCode != 0)
throw ex;
}
_hHook = 0;
}
catch (Exception)
{
}
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (Handle != 0)
{
Unhook();
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.