context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using UnityEngine;
using System.Collections.Generic;
[AddComponentMenu("Strategy/Trade Route Creator")]
public class TradeRouteCreator : MonoBehaviour
{
[HideInInspector]
public static TradeRouteCreator Instance = null;
private GameObject mGO = null;
private TradeRoute mRoute = null;
private bool mIsValid = false;
private Vector3 mTargetPos;
private Town mTargetTown = null;
private ArrowProjector mProj = null;
private string mTooltip;
public Texture2D pathTexture = null;
/// <summary>
/// Gets a value indicating whether the <see cref="TradeRouteCreator"/> is active.
/// </summary>
public bool isActive { get { return mGO != null; } }
void OnEnable()
{
Instance = this;
mProj = gameObject.GetComponent<ArrowProjector>();
if (mProj == null) mProj = gameObject.AddComponent<ArrowProjector>();
}
void OnDisable()
{
if (Instance == this) Instance = null;
}
void Start()
{
Config.Instance.onGUI.Add(DrawGUI);
}
void DrawGUI()
{
if (StrategicCamera.viewpoint == null)
{
if (isActive)
{
if (mRoute.town0 == null)
{
UI.DrawTitle(new Rect(0f, 0f, Screen.width, 35f),
"Start by selecting the starting town.", Config.Instance.infoStyle);
}
else if (mRoute.town1 == null)
{
UI.DrawTitle(new Rect(0f, 0f, Screen.width, 35f),
"Draw a path by left-clicking. Right-click to undo.", Config.Instance.infoStyle);
}
if (mProj != null && !string.IsNullOrEmpty(mTooltip))
{
Vector2 pos = UI.GetScreenPos(mProj.transform.position);
UI.DrawTitle(new Rect(pos.x - 100f, pos.y - 17f, 200f, 35f),
mTooltip, Config.Instance.infoStyle);
}
}
}
}
/// <summary>
/// Starts a new trade route.
/// </summary>
public TradeRoute StartNewTradeRoute (Town town)
{
if (mGO == null)
{
mGO = new GameObject("Trade Route Creator");
mRoute = mGO.AddComponent<TradeRoute>();
mRoute.texture = pathTexture;
}
if (town != null)
{
mRoute.Connect(town);
}
return mRoute;
}
/// <summary>
/// Gets the town under the mouse cursor.
/// </summary>
Town GetTownUnderMouse()
{
RaycastHit hitInfo;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo, 300.0f))
{
return Town.Find(hitInfo.collider.gameObject);
}
return null;
}
/// <summary>
/// Gets the water surface target position under the mouse.
/// </summary>
Vector3 GetMouseTargetPos (Town town)
{
if (town == null) return Game.GetMouseWaterPosition();
Transform trans = town.transform.FindChild("Anchor");
return (trans != null) ? trans.position : town.transform.position;
}
/// <summary>
/// Determines whether the current route placement is valid.
/// </summary>
bool IsPlacementValid (Vector3 target)
{
mTooltip = string.Empty;
if (mRoute != null && mRoute.path.list.Count > 0)
{
Vector3 start = mRoute.path.list[mRoute.path.list.Count - 1].mVal;
RaycastHit hit;
Vector3 dir = target - start;
float dist = dir.magnitude;
if (dist < 5.0f)
{
mTooltip = "Too short!";
return false;
}
dir *= 1.0f / dist;
// Allow only up to 90 degree turns
if (mRoute.path.length > 1)
{
Vector3 prev = mRoute.path.list[mRoute.path.list.Count - 2].mVal;
Vector3 prevDir = (start - prev).normalized;
if (Vector3.Dot(dir, prevDir) < 0f)
{
mTooltip = "Tight turn!";
return false;
}
}
// Collide only with the terrain
if (Physics.SphereCast(start, 1f, dir, out hit, dist, 1 << 10))
{
mTooltip = "Too shallow!";
return false;
}
// Display some useful information
mTooltip = Mathf.RoundToInt(dist) + " miles";
}
return true;
}
/// <summary>
/// Update this instance.
/// </summary>
void Update()
{
// The camera should not respond to clicks while we are creating a trade route -- let us handle that
if (isActive)
{
StrategicCamera.onClick = OnClick;
// Update the target town and position
mTargetTown = GetTownUnderMouse();
mTargetPos = GetMouseTargetPos(mTargetTown);
// Validate the trade route segment
mIsValid = IsPlacementValid(mTargetPos);
}
// Reposition the projector
if (mProj != null)
{
if (isActive && mRoute != null && mRoute.path.list.Count > 0)
{
mProj.enabled = true;
mProj.originPos = mRoute.path.list[mRoute.path.list.Count - 1].mVal;
mProj.targetPos = mTargetPos;
mProj.color = mIsValid ? Color.white : Color.red;
}
else mProj.enabled = false;
}
}
/// <summary>
/// Callback triggered when the player clicks on something.
/// </summary>
void OnClick (int button)
{
if (button == 0)
{
if (mIsValid)
{
if (mTargetTown != null)
{
if (mRoute.Connect(mTargetTown))
{
// See if there is a duplicate route
foreach (TradeRoute tr in TradeRoute.list)
{
if (tr != mRoute && tr.GetConnectedTown(mRoute.town0) == mRoute.town1)
{
// Copy the trade path
tr.CopyPath(mRoute.path);
// Ensure that no towns are still referencing this trade route
foreach (Town t in Town.list) t.DisconnectTradeRoute(tr);
Object.Destroy(mGO);
break;
}
}
// This route has now been created
mIsValid = false;
mTargetTown = null;
mRoute = null;
mGO = null;
}
}
else
{
mRoute.Add(mTargetPos);
}
}
}
else if (!mRoute.UndoAdd())
{
foreach (Town t in Town.list) t.DisconnectTradeRoute(mRoute);
Object.Destroy(mGO);
mIsValid = false;
mTargetTown = null;
mRoute = null;
mGO = null;
}
}
}
| |
// $Id: mxGeometry.cs,v 1.20 2010-04-30 12:58:23 gaudenz Exp $
// Copyright (c) 2007-2008, Gaudenz Alder
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace com.mxgraph
{
/// <summary>
/// Represents the geometry of a cell. For vertices, the geometry consists
/// of the x- and y-location, as well as the width and height. For edges,
/// the edge either defines the source- and target-terminal, or the geometry
/// defines the respective terminal points.
/// </summary>
public class mxGeometry : mxRectangle
{
/// <summary>
/// Global switch to translate the points in translate. Default is true.
/// </summary>
public static bool TRANSLATE_CONTROL_POINTS = true;
/// <summary>
/// Stores alternate values for x, y, width and height in a rectangle.
/// Default is null.
/// </summary>
protected mxRectangle alternateBounds;
/// <summary>
/// Defines the source-point of the edge. This is used if the
/// corresponding edge does not have a source vertex. Otherwise it is
/// ignored. Default is null.
/// </summary>
protected mxPoint sourcePoint;
/// <summary>
/// Defines the target-point of the edge. This is used if the
/// corresponding edge does not have a source vertex. Otherwise it is
/// ignored. Default is null.
/// </summary>
protected mxPoint targetPoint;
/// <summary>
/// Holds the offset of the label for edges. This is the absolute vector
/// between the center of the edge and the top, left point of the label.
/// Default is null.
/// </summary>
protected mxPoint offset;
/// <summary>
/// List of mxPoints which specifies the control points along the edge.
/// These points are the intermediate points on the edge, for the endpoints
/// use targetPoint and sourcePoint or set the terminals of the edge to
/// a non-null value. Default is null.
/// </summary>
protected List<mxPoint> points;
/// <summary>
/// Specifies if the coordinates in the geometry are to be interpreted as
/// relative coordinates. Default is false. This is used to mark a geometry
/// with an x- and y-coordinate that is used to describe an edge label
/// position.
/// </summary>
protected bool relative = false;
/// <summary>
/// Constructs a new geometry at (0, 0) with the width and height set to 0.
/// </summary>
public mxGeometry() : this(0, 0, 0, 0) { }
/// <summary>
/// Constructs a geometry using the given parameters.
/// </summary>
/// <param name="x">X-coordinate of the new geometry.</param>
/// <param name="y">Y-coordinate of the new geometry.</param>
/// <param name="width">Width of the new geometry.</param>
/// <param name="height">Height of the new geometry.</param>
public mxGeometry(double x, double y, double width, double height) : base(x, y, width, height) { }
/// <summary>
/// Constructs a copy of the given geometry.
/// </summary>
/// <param name="geometry">Geometry to construct a copy of.</param>
public mxGeometry(mxGeometry geometry)
: base(geometry.X, geometry.Y, geometry.Width, geometry
.Height)
{
if (geometry.points != null)
{
points = new List<mxPoint>(geometry.points.Count);
foreach (mxPoint pt in geometry.points)
{
points.Add(pt.Clone());
}
}
if (geometry.sourcePoint != null)
{
sourcePoint = geometry.sourcePoint.Clone();
}
if (geometry.targetPoint != null)
{
targetPoint = geometry.targetPoint.Clone();
}
if (geometry.offset != null)
{
offset = geometry.offset.Clone();
}
if (geometry.alternateBounds != null)
{
alternateBounds = geometry.alternateBounds.Clone();
}
relative = geometry.relative;
}
/// <summary>
/// Sets or returns the alternate bounds.
/// </summary>
public mxRectangle AlternateBounds
{
get { return alternateBounds; }
set { alternateBounds = value; }
}
/// <summary>
/// Sets or returns the source point.
/// </summary>
public mxPoint SourcePoint
{
get { return sourcePoint; }
set { sourcePoint = value; }
}
/// <summary>
/// Sets or returns the target point.
/// </summary>
public mxPoint TargetPoint
{
get { return targetPoint; }
set { targetPoint = value; }
}
/// <summary>
/// Sets or returns the list of control points.
/// </summary>
public List<mxPoint> Points
{
get { return points; }
set { points = value; }
}
/// <summary>
/// Sets or returns the offset.
/// </summary>
public mxPoint Offset
{
get { return offset; }
set { offset = value; }
}
/// <summary>
/// Sets or returns if the geometry is relative.
/// </summary>
public bool Relative
{
get { return relative; }
set { relative = value; }
}
/// <summary>
/// Returns the point representing the source or target point of this edge.
/// This is only used if the edge has no source or target vertex.
/// </summary>
/// <param name="source">Boolean that specifies if the source or target point
/// should be returned.</param>
/// <returns>Returns the source or target point.</returns>
public mxPoint GetTerminalPoint(bool source)
{
return (source) ? sourcePoint : targetPoint;
}
/// <summary>
/// Sets the sourcePoint or targetPoint to the given point and returns the
/// new point.
/// </summary>
/// <param name="point">Point to be used as the new source or target point.</param>
/// <param name="source">Boolean that specifies if the source or target point
/// should be set.</param>
/// <returns>Returns the new point.</returns>
public mxPoint SetTerminalPoint(mxPoint point, bool source)
{
if (source)
{
sourcePoint = point;
}
else
{
targetPoint = point;
}
return point;
}
/// <summary>
/// Translates the geometry by the specified amount. That is, x and y of the
/// geometry, the sourcePoint, targetPoint and all elements of points are
/// translated by the given amount. X and y are only translated if the
/// geometry is not relative. If TRANSLATE_CONTROL_POINTS is false, then
/// are not modified by this function.
/// </summary>
/// <param name="dx">Integer that specifies the x-coordinate of the translation.</param>
/// <param name="dy">Integer that specifies the y-coordinate of the translation.</param>
public void Translate(double dx, double dy)
{
// Translates the geometry
if (!Relative)
{
x += dx;
y += dy;
}
// Translates the source point
if (sourcePoint != null)
{
sourcePoint.X += dx;
sourcePoint.Y += dy;
}
// Translates the target point
if (targetPoint != null)
{
targetPoint.X += dx;
targetPoint.Y += dy;
}
// Translate the control points
if (TRANSLATE_CONTROL_POINTS &&
points != null)
{
int count = points.Count;
for (int i = 0; i < count; i++)
{
mxPoint pt = points[i];
pt.X += dx;
pt.Y += dy;
}
}
}
/// <summary>
/// Returns a new instance of the same geometry.
/// </summary>
/// <returns>Returns a clone of the geometry.</returns>
public new mxGeometry Clone()
{
return new mxGeometry(this);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
/// <summary>
/// Tests that apply to the filesystem/cache portions of the X509 infrastructure on Unix implementations.
/// </summary>
[Collection("X509Filesystem")]
public static class X509FilesystemTests
{
// #9293: Our Fedora23 CI machines use NTFS for "tmphome", which causes our filesystem permissions checks to fail.
private static bool IsReliableInCI { get; } = !PlatformDetection.IsFedora23;
[Fact]
[OuterLoop]
public static void VerifyCrlCache()
{
string crlDirectory = PersistedFiles.GetUserFeatureDirectory("cryptography", "crls");
string crlFile = Path.Combine(crlDirectory,MicrosoftDotComRootCrlFilename);
Directory.CreateDirectory(crlDirectory);
File.Delete(crlFile);
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
// The very start of the CRL period.
chain.ChainPolicy.VerificationTime = new DateTime(2015, 6, 17, 0, 0, 0, DateTimeKind.Utc);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EndCertificateOnly;
chain.ChainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;
bool valid = chain.Build(microsoftDotComIssuer);
Assert.True(valid, "Precondition: Chain builds with no revocation checks");
int initialErrorCount = chain.ChainStatus.Length;
Assert.InRange(initialErrorCount, 0, 1);
if (initialErrorCount > 0)
{
Assert.Equal(X509ChainStatusFlags.UntrustedRoot, chain.ChainStatus[0].Status);
}
chainHolder.DisposeChainElements();
chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
valid = chain.Build(microsoftDotComIssuer);
Assert.False(valid, "Chain should not build validly");
Assert.Equal(initialErrorCount + 1, chain.ChainStatus.Length);
Assert.Equal(X509ChainStatusFlags.RevocationStatusUnknown, chain.ChainStatus[0].Status);
File.WriteAllText(crlFile, MicrosoftDotComRootCrlPem, Encoding.ASCII);
chainHolder.DisposeChainElements();
valid = chain.Build(microsoftDotComIssuer);
Assert.True(valid, "Chain should build validly now");
Assert.Equal(initialErrorCount, chain.ChainStatus.Length);
}
}
[Fact]
public static void X509Store_OpenExisting_Fails()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
// Since the directory was explicitly deleted already, this should fail.
Assert.Throws<CryptographicException>(
() => store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly));
});
}
[Fact]
private static void X509Store_AddReadOnly()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
}
});
}
[Fact]
private static void X509Store_AddClosed()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
// Adding a certificate when the store is closed should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddOne()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(1, storeCerts.Count);
using (X509Certificate2 storeCert = storeCerts[0])
{
Assert.Equal(cert, storeCert);
Assert.NotSame(cert, storeCert);
}
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddOneAfterUpgrade()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
// Calling Open on an open store changes the access rights:
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(1, storeCerts.Count);
using (X509Certificate2 storeCert = storeCerts[0])
{
Assert.Equal(cert, storeCert);
Assert.NotSame(cert, storeCert);
}
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_DowngradePermissions()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
// Ensure that ReadWrite took effect.
store.Add(certA);
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(certB));
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddAfterDispose()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
// Dispose returns the store to the pre-opened state.
store.Dispose();
// Adding a certificate when the store is closed should fail:
Assert.Throws<CryptographicException>(() => store.Add(certB));
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddAndClear()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
store.Remove(cert);
// The directory should still exist.
Assert.True(Directory.Exists(storeDirectory), "Store Directory Still Exists");
Assert.Equal(0, Directory.GetFiles(storeDirectory).Length);
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddDuplicate()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
using (var certClone = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
store.Add(certClone);
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(2, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certA, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo_UpgradePrivateKey()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certAPrivate = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var certAPublic = new X509Certificate2(certAPrivate.RawData))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certAPublic);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
string[] storeFiles = Directory.GetFiles(storeDirectory);
Assert.Equal(2, storeFiles.Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certAPublic, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (before)");
storeCert.Dispose();
}
store.Add(certAPrivate);
// It replaces the existing file, the names should be unaffected.
Assert.Equal(storeFiles, Directory.GetFiles(storeDirectory));
storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
bool foundCertA = false;
foreach (X509Certificate2 storeCert in storeCerts)
{
// The public instance and private instance are .Equal
if (storeCert.Equals(certAPublic))
{
Assert.True(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (affected cert)");
foundCertA = true;
}
else
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (other cert)");
}
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
Assert.True(foundCertA, "foundCertA");
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo_UpgradePrivateKey_NoDowngrade()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certAPrivate = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var certAPublic = new X509Certificate2(certAPrivate.RawData))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certAPublic);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certAPublic, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (before)");
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
// Add the private (checked in X509Store_AddTwo_UpgradePrivateKey)
store.Add(certAPrivate);
// Then add the public again, which shouldn't do anything.
store.Add(certAPublic);
storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
bool foundCertA = false;
foreach (X509Certificate2 storeCert in storeCerts)
{
if (storeCert.Equals(certAPublic))
{
Assert.True(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (affected cert)");
foundCertA = true;
}
else
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (other cert)");
}
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
Assert.True(foundCertA, "foundCertA");
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_DistinctCollections()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(2, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCertsA = store.Certificates;
X509Certificate2Collection storeCertsB = store.Certificates;
Assert.NotSame(storeCertsA, storeCertsB);
Assert.Equal(storeCertsA.Count, storeCertsB.Count);
foreach (X509Certificate2 collACert in storeCertsA)
{
int bIndex = storeCertsB.IndexOf(collACert);
Assert.InRange(bIndex, 0, storeCertsB.Count);
X509Certificate2 collBCert = storeCertsB[bIndex];
// Equal is implied by IndexOf working.
Assert.NotSame(collACert, collBCert);
storeCertsB.RemoveAt(bIndex);
collACert.Dispose();
collBCert.Dispose();
}
}
});
}
[ConditionalFact(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_Add4_Remove1()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
using (var certBClone = new X509Certificate2(certB.RawData))
using (var certC = new X509Certificate2(TestData.ECDsa256Certificate))
using (var certD = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
store.Add(certC);
store.Add(certD);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(4, Directory.GetFiles(storeDirectory).Length);
X509Certificate2[] expectedCerts = { certA, certB, certC, certD };
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(4, storeCerts.Count);
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
store.Remove(certBClone);
Assert.Equal(3, Directory.GetFiles(storeDirectory).Length);
expectedCerts = new[] { certA, certC, certD };
storeCerts = store.Certificates;
Assert.Equal(3, storeCerts.Count);
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
}
});
}
[ConditionalTheory(nameof(IsReliableInCI))]
[OuterLoop(/* Alters user/machine state */)]
[InlineData(false)]
[InlineData(true)]
private static void X509Store_MultipleObjects(bool matchCase)
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
using (var certC = new X509Certificate2(TestData.ECDsa256Certificate))
using (var certD = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
string newName = store.Name;
if (!matchCase)
{
newName = newName.ToUpperInvariant();
Assert.NotEqual(store.Name, newName);
}
using (X509Store storeClone = new X509Store(newName, store.Location))
{
storeClone.Open(OpenFlags.ReadWrite);
AssertEqualContents(store, storeClone);
store.Add(certC);
// The object was added to store, but should show up in both objects
// after re-reading the Certificates property
AssertEqualContents(store, storeClone);
// Now add one to storeClone to prove bidirectionality.
storeClone.Add(certD);
AssertEqualContents(store, storeClone);
}
}
});
}
private static void AssertEqualContents(X509Store storeA, X509Store storeB)
{
Assert.NotSame(storeA, storeB);
using (var storeATracker = new ImportedCollection(storeA.Certificates))
using (var storeBTracker = new ImportedCollection(storeB.Certificates))
{
X509Certificate2Collection storeACerts = storeATracker.Collection;
X509Certificate2Collection storeBCerts = storeBTracker.Collection;
Assert.Equal(storeACerts.OfType<X509Certificate2>(), storeBCerts.OfType<X509Certificate2>());
}
}
private static void RunX509StoreTest(Action<X509Store, string> testAction)
{
string certStoresFeaturePath = PersistedFiles.GetUserFeatureDirectory("cryptography", "x509stores");
string storeName = "TestStore" + Guid.NewGuid().ToString("N");
string storeDirectory = Path.Combine(certStoresFeaturePath, storeName.ToLowerInvariant());
if (Directory.Exists(storeDirectory))
{
Directory.Delete(storeDirectory, true);
}
try
{
using (X509Store store = new X509Store(storeName, StoreLocation.CurrentUser))
{
testAction(store, storeDirectory);
}
}
finally
{
try
{
if (Directory.Exists(storeDirectory))
{
Directory.Delete(storeDirectory, true);
}
}
catch
{
// Don't allow any (additional?) I/O errors to propagate.
}
}
}
// `openssl crl -in [MicrosoftDotComRootCrlPem] -noout -hash`.crl
private const string MicrosoftDotComRootCrlFilename = "b204d74a.crl";
// This CRL was downloaded 2015-08-31 20:31 PDT
// It is valid from Jun 17 00:00:00 2015 GMT to Sep 30 23:59:59 2015 GMT
private const string MicrosoftDotComRootCrlPem =
@"-----BEGIN X509 CRL-----
MIICETCB+jANBgkqhkiG9w0BAQUFADCByjELMAkGA1UEBhMCVVMxFzAVBgNVBAoT
DlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3Jr
MTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3Jp
emVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQ
cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUXDTE1MDYxNzAwMDAw
MFoXDTE1MDkzMDIzNTk1OVowDQYJKoZIhvcNAQEFBQADggEBAFxqobObEqKNSAe+
A9cHCYI7sw+Vc8HuE7E+VZc6ni3a2UHiprYuXDsvD18+cyv/nFSLpLqLmExZrsf/
dzH8GH2HgBTt5aO/nX08EBrDgcjHo9b0VI6ZuOOaEeS0NsRh28Jupfn1Xwcsbdw9
nVh1OaExpHwxgg7pJr4pXzaAjbl3b4QfCPyTd5aaOQOEmqvJtRrMwCna4qQ3p4r6
QYe19/pXqK9my7lSmH1vZ0CmNvQeNPmnx+YmFXYTBgap+Xi2cs6GX/qI04CDzjWi
sm6L0+S1Zx2wMhiYOi0JvrRizf+rIyKkDbPMoYEyXZqcCwSnv6mJQY81vmKRKU5N
WKo2mLw=
-----END X509 CRL-----";
}
}
| |
// <copyright file="ModifiedBessel.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2012 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <contribution>
// CERN - European Laboratory for Particle Physics
// http://www.docjar.com/html/api/cern/jet/math/Bessel.java.html
// Copyright 1999 CERN - European Laboratory for Particle Physics.
// Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose
// is hereby granted without fee, provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear in supporting documentation.
// CERN makes no representations about the suitability of this software for any purpose.
// It is provided "as is" without expressed or implied warranty.
// TOMS757 - Uncommon Special Functions (Fortran77) by Allan McLeod
// http://people.sc.fsu.edu/~jburkardt/f77_src/toms757/toms757.html
// Wei Wu
// Cephes Math Library, Stephen L. Moshier
// ALGLIB 2.0.1, Sergey Bochkanov
// </contribution>
// ReSharper disable CheckNamespace
namespace MathNet.Numerics
// ReSharper restore CheckNamespace
{
using System;
/// <summary>
/// This partial implementation of the SpecialFunctions class contains all methods related to the modified bessel function.
/// </summary>
public static partial class SpecialFunctions
{
/// <summary>
/// **************************************
/// COEFFICIENTS FOR METHODS bessi0 *
/// **************************************
/// </summary>
/// <summary> Chebyshev coefficients for exp(-x) I0(x)
/// in the interval [0, 8].
///
/// lim(x->0){ exp(-x) I0(x) } = 1.
/// </summary>
private static readonly double[] BesselI0A = { -4.41534164647933937950e-18, 3.33079451882223809783e-17, -2.43127984654795469359e-16, 1.71539128555513303061e-15, -1.16853328779934516808e-14, 7.67618549860493561688e-14, -4.85644678311192946090e-13, 2.95505266312963983461e-12, -1.72682629144155570723e-11, 9.67580903537323691224e-11, -5.18979560163526290666e-10, 2.65982372468238665035e-9, -1.30002500998624804212e-8, 6.04699502254191894932e-8, -2.67079385394061173391e-7, 1.11738753912010371815e-6, -4.41673835845875056359e-6, 1.64484480707288970893e-5, -5.75419501008210370398e-5, 1.88502885095841655729e-4, -5.76375574538582365885e-4, 1.63947561694133579842e-3, -4.32430999505057594430e-3, 1.05464603945949983183e-2, -2.37374148058994688156e-2, 4.93052842396707084878e-2, -9.49010970480476444210e-2, 1.71620901522208775349e-1, -3.04682672343198398683e-1, 6.76795274409476084995e-1 };
/// <summary> Chebyshev coefficients for exp(-x) sqrt(x) I0(x)
/// in the inverted interval [8, infinity].
///
/// lim(x->inf){ exp(-x) sqrt(x) I0(x) } = 1/sqrt(2pi).
/// </summary>
private static readonly double[] BesselI0B = { -7.23318048787475395456e-18, -4.83050448594418207126e-18, 4.46562142029675999901e-17, 3.46122286769746109310e-17, -2.82762398051658348494e-16, -3.42548561967721913462e-16, 1.77256013305652638360e-15, 3.81168066935262242075e-15, -9.55484669882830764870e-15, -4.15056934728722208663e-14, 1.54008621752140982691e-14, 3.85277838274214270114e-13, 7.18012445138366623367e-13, -1.79417853150680611778e-12, -1.32158118404477131188e-11, -3.14991652796324136454e-11, 1.18891471078464383424e-11, 4.94060238822496958910e-10, 3.39623202570838634515e-9, 2.26666899049817806459e-8, 2.04891858946906374183e-7, 2.89137052083475648297e-6, 6.88975834691682398426e-5, 3.36911647825569408990e-3, 8.04490411014108831608e-1 };
/// <summary>
/// **************************************
/// COEFFICIENTS FOR METHODS bessi1 *
/// **************************************
/// </summary>
/// <summary> Chebyshev coefficients for exp(-x) I1(x) / x
/// in the interval [0, 8].
///
/// lim(x->0){ exp(-x) I1(x) / x } = 1/2.
/// </summary>
private static readonly double[] BesselI1A = { 2.77791411276104639959e-18, -2.11142121435816608115e-17, 1.55363195773620046921e-16, -1.10559694773538630805e-15, 7.60068429473540693410e-15, -5.04218550472791168711e-14, 3.22379336594557470981e-13, -1.98397439776494371520e-12, 1.17361862988909016308e-11, -6.66348972350202774223e-11, 3.62559028155211703701e-10, -1.88724975172282928790e-9, 9.38153738649577178388e-9, -4.44505912879632808065e-8, 2.00329475355213526229e-7, -8.56872026469545474066e-7, 3.47025130813767847674e-6, -1.32731636560394358279e-5, 4.78156510755005422638e-5, -1.61760815825896745588e-4, 5.12285956168575772895e-4, -1.51357245063125314899e-3, 4.15642294431288815669e-3, -1.05640848946261981558e-2, 2.47264490306265168283e-2, -5.29459812080949914269e-2, 1.02643658689847095384e-1, -1.76416518357834055153e-1, 2.52587186443633654823e-1 };
/// <summary> Chebyshev coefficients for exp(-x) sqrt(x) I1(x)
/// in the inverted interval [8, infinity].
///
/// lim(x->inf){ exp(-x) sqrt(x) I1(x) } = 1/sqrt(2pi).
/// </summary>
private static readonly double[] BesselI1B = { 7.51729631084210481353e-18, 4.41434832307170791151e-18, -4.65030536848935832153e-17, -3.20952592199342395980e-17, 2.96262899764595013876e-16, 3.30820231092092828324e-16, -1.88035477551078244854e-15, -3.81440307243700780478e-15, 1.04202769841288027642e-14, 4.27244001671195135429e-14, -2.10154184277266431302e-14, -4.08355111109219731823e-13, -7.19855177624590851209e-13, 2.03562854414708950722e-12, 1.41258074366137813316e-11, 3.25260358301548823856e-11, -1.89749581235054123450e-11, -5.58974346219658380687e-10, -3.83538038596423702205e-9, -2.63146884688951950684e-8, -2.51223623787020892529e-7, -3.88256480887769039346e-6, -1.10588938762623716291e-4, -9.76109749136146840777e-3, 7.78576235018280120474e-1 };
/// <summary>
/// **************************************
/// COEFFICIENTS FOR METHODS bessk0, bessk0e *
/// **************************************
/// </summary>
/// <summary> Chebyshev coefficients for K0(x) + log(x/2) I0(x)
/// in the interval [0, 2]. The odd order coefficients are all
/// zero; only the even order coefficients are listed.
///
/// lim(x->0){ K0(x) + log(x/2) I0(x) } = -EUL.
/// </summary>
private static readonly double[] BesselK0A = { 1.37446543561352307156e-16, 4.25981614279661018399e-14, 1.03496952576338420167e-11, 1.90451637722020886025e-9, 2.53479107902614945675e-7, 2.28621210311945178607e-5, 1.26461541144692592338e-3, 3.59799365153615016266e-2, 3.44289899924628486886e-1, -5.35327393233902768720e-1 };
/// <summary> Chebyshev coefficients for exp(x) sqrt(x) K0(x)
/// in the inverted interval [2, infinity].
///
/// lim(x->inf){ exp(x) sqrt(x) K0(x) } = sqrt(pi/2).
/// </summary>
private static readonly double[] BesselK0B = { 5.30043377268626276149e-18, -1.64758043015242134646e-17, 5.21039150503902756861e-17, -1.67823109680541210385e-16, 5.51205597852431940784e-16, -1.84859337734377901440e-15, 6.34007647740507060557e-15, -2.22751332699166985548e-14, 8.03289077536357521100e-14, -2.98009692317273043925e-13, 1.14034058820847496303e-12, -4.51459788337394416547e-12, 1.85594911495471785253e-11, -7.95748924447710747776e-11, 3.57739728140030116597e-10, -1.69753450938905987466e-9, 8.57403401741422608519e-9, -4.66048989768794782956e-8, 2.76681363944501510342e-7, -1.83175552271911948767e-6, 1.39498137188764993662e-5, -1.28495495816278026384e-4, 1.56988388573005337491e-3, -3.14481013119645005427e-2, 2.44030308206595545468e0 };
/// <summary>
/// **************************************
/// COEFFICIENTS FOR METHODS bessk1, bessk1e *
/// **************************************
/// </summary>
/// <summary> Chebyshev coefficients for x(K1(x) - log(x/2) I1(x))
/// in the interval [0, 2].
///
/// lim(x->0){ x(K1(x) - log(x/2) I1(x)) } = 1.
/// </summary>
private static readonly double[] BesselK1A = { -7.02386347938628759343e-18, -2.42744985051936593393e-15, -6.66690169419932900609e-13, -1.41148839263352776110e-10, -2.21338763073472585583e-8, -2.43340614156596823496e-6, -1.73028895751305206302e-4, -6.97572385963986435018e-3, -1.22611180822657148235e-1, -3.53155960776544875667e-1, 1.52530022733894777053e0 };
/// <summary> Chebyshev coefficients for exp(x) sqrt(x) K1(x)
/// in the interval [2, infinity].
///
/// lim(x->inf){ exp(x) sqrt(x) K1(x) } = sqrt(pi/2).
/// </summary>
private static readonly double[] BesselK1B = { -5.75674448366501715755e-18, 1.79405087314755922667e-17, -5.68946255844285935196e-17, 1.83809354436663880070e-16, -6.05704724837331885336e-16, 2.03870316562433424052e-15, -7.01983709041831346144e-15, 2.47715442448130437068e-14, -8.97670518232499435011e-14, 3.34841966607842919884e-13, -1.28917396095102890680e-12, 5.13963967348173025100e-12, -2.12996783842756842877e-11, 9.21831518760500529508e-11, -4.19035475934189648750e-10, 2.01504975519703286596e-9, -1.03457624656780970260e-8, 5.74108412545004946722e-8, -3.50196060308781257119e-7, 2.40648494783721712015e-6, -1.93619797416608296024e-5, 1.95215518471351631108e-4, -2.85781685962277938680e-3, 1.03923736576817238437e-1, 2.72062619048444266945e0 };
/// <summary>Returns the modified Bessel function of first kind, order 0 of the argument.
/// <p/>
/// The function is defined as <tt>i0(x) = j0( ix )</tt>.
/// <p/>
/// The range is partitioned into the two intervals [0, 8] and
/// (8, infinity). Chebyshev polynomial expansions are employed
/// in each interval.
/// </summary>
/// <param name="x">The value to compute the bessel function of.
/// </param>
public static double BesselI0(double x)
{
if (x < 0)
{
x = -x;
}
if (x <= 8.0)
{
double y = (x / 2.0) - 2.0;
return Math.Exp(x) * Evaluate.ChebyshevA(BesselI0A, y);
}
double x1 = 32.0 / x - 2.0;
return Math.Exp(x) * Evaluate.ChebyshevA(BesselI0B, x1) / Math.Sqrt(x);
}
/// <summary>Returns the modified Bessel function of first kind,
/// order 1 of the argument.
/// <p/>
/// The function is defined as <tt>i1(x) = -i j1( ix )</tt>.
/// <p/>
/// The range is partitioned into the two intervals [0, 8] and
/// (8, infinity). Chebyshev polynomial expansions are employed
/// in each interval.
/// </summary>
/// <param name="x">The value to compute the bessel function of.
/// </param>
public static double BesselI1(double x)
{
double z = Math.Abs(x);
if (z <= 8.0)
{
double y = (z / 2.0) - 2.0;
z = Evaluate.ChebyshevA(BesselI1A, y) * z * Math.Exp(z);
}
else
{
double x1 = 32.0 / z - 2.0;
z = Math.Exp(z) * Evaluate.ChebyshevA(BesselI1B, x1) / Math.Sqrt(z);
}
if (x < 0.0)
{
z = -z;
}
return z;
}
/// <summary> Returns the modified Bessel function of the second kind
/// of order 0 of the argument.
/// <p/>
/// The range is partitioned into the two intervals [0, 8] and
/// (8, infinity). Chebyshev polynomial expansions are employed
/// in each interval.
/// </summary>
/// <param name="x">The value to compute the bessel function of.
/// </param>
public static double BesselK0(double x)
{
if (x <= 0.0)
{
throw new ArithmeticException();
}
if (x <= 2.0)
{
double y = x * x - 2.0;
return Evaluate.ChebyshevA(BesselK0A, y) - Math.Log(0.5 * x) * BesselI0(x);
}
double z = 8.0 / x - 2.0;
return Math.Exp(-x) * Evaluate.ChebyshevA(BesselK0B, z) / Math.Sqrt(x);
}
/// <summary>Returns the exponentially scaled modified Bessel function
/// of the second kind of order 0 of the argument.
/// </summary>
/// <param name="x">The value to compute the bessel function of.
/// </param>
public static double BesselK0e(double x)
{
if (x <= 0.0)
{
throw new ArithmeticException();
}
if (x <= 2.0)
{
double y = x * x - 2.0;
return Evaluate.ChebyshevA(BesselK0A, y) - Math.Log(0.5 * x) * BesselI0(x) * Math.Exp(x);
}
double x1 = 8.0 / x - 2.0;
return Evaluate.ChebyshevA(BesselK0B, x1) / Math.Sqrt(x);
}
/// <summary> Returns the modified Bessel function of the second kind
/// of order 1 of the argument.
/// <p/>
/// The range is partitioned into the two intervals [0, 2] and
/// (2, infinity). Chebyshev polynomial expansions are employed
/// in each interval.
/// </summary>
/// <param name="x">The value to compute the bessel function of.
/// </param>
public static double BesselK1(double x)
{
double z = 0.5 * x;
if (z <= 0.0)
{
throw new ArithmeticException();
}
if (x <= 2.0)
{
double y = x * x - 2.0;
return Math.Log(z) * BesselI1(x) + Evaluate.ChebyshevA(BesselK1A, y) / x;
}
double x1 = 8.0 / x - 2.0;
return Math.Exp(-x) * Evaluate.ChebyshevA(BesselK1B, x1) / Math.Sqrt(x);
}
/// <summary> Returns the exponentially scaled modified Bessel function
/// of the second kind of order 1 of the argument.
/// <p/>
/// <tt>k1e(x) = exp(x) * k1(x)</tt>.
/// </summary>
/// <param name="x">The value to compute the bessel function of.
/// </param>
public static double BesselK1e(double x)
{
if (x <= 0.0)
{
throw new ArithmeticException();
}
if (x <= 2.0)
{
double y = x * x - 2.0;
return Math.Log(0.5 * x) * BesselI1(x) + Evaluate.ChebyshevA(BesselK1A, y) / x * Math.Exp(x);
}
double x1 = 8.0 / x - 2.0;
return Evaluate.ChebyshevA(BesselK1B, x1) / Math.Sqrt(x);
}
}
}
| |
//
// https://github.com/NServiceKit/NServiceKit.Text
// NServiceKit.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using NServiceKit.Text.Common;
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace NServiceKit.Text.Json
{
/// <summary>A JSON type serializer.</summary>
internal class JsonTypeSerializer
: ITypeSerializer
{
/// <summary>The instance.</summary>
public static ITypeSerializer Instance = new JsonTypeSerializer();
/// <summary>Gets a value indicating whether the null values should be included.</summary>
/// <value>true if include null values, false if not.</value>
public bool IncludeNullValues
{
get { return JsConfig.IncludeNullValues; }
}
/// <summary>Gets the type attribute in object.</summary>
/// <value>The type attribute in object.</value>
public string TypeAttrInObject
{
get { return JsConfig.JsonTypeAttrInObject; }
}
/// <summary>Gets type attribute in object.</summary>
/// <param name="typeAttr">The type attribute.</param>
/// <returns>The type attribute in object.</returns>
internal static string GetTypeAttrInObject(string typeAttr)
{
return string.Format("{{\"{0}\":", typeAttr);
}
/// <summary>The white space flags.</summary>
public static readonly bool[] WhiteSpaceFlags = new bool[' ' + 1];
/// <summary>
/// Initializes static members of the NServiceKit.Text.Json.JsonTypeSerializer class.
/// </summary>
static JsonTypeSerializer()
{
WhiteSpaceFlags[' '] = true;
WhiteSpaceFlags['\t'] = true;
WhiteSpaceFlags['\r'] = true;
WhiteSpaceFlags['\n'] = true;
}
/// <summary>Gets write function.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <returns>The write function.</returns>
public WriteObjectDelegate GetWriteFn<T>()
{
return JsonWriter<T>.WriteFn();
}
/// <summary>Gets write function.</summary>
/// <param name="type">The type.</param>
/// <returns>The write function.</returns>
public WriteObjectDelegate GetWriteFn(Type type)
{
return JsonWriter.GetWriteFn(type);
}
/// <summary>Gets type information.</summary>
/// <param name="type">The type.</param>
/// <returns>The type information.</returns>
public TypeInfo GetTypeInfo(Type type)
{
return JsonWriter.GetTypeInfo(type);
}
/// <summary>Shortcut escape when we're sure value doesn't contain any escaped chars.</summary>
/// <param name="writer">.</param>
/// <param name="value"> .</param>
public void WriteRawString(TextWriter writer, string value)
{
writer.Write(JsWriter.QuoteChar);
writer.Write(value);
writer.Write(JsWriter.QuoteChar);
}
/// <summary>Writes a property name.</summary>
/// <param name="writer">The writer.</param>
/// <param name="value"> The value.</param>
public void WritePropertyName(TextWriter writer, string value)
{
if (JsState.WritingKeyCount > 0)
{
writer.Write(JsWriter.EscapedQuoteString);
writer.Write(value);
writer.Write(JsWriter.EscapedQuoteString);
}
else
{
WriteRawString(writer, value);
}
}
/// <summary>Writes a string.</summary>
/// <param name="writer">The writer.</param>
/// <param name="value"> The value.</param>
public void WriteString(TextWriter writer, string value)
{
JsonUtils.WriteString(writer, value);
}
/// <summary>Writes a built in.</summary>
/// <param name="writer">The writer.</param>
/// <param name="value"> The value.</param>
public void WriteBuiltIn(TextWriter writer, object value)
{
if (JsState.WritingKeyCount > 0 && !JsState.IsWritingValue) writer.Write(JsonUtils.QuoteChar);
WriteRawString(writer, value.ToString());
if (JsState.WritingKeyCount > 0 && !JsState.IsWritingValue) writer.Write(JsonUtils.QuoteChar);
}
/// <summary>Writes an object string.</summary>
/// <param name="writer">The writer.</param>
/// <param name="value"> The value.</param>
public void WriteObjectString(TextWriter writer, object value)
{
JsonUtils.WriteString(writer, value != null ? value.ToString() : null);
}
/// <summary>Writes a formattable object string.</summary>
/// <param name="writer">The writer.</param>
/// <param name="value"> The value.</param>
public void WriteFormattableObjectString(TextWriter writer, object value)
{
var formattable = value as IFormattable;
JsonUtils.WriteString(writer, formattable != null ? formattable.ToString(null, CultureInfo.InvariantCulture) : null);
}
/// <summary>Writes an exception.</summary>
/// <param name="writer">The writer.</param>
/// <param name="value"> The value.</param>
public void WriteException(TextWriter writer, object value)
{
WriteString(writer, ((Exception)value).Message);
}
/// <summary>Writes a date time.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="oDateTime">The date time.</param>
public void WriteDateTime(TextWriter writer, object oDateTime)
{
writer.Write(JsWriter.QuoteString);
DateTimeSerializer.WriteWcfJsonDate(writer, (DateTime)oDateTime);
writer.Write(JsWriter.QuoteString);
}
/// <summary>Writes a nullable date time.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="dateTime">The date time.</param>
public void WriteNullableDateTime(TextWriter writer, object dateTime)
{
if (dateTime == null)
writer.Write(JsonUtils.Null);
else
WriteDateTime(writer, dateTime);
}
/// <summary>Writes a date time offset.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="oDateTimeOffset">The date time offset.</param>
public void WriteDateTimeOffset(TextWriter writer, object oDateTimeOffset)
{
writer.Write(JsWriter.QuoteString);
DateTimeSerializer.WriteWcfJsonDateTimeOffset(writer, (DateTimeOffset)oDateTimeOffset);
writer.Write(JsWriter.QuoteString);
}
/// <summary>Writes a nullable date time offset.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="dateTimeOffset">The date time offset.</param>
public void WriteNullableDateTimeOffset(TextWriter writer, object dateTimeOffset)
{
if (dateTimeOffset == null)
writer.Write(JsonUtils.Null);
else
WriteDateTimeOffset(writer, dateTimeOffset);
}
/// <summary>Writes a time span.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="oTimeSpan"> The date time offset.</param>
/// ### <param name="dateTimeOffset">The date time offset.</param>
public void WriteTimeSpan(TextWriter writer, object oTimeSpan)
{
var stringValue = JsConfig.TimeSpanHandler == JsonTimeSpanHandler.StandardFormat
? oTimeSpan.ToString()
: DateTimeSerializer.ToXsdTimeSpanString((TimeSpan)oTimeSpan);
WriteRawString(writer, stringValue);
}
/// <summary>Writes a nullable time span.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="oTimeSpan"> The date time offset.</param>
/// ### <param name="dateTimeOffset">The date time offset.</param>
public void WriteNullableTimeSpan(TextWriter writer, object oTimeSpan)
{
if (oTimeSpan == null) return;
WriteTimeSpan(writer, ((TimeSpan?)oTimeSpan).Value);
}
/// <summary>Writes a unique identifier.</summary>
/// <param name="writer">The writer.</param>
/// <param name="oValue">The value.</param>
public void WriteGuid(TextWriter writer, object oValue)
{
WriteRawString(writer, ((Guid)oValue).ToString("N"));
}
/// <summary>Writes a nullable unique identifier.</summary>
/// <param name="writer">The writer.</param>
/// <param name="oValue">The value.</param>
public void WriteNullableGuid(TextWriter writer, object oValue)
{
if (oValue == null) return;
WriteRawString(writer, ((Guid)oValue).ToString("N"));
}
/// <summary>Writes the bytes.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="oByteValue">The byte value.</param>
public void WriteBytes(TextWriter writer, object oByteValue)
{
if (oByteValue == null) return;
WriteRawString(writer, Convert.ToBase64String((byte[])oByteValue));
}
/// <summary>Writes a character.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="charValue">The character value.</param>
public void WriteChar(TextWriter writer, object charValue)
{
if (charValue == null)
writer.Write(JsonUtils.Null);
else
WriteRawString(writer, ((char)charValue).ToString());
}
/// <summary>Writes a byte.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="byteValue">The byte value.</param>
public void WriteByte(TextWriter writer, object byteValue)
{
if (byteValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((byte)byteValue);
}
/// <summary>Writes an int 16.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="intValue">The int value.</param>
public void WriteInt16(TextWriter writer, object intValue)
{
if (intValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((short)intValue);
}
/// <summary>Writes an u int 16.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="intValue">The int value.</param>
public void WriteUInt16(TextWriter writer, object intValue)
{
if (intValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((ushort)intValue);
}
/// <summary>Writes an int 32.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="intValue">The int value.</param>
public void WriteInt32(TextWriter writer, object intValue)
{
if (intValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((int)intValue);
}
/// <summary>Writes an u int 32.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="uintValue">The value.</param>
public void WriteUInt32(TextWriter writer, object uintValue)
{
if (uintValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((uint)uintValue);
}
/// <summary>Writes an int 64.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="integerValue"> The long value.</param>
/// ### <param name="longValue">The long value.</param>
public void WriteInt64(TextWriter writer, object integerValue)
{
if (integerValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((long)integerValue);
}
/// <summary>Writes an u int 64.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="ulongValue">The ulong value.</param>
public void WriteUInt64(TextWriter writer, object ulongValue)
{
if (ulongValue == null)
{
writer.Write(JsonUtils.Null);
}
else
writer.Write((ulong)ulongValue);
}
/// <summary>Writes a bool.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="boolValue">The value.</param>
public void WriteBool(TextWriter writer, object boolValue)
{
if (boolValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write(((bool)boolValue) ? JsonUtils.True : JsonUtils.False);
}
/// <summary>Writes a float.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="floatValue">The float value.</param>
public void WriteFloat(TextWriter writer, object floatValue)
{
if (floatValue == null)
writer.Write(JsonUtils.Null);
else
{
var floatVal = (float)floatValue;
if (Equals(floatVal, float.MaxValue) || Equals(floatVal, float.MinValue))
writer.Write(floatVal.ToString("r", CultureInfo.InvariantCulture));
else
writer.Write(floatVal.ToString(CultureInfo.InvariantCulture));
}
}
/// <summary>Writes a double.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="doubleValue">The double value.</param>
public void WriteDouble(TextWriter writer, object doubleValue)
{
if (doubleValue == null)
writer.Write(JsonUtils.Null);
else
{
var doubleVal = (double)doubleValue;
if (Equals(doubleVal, double.MaxValue) || Equals(doubleVal, double.MinValue))
writer.Write(doubleVal.ToString("r", CultureInfo.InvariantCulture));
else
writer.Write(doubleVal.ToString(CultureInfo.InvariantCulture));
}
}
/// <summary>Writes a decimal.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="decimalValue">The decimal value.</param>
public void WriteDecimal(TextWriter writer, object decimalValue)
{
if (decimalValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write(((decimal)decimalValue).ToString(CultureInfo.InvariantCulture));
}
/// <summary>Writes an enum.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="enumValue">The enum value.</param>
public void WriteEnum(TextWriter writer, object enumValue)
{
if (enumValue == null) return;
if (GetTypeInfo(enumValue.GetType()).IsNumeric)
JsWriter.WriteEnumFlags(writer, enumValue);
else
WriteRawString(writer, enumValue.ToString());
}
/// <summary>Writes an enum flags.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="enumFlagValue">The enum flag value.</param>
public void WriteEnumFlags(TextWriter writer, object enumFlagValue)
{
JsWriter.WriteEnumFlags(writer, enumFlagValue);
}
/// <summary>Writes a linq binary.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="linqBinaryValue">The linq binary value.</param>
public void WriteLinqBinary(TextWriter writer, object linqBinaryValue)
{
#if !MONOTOUCH && !SILVERLIGHT && !XBOX && !ANDROID
WriteRawString(writer, Convert.ToBase64String(((System.Data.Linq.Binary)linqBinaryValue).ToArray()));
#endif
}
/// <summary>Gets parse function.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <returns>The parse function.</returns>
public ParseStringDelegate GetParseFn<T>()
{
return JsonReader.Instance.GetParseFn<T>();
}
/// <summary>Gets parse function.</summary>
/// <param name="type">The type.</param>
/// <returns>The parse function.</returns>
public ParseStringDelegate GetParseFn(Type type)
{
return JsonReader.GetParseFn(type);
}
/// <summary>Parse raw string.</summary>
/// <param name="value">The value.</param>
/// <returns>A string.</returns>
public string ParseRawString(string value)
{
return value;
}
/// <summary>Parse string.</summary>
/// <param name="value">The value.</param>
/// <returns>A string.</returns>
public string ParseString(string value)
{
return string.IsNullOrEmpty(value) ? value : ParseRawString(value);
}
/// <summary>Query if 'value' is empty map.</summary>
/// <param name="value">The value.</param>
/// <param name="i"> Zero-based index of the.</param>
/// <returns>true if empty map, false if not.</returns>
internal static bool IsEmptyMap(string value, int i = 1)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
if (value.Length == i) return true;
return value[i++] == JsWriter.MapEndChar;
}
/// <summary>Parse string.</summary>
/// <exception cref="Exception">Thrown when an exception error condition occurs.</exception>
/// <param name="json"> The JSON.</param>
/// <param name="index">Zero-based index of the.</param>
/// <returns>A string.</returns>
internal static string ParseString(string json, ref int index)
{
var jsonLength = json.Length;
if (json[index] != JsonUtils.QuoteChar)
throw new Exception("Invalid unquoted string starting with: " + json.SafeSubstring(50));
var startIndex = ++index;
do
{
char c = json[index];
if (c == JsonUtils.QuoteChar) break;
if (c != JsonUtils.EscapeChar) continue;
c = json[index++];
if (c == 'u')
{
index += 4;
}
} while (index++ < jsonLength);
index++;
return json.Substring(startIndex, Math.Min(index, jsonLength) - startIndex - 1);
}
/// <summary>Unescape string.</summary>
/// <param name="value">The value.</param>
/// <returns>A string.</returns>
public string UnescapeString(string value)
{
var i = 0;
return UnEscapeJsonString(value, ref i);
}
/// <summary>Unescape safe string.</summary>
/// <param name="value">The value.</param>
/// <returns>A string.</returns>
public string UnescapeSafeString(string value)
{
if (string.IsNullOrEmpty(value)) return value;
return value[0] == JsonUtils.QuoteChar && value[value.Length - 1] == JsonUtils.QuoteChar
? value.Substring(1, value.Length - 2)
: value;
//if (value[0] != JsonUtils.QuoteChar)
// throw new Exception("Invalid unquoted string starting with: " + value.SafeSubstring(50));
//return value.Substring(1, value.Length - 2);
}
/// <summary>The is safe JSON characters.</summary>
static readonly char[] IsSafeJsonChars = new[] { JsonUtils.QuoteChar, JsonUtils.EscapeChar };
/// <summary>Parse JSON string.</summary>
/// <param name="json"> The JSON.</param>
/// <param name="index">Zero-based index of the.</param>
/// <returns>A string.</returns>
internal static string ParseJsonString(string json, ref int index)
{
for (; index < json.Length; index++) { var ch = json[index]; if (ch >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[ch]) break; } //Whitespace inline
return UnEscapeJsonString(json, ref index);
}
/// <summary>Un escape JSON string.</summary>
/// <param name="json"> The JSON.</param>
/// <param name="index">Zero-based index of the.</param>
/// <returns>A string.</returns>
private static string UnEscapeJsonString(string json, ref int index)
{
if (string.IsNullOrEmpty(json)) return json;
var jsonLength = json.Length;
var firstChar = json[index];
if (firstChar == JsonUtils.QuoteChar)
{
index++;
//MicroOp: See if we can short-circuit evaluation (to avoid StringBuilder)
var strEndPos = json.IndexOfAny(IsSafeJsonChars, index);
if (strEndPos == -1) return json.Substring(index, jsonLength - index);
if (json[strEndPos] == JsonUtils.QuoteChar)
{
var potentialValue = json.Substring(index, strEndPos - index);
index = strEndPos + 1;
return potentialValue;
}
}
return Unescape(json);
}
/// <summary>Unescapes.</summary>
/// <param name="input">The input.</param>
/// <returns>A string.</returns>
public static string Unescape(string input)
{
var length = input.Length;
int start = 0;
int count = 0;
StringBuilder output = new StringBuilder(length);
for (; count < length; )
{
if (input[count] == JsonUtils.QuoteChar)
{
if (start != count)
{
output.Append(input, start, count - start);
}
count++;
start = count;
continue;
}
if (input[count] == JsonUtils.EscapeChar)
{
if (start != count)
{
output.Append(input, start, count - start);
}
start = count;
count++;
if (count >= length) continue;
//we will always be parsing an escaped char here
var c = input[count];
switch (c)
{
case 'a':
output.Append('\a');
count++;
break;
case 'b':
output.Append('\b');
count++;
break;
case 'f':
output.Append('\f');
count++;
break;
case 'n':
output.Append('\n');
count++;
break;
case 'r':
output.Append('\r');
count++;
break;
case 'v':
output.Append('\v');
count++;
break;
case 't':
output.Append('\t');
count++;
break;
case 'u':
if (count + 4 < length)
{
var unicodeString = input.Substring(count + 1, 4);
var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber);
output.Append(JsonTypeSerializer.ConvertFromUtf32((int)unicodeIntVal));
count += 5;
}
else
{
output.Append(c);
}
break;
case 'x':
if (count + 4 < length)
{
var unicodeString = input.Substring(count + 1, 4);
var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber);
output.Append(JsonTypeSerializer.ConvertFromUtf32((int)unicodeIntVal));
count += 5;
}
else
if (count + 2 < length)
{
var unicodeString = input.Substring(count + 1, 2);
var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber);
output.Append(JsonTypeSerializer.ConvertFromUtf32((int)unicodeIntVal));
count += 3;
}
else
{
output.Append(input, start, count - start);
}
break;
default:
output.Append(c);
count++;
break;
}
start = count;
}
else
{
count++;
}
}
output.Append(input, start, length - start);
return output.ToString();
}
/// <summary>
/// Given a character as utf32, returns the equivalent string provided that the character is
/// legal json.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown when one or more arguments are outside the
/// required range.</exception>
/// <param name="utf32">.</param>
/// <returns>from converted UTF 32.</returns>
public static string ConvertFromUtf32(int utf32)
{
if (utf32 < 0 || utf32 > 0x10FFFF)
throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF.");
if (utf32 < 0x10000)
return new string((char)utf32, 1);
utf32 -= 0x10000;
return new string(new[] {(char) ((utf32 >> 10) + 0xD800),
(char) (utf32 % 0x0400 + 0xDC00)});
}
/// <summary>Eat type value.</summary>
/// <param name="value">The value.</param>
/// <param name="i"> Zero-based index of the.</param>
/// <returns>A string.</returns>
public string EatTypeValue(string value, ref int i)
{
return EatValue(value, ref i);
}
/// <summary>Eat map start character.</summary>
/// <param name="value">The value.</param>
/// <param name="i"> Zero-based index of the.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
public bool EatMapStartChar(string value, ref int i)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
return value[i++] == JsWriter.MapStartChar;
}
/// <summary>Eat map key.</summary>
/// <param name="value">The value.</param>
/// <param name="i"> Zero-based index of the.</param>
/// <returns>A string.</returns>
public string EatMapKey(string value, ref int i)
{
var valueLength = value.Length;
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
var tokenStartPos = i;
var valueChar = value[i];
switch (valueChar)
{
//If we are at the end, return.
case JsWriter.ItemSeperator:
case JsWriter.MapEndChar:
return null;
//Is Within Quotes, i.e. "..."
case JsWriter.QuoteChar:
return ParseString(value, ref i);
}
//Is Value
while (++i < valueLength)
{
valueChar = value[i];
if (valueChar == JsWriter.ItemSeperator
//If it doesn't have quotes it's either a keyword or number so also has a ws boundary
|| (valueChar < WhiteSpaceFlags.Length && WhiteSpaceFlags[valueChar])
)
{
break;
}
}
return value.Substring(tokenStartPos, i - tokenStartPos);
}
/// <summary>Eat map key seperator.</summary>
/// <param name="value">The value.</param>
/// <param name="i"> Zero-based index of the.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
public bool EatMapKeySeperator(string value, ref int i)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
if (value.Length == i) return false;
return value[i++] == JsWriter.MapKeySeperator;
}
/// <summary>Eat item seperator map end character.</summary>
/// <param name="value">The value.</param>
/// <param name="i"> Zero-based index of the.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
public bool EatItemSeperatorOrMapEndChar(string value, ref int i)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
if (i == value.Length) return false;
var success = value[i] == JsWriter.ItemSeperator
|| value[i] == JsWriter.MapEndChar;
i++;
if (success)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
}
return success;
}
/// <summary>Eat whitespace.</summary>
/// <param name="value">The value.</param>
/// <param name="i"> Zero-based index of the.</param>
public void EatWhitespace(string value, ref int i)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
}
/// <summary>Eat value.</summary>
/// <param name="value">The value.</param>
/// <param name="i"> Zero-based index of the.</param>
/// <returns>A string.</returns>
public string EatValue(string value, ref int i)
{
var valueLength = value.Length;
if (i == valueLength) return null;
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
if (i == valueLength) return null;
var tokenStartPos = i;
var valueChar = value[i];
var withinQuotes = false;
var endsToEat = 1;
switch (valueChar)
{
//If we are at the end, return.
case JsWriter.ItemSeperator:
case JsWriter.MapEndChar:
return null;
//Is Within Quotes, i.e. "..."
case JsWriter.QuoteChar:
return ParseString(value, ref i);
//Is Type/Map, i.e. {...}
case JsWriter.MapStartChar:
while (++i < valueLength && endsToEat > 0)
{
valueChar = value[i];
if (valueChar == JsonUtils.EscapeChar)
{
i++;
continue;
}
if (valueChar == JsWriter.QuoteChar)
withinQuotes = !withinQuotes;
if (withinQuotes)
continue;
if (valueChar == JsWriter.MapStartChar)
endsToEat++;
if (valueChar == JsWriter.MapEndChar)
endsToEat--;
}
return value.Substring(tokenStartPos, i - tokenStartPos);
//Is List, i.e. [...]
case JsWriter.ListStartChar:
while (++i < valueLength && endsToEat > 0)
{
valueChar = value[i];
if (valueChar == JsonUtils.EscapeChar)
{
i++;
continue;
}
if (valueChar == JsWriter.QuoteChar)
withinQuotes = !withinQuotes;
if (withinQuotes)
continue;
if (valueChar == JsWriter.ListStartChar)
endsToEat++;
if (valueChar == JsWriter.ListEndChar)
endsToEat--;
}
return value.Substring(tokenStartPos, i - tokenStartPos);
}
//Is Value
while (++i < valueLength)
{
valueChar = value[i];
if (valueChar == JsWriter.ItemSeperator
|| valueChar == JsWriter.MapEndChar
//If it doesn't have quotes it's either a keyword or number so also has a ws boundary
|| (valueChar < WhiteSpaceFlags.Length && WhiteSpaceFlags[valueChar])
)
{
break;
}
}
var strValue = value.Substring(tokenStartPos, i - tokenStartPos);
return strValue == JsonUtils.Null ? null : strValue;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ViewSwitchingNavigation.Email.Model;
using ViewSwitchingNavigation.Email.ViewModels;
using System.Threading;
using Prism.Interactivity.InteractionRequest;
using Prism.Regions;
namespace ViewSwitchingNavigation.Email.Tests
{
[TestClass]
public class ComposeEmailViewModelFixture
{
[TestMethod]
public void WhenSendMessageCommandIsExecuted_ThenSendsMessageThroughService()
{
var emailServiceMock = new Mock<IEmailService>();
var viewModel = new ComposeEmailViewModel(emailServiceMock.Object);
((INavigationAware)viewModel).OnNavigatedTo(new NavigationContext(new Mock<IRegionNavigationService>().Object, new Uri("", UriKind.Relative)));
viewModel.SendEmailCommand.Execute(null);
Assert.AreEqual("Sending", viewModel.SendState);
emailServiceMock.Verify(svc => svc.BeginSendEmailDocument(viewModel.EmailDocument, It.IsAny<AsyncCallback>(), null));
}
[TestMethod]
public void WhenNavigatedToWithAReplyToQueryParameter_ThenRepliesToTheAppropriateMessage()
{
var replyToEmail = new EmailDocument { From = "somebody@contoso.com", To = "", Subject = "", Text = "" };
var emailServiceMock = new Mock<IEmailService>();
emailServiceMock
.Setup(svc => svc.GetEmailDocument(replyToEmail.Id))
.Returns(replyToEmail);
var viewModel = new ComposeEmailViewModel(emailServiceMock.Object);
var navService = new Mock<IRegionNavigationService>();
var region = new Mock<IRegion>();
region.SetupGet(x => x.Context).Returns(null);
navService.SetupGet(x => x.Region).Returns(region.Object);
((INavigationAware)viewModel).OnNavigatedTo(new NavigationContext(navService.Object, new Uri("location?ReplyTo=" + replyToEmail.Id.ToString("N"), UriKind.Relative)));
Assert.AreEqual("somebody@contoso.com", viewModel.EmailDocument.To);
}
[TestMethod]
public void WhenNavigatedToWithAToQueryParameter_ThenInitializesToField()
{
var emailServiceMock = new Mock<IEmailService>();
var viewModel = new ComposeEmailViewModel(emailServiceMock.Object);
var navService = new Mock<IRegionNavigationService>();
var region = new Mock<IRegion>();
region.SetupGet(x => x.Context).Returns(null);
navService.SetupGet(x => x.Region).Returns(region.Object);
((INavigationAware)viewModel).OnNavigatedTo(new NavigationContext(navService.Object, new Uri("location?To=somebody@contoso.com", UriKind.Relative)));
Assert.AreEqual("somebody@contoso.com", viewModel.EmailDocument.To);
}
[TestMethod]
public void WhenFinishedSendingMessage_ThenNavigatesBack()
{
var sendEmailResultMock = new Mock<IAsyncResult>();
var emailServiceMock = new Mock<IEmailService>();
AsyncCallback callback = null;
emailServiceMock
.Setup(svc => svc.BeginSendEmailDocument(It.IsAny<EmailDocument>(), It.IsAny<AsyncCallback>(), null))
.Callback<EmailDocument, AsyncCallback, object>((e, c, o) => { callback = c; })
.Returns(sendEmailResultMock.Object);
emailServiceMock
.Setup(svc => svc.EndSendEmailDocument(sendEmailResultMock.Object))
.Verifiable();
var journalMock = new Mock<IRegionNavigationJournal>();
journalMock.Setup(j => j.GoBack()).Verifiable();
var navigationServiceMock = new Mock<IRegionNavigationService>();
navigationServiceMock.SetupGet(svc => svc.Journal).Returns(journalMock.Object);
var viewModel = new ComposeEmailViewModel(emailServiceMock.Object);
((INavigationAware)viewModel).OnNavigatedTo(new NavigationContext(navigationServiceMock.Object, new Uri("", UriKind.Relative)));
viewModel.SendEmailCommand.Execute(null);
callback(sendEmailResultMock.Object);
// The action is performed asynchronously in the view model, so we need to wait until it's completed.
Thread.Sleep(500);
Assert.AreEqual("Sent", viewModel.SendState);
journalMock.VerifyAll();
}
[TestMethod]
public void WhenRequestedForVetoOnNavigationBeforeSubmitting_ThenRaisesInteractionRequest()
{
var emailServiceMock = new Mock<IEmailService>();
var viewModel = new ComposeEmailViewModel(emailServiceMock.Object);
var navService = new Mock<IRegionNavigationService>();
var region = new Mock<IRegion>();
region.SetupGet(x => x.Context).Returns(null);
navService.SetupGet(x => x.Region).Returns(region.Object);
((INavigationAware)viewModel).OnNavigatedTo(new NavigationContext(navService.Object, new Uri("location?To=somebody@contoso.com", UriKind.Relative)));
InteractionRequestedEventArgs args = null;
viewModel.ConfirmExitInteractionRequest.Raised += (s, e) => args = e;
bool? callbackResult = null;
((IConfirmNavigationRequest)viewModel).ConfirmNavigationRequest(
new NavigationContext(new Mock<IRegionNavigationService>().Object, new Uri("some uri", UriKind.Relative)),
b => callbackResult = b);
Assert.IsNotNull(args);
Assert.IsNull(callbackResult);
}
[TestMethod]
public void WhenRequestedForVetoOnNavigationAfterSubmitting_ThenDoesNotRaiseInteractionRequest()
{
var emailServiceMock = new Mock<IEmailService>();
var viewModel = new ComposeEmailViewModel(emailServiceMock.Object);
var navService = new Mock<IRegionNavigationService>();
var region = new Mock<IRegion>();
region.SetupGet(x => x.Context).Returns(null);
navService.SetupGet(x => x.Region).Returns(region.Object);
((INavigationAware)viewModel).OnNavigatedTo(new NavigationContext(navService.Object, new Uri("location?To=somebody@contoso.com", UriKind.Relative)));
InteractionRequestedEventArgs args = null;
viewModel.ConfirmExitInteractionRequest.Raised += (s, e) => args = e;
viewModel.SendEmailCommand.Execute(null);
bool? callbackResult = null;
((IConfirmNavigationRequest)viewModel).ConfirmNavigationRequest(
new NavigationContext(new Mock<IRegionNavigationService>().Object, new Uri("some uri", UriKind.Relative)),
b => callbackResult = b);
Assert.IsNull(args);
Assert.IsTrue(callbackResult.Value);
}
[TestMethod]
public void WhenRejectingConfirmationToNavigateAway_ThenInvokesRequestCallbackWithFalse()
{
var emailServiceMock = new Mock<IEmailService>();
var viewModel = new ComposeEmailViewModel(emailServiceMock.Object);
var navService = new Mock<IRegionNavigationService>();
var region = new Mock<IRegion>();
region.SetupGet(x => x.Context).Returns(null);
navService.SetupGet(x => x.Region).Returns(region.Object);
((INavigationAware)viewModel).OnNavigatedTo(new NavigationContext(navService.Object, new Uri("location?To=somebody@contoso.com", UriKind.Relative)));
InteractionRequestedEventArgs args = null;
viewModel.ConfirmExitInteractionRequest.Raised += (s, e) => args = e;
bool? callbackResult = null;
((IConfirmNavigationRequest)viewModel).ConfirmNavigationRequest(
new NavigationContext(new Mock<IRegionNavigationService>().Object, new Uri("some uri", UriKind.Relative)),
b => callbackResult = b);
var confirmation = args.Context as Confirmation;
confirmation.Confirmed = false;
args.Callback();
Assert.IsFalse(callbackResult.Value);
}
[TestMethod]
public void WhenAcceptingConfirmationToNavigateAway_ThenInvokesRequestCallbackWithTrue()
{
var emailServiceMock = new Mock<IEmailService>();
var viewModel = new ComposeEmailViewModel(emailServiceMock.Object);
var navService = new Mock<IRegionNavigationService>();
var region = new Mock<IRegion>();
region.SetupGet(x => x.Context).Returns(null);
navService.SetupGet(x => x.Region).Returns(region.Object);
((INavigationAware)viewModel).OnNavigatedTo(new NavigationContext(navService.Object, new Uri("location?To=somebody@contoso.com", UriKind.Relative)));
InteractionRequestedEventArgs args = null;
viewModel.ConfirmExitInteractionRequest.Raised += (s, e) => args = e;
bool? callbackResult = null;
((IConfirmNavigationRequest)viewModel).ConfirmNavigationRequest(
new NavigationContext(new Mock<IRegionNavigationService>().Object, new Uri("some uri", UriKind.Relative)),
b => callbackResult = b);
var confirmation = args.Context as Confirmation;
confirmation.Confirmed = true;
args.Callback();
Assert.IsTrue(callbackResult.Value);
}
[TestMethod]
public void WhenCancelling_ThenNavigatesBack()
{
var emailServiceMock = new Mock<IEmailService>();
var viewModel = new ComposeEmailViewModel(emailServiceMock.Object);
var journalMock = new Mock<IRegionNavigationJournal>();
var navigationServiceMock = new Mock<IRegionNavigationService>();
navigationServiceMock.SetupGet(svc => svc.Journal).Returns(journalMock.Object);
((INavigationAware)viewModel).OnNavigatedTo(
new NavigationContext(
navigationServiceMock.Object,
new Uri("location", UriKind.Relative)));
viewModel.CancelEmailCommand.Execute(null);
journalMock.Verify(j => j.GoBack());
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.IO;
using System.Text;
using Microsoft.CSharp;
//using Microsoft.JScript;
using Microsoft.VisualBasic;
using log4net;
using OpenSim.Region.Framework.Interfaces;
using OpenMetaverse;
namespace Aurora.ScriptEngine.AuroraDotNetEngine.CompilerTools
{
public class Compiler
{
#region Declares
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// * Uses "LSL2Converter" to convert LSL to C# if necessary.
// * Compiles C#-code into an assembly
// * Returns assembly name ready for AppDomain load.
//
// Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
//
private string DefaultCompileLanguage;
private bool WriteScriptSourceToDebugFile;
private bool CompileWithDebugInformation;
public Dictionary<string, IScriptConverter> AllowedCompilers = new Dictionary<string, IScriptConverter>(StringComparer.CurrentCultureIgnoreCase);
List<IScriptConverter> converters = new List<IScriptConverter>();
private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> PositionMap;
public bool firstStartup = true;
private string FilePrefix;
private List<string> m_warnings = new List<string>();
private List<string> m_errors = new List<string>();
private List<string> m_referencedFiles = new List<string>();
private static UInt64 scriptCompileCounter = 0; // And a counter
public UInt64 ScriptCompileCounter
{
get { return scriptCompileCounter; }
}
private ScriptEngine m_scriptEngine;
public ScriptEngine ScriptEngine
{
get { return m_scriptEngine; }
}
#endregion
#region Setup
public Compiler(ScriptEngine scriptEngine)
{
m_scriptEngine = scriptEngine;
ReadConfig();
SetupApis();
}
public void ReadConfig()
{
// Get some config
WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", false);
CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true);
MakeFilePrefixSafe();
//Set up the compilers
SetupCompilers();
//Find the default compiler
FindDefaultCompiler();
}
private void MakeFilePrefixSafe()
{
// Get file prefix from scriptengine name and make it file system safe:
FilePrefix = "CommonCompiler";
foreach (char c in Path.GetInvalidFileNameChars())
{
FilePrefix = FilePrefix.Replace(c, '_');
}
}
private void FindDefaultCompiler()
{
// Allowed compilers
string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl");
AllowedCompilers.Clear();
// Default language
DefaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower();
bool found = false;
foreach (string strl in allowComp.Split(','))
{
string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
foreach (IScriptConverter converter in converters)
{
if (converter.Name == strlan)
{
AllowedCompilers.Add(strlan, converter);
if (converter.Name == DefaultCompileLanguage)
{
found = true;
}
}
}
}
if (AllowedCompilers.Count == 0)
m_log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
if (!found)
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + DefaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
// Is this language in allow-list?
if (!AllowedCompilers.ContainsKey(DefaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + DefaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
}
// We now have an allow-list, a mapping list, and a default language
}
private void SetupCompilers()
{
converters = Aurora.Framework.AuroraModuleLoader.PickupModules<IScriptConverter>();
foreach (IScriptConverter convert in converters)
{
convert.Initialise(this);
}
}
private void SetupApis()
{
//Get all of the Apis that are allowed (this does check for it)
IScriptApi[] apis = m_scriptEngine.GetAPIs();
//Now we need to pull the files they will need to access from them
foreach (IScriptApi api in apis)
{
m_referencedFiles.AddRange(api.ReferencedAssemblies);
}
}
#endregion
#region Compile script
/// <summary>
/// Converts script (if needed) and compiles
/// </summary>
/// <param name="Script">LSL script</param>
/// <returns>Filename to .dll assembly</returns>
public void PerformScriptCompile(string Script, UUID itemID, UUID ownerUUID, int VersionID, out string assembly)
{
assembly = "";
if (Script == String.Empty)
{
AddError("No script text present");
return;
}
m_warnings.Clear();
m_errors.Clear();
UUID assemblyGuid = UUID.Random();
// assembly = CheckDirectories(FilePrefix + "_compiled_" + itemID.ToString() + "V" + VersionID + ".dll", itemID);
assembly = CheckDirectories(assemblyGuid.ToString() + ".dll", assemblyGuid);
IScriptConverter converter;
string compileScript;
CheckLanguageAndConvert(Script, ownerUUID, out converter, out compileScript);
if (GetErrors().Length != 0)
return;
if (converter == null)
{
AddError("No Compiler found for this type of script.");
return;
}
CompileFromDotNetText(compileScript, converter, assembly, Script, false);
}
/// <summary>
/// Converts script (if needed) and compiles into memory
/// </summary>
/// <param name="Script"></param>
/// <param name="itemID"></param>
/// <returns></returns>
public void PerformInMemoryScriptCompile(string Script, UUID itemID)
{
if (Script == String.Empty)
{
AddError("No script text present");
return;
}
m_warnings.Clear();
m_errors.Clear();
IScriptConverter converter;
string compileScript;
CheckLanguageAndConvert(Script, UUID.Zero, out converter, out compileScript);
if (GetErrors().Length != 0)
return;
if (converter == null)
{
AddError("No Compiler found for this type of script.");
return;
}
CompileFromDotNetText(compileScript, converter, "", Script, true);
}
public string FindDefaultStateForScript (string Script)
{
return FindConverterForScript(Script).DefaultState;
}
public IScriptConverter FindConverterForScript(string Script)
{
IScriptConverter language = null;
foreach (IScriptConverter convert in converters)
{
if (convert.Name == DefaultCompileLanguage)
{
language = convert;
break;
}
}
foreach (IScriptConverter convert in converters)
{
if (Script.StartsWith ("//" + convert.Name, true, CultureInfo.InvariantCulture))
language = convert;
}
return language;
}
private void CheckLanguageAndConvert(string Script, UUID ownerID, out IScriptConverter converter, out string compileScript)
{
compileScript = Script;
converter = null;
string language = DefaultCompileLanguage;
foreach (IScriptConverter convert in converters)
{
if (Script.StartsWith("//" + convert.Name, true, CultureInfo.InvariantCulture))
language = convert.Name;
}
if (!AllowedCompilers.ContainsKey(language))
{
// Not allowed to compile to this language!
AddError("The compiler for language \"" + language.ToString() + "\" is not in list of allowed compilers. Script will not be executed!");
return;
}
if (m_scriptEngine.Worlds[0].Permissions.CanCompileScript(ownerID, language) == false)
{
// Not allowed to compile to this language!
AddError(ownerID + " is not in list of allowed users for this scripting language. Script will not be executed!");
return;
}
AllowedCompilers.TryGetValue(language, out converter);
converter.Convert(Script, out compileScript, out PositionMap);
}
public void RecreateDirectory()
{
if (Directory.Exists(m_scriptEngine.ScriptEnginesPath))
{
string[] directories = Directory.GetDirectories(m_scriptEngine.ScriptEnginesPath);
foreach (string dir in directories)
{
try
{
Directory.Delete(dir, true);
}
catch (Exception) { }
}
}
if (!Directory.Exists(m_scriptEngine.ScriptEnginesPath))
{
try
{
Directory.CreateDirectory(m_scriptEngine.ScriptEnginesPath);
}
catch (Exception) { }
}
}
private string CheckDirectories(string assembly, UUID itemID)
{
string dirName = itemID.ToString().Substring(0, 3);
if (!Directory.Exists(m_scriptEngine.ScriptEnginesPath))
{
try
{
Directory.CreateDirectory(m_scriptEngine.ScriptEnginesPath);
}
catch (Exception)
{
}
}
if (!Directory.Exists(Path.Combine(m_scriptEngine.ScriptEnginesPath, dirName)))
{
try
{
Directory.CreateDirectory(Path.Combine(m_scriptEngine.ScriptEnginesPath, dirName));
}
catch (Exception)
{
}
}
assembly = Path.Combine(Path.Combine(m_scriptEngine.ScriptEnginesPath, dirName), assembly);
assembly = CheckAssembly(assembly, 0);
return assembly;
}
private string CheckAssembly(string assembly, int i)
{
if (File.Exists(assembly) || File.Exists(assembly.Remove(assembly.Length - 4) + ".pdb"))
{
try
{
File.Delete(assembly);
File.Delete(assembly.Remove(assembly.Length - 4) + ".pdb");
}
catch (Exception) // NOTLEGIT - Should be just FileIOException
{
assembly = assembly.Remove(assembly.Length - 4);
assembly += "A.dll";
i++;
return CheckAssembly(assembly, i);
}
}
return assembly;
}
public string[] GetWarnings()
{
return m_warnings.ToArray();
}
public void AddWarning(string warning)
{
if (!m_warnings.Contains(warning))
{
m_warnings.Add(warning);
}
}
public string[] GetErrors()
{
return m_errors.ToArray();
}
public void AddError(string error)
{
if (!m_errors.Contains(error))
{
m_errors.Add(error);
}
}
/// <summary>
/// Compile .NET script to .Net assembly (.dll)
/// </summary>
/// <param name="Script">CS script</param>
/// <returns>Filename to .dll assembly</returns>
internal void CompileFromDotNetText(string Script, IScriptConverter converter, string assembly, string originalScript, bool inMemory)
{
string ext = "." + converter.Name;
if (!inMemory)
{
// Output assembly name
scriptCompileCounter++;
try
{
File.Delete(assembly);
}
catch (Exception e) // NOTLEGIT - Should be just FileIOException
{
AddError("Unable to delete old existing " +
"script-file before writing new. Compile aborted: " +
e.ToString());
return;
}
// DEBUG - write source to disk
if (WriteScriptSourceToDebugFile)
{
string srcFileName = Path.GetFileNameWithoutExtension(assembly) + ext;
try
{
File.WriteAllText(Path.Combine(m_scriptEngine.ScriptEnginesPath,
srcFileName), Script);
}
catch (Exception ex) //NOTLEGIT - Should be just FileIOException
{
m_log.Error("[Compiler]: Exception while " +
"trying to write script source to file \"" +
srcFileName + "\": " + ex.ToString());
}
}
}
// Do actual compile
CompilerParameters parameters = new CompilerParameters();
parameters.IncludeDebugInformation = true;
string rootPath =
Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"Aurora.ScriptEngine.AuroraDotNetEngine.dll"));
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Framework.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenMetaverseTypes.dll"));
if (converter.Name == "yp")
{
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.YieldProlog.dll"));
}
parameters.ReferencedAssemblies.AddRange(m_referencedFiles.ToArray());
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = inMemory;
parameters.OutputAssembly = assembly;
parameters.IncludeDebugInformation = CompileWithDebugInformation;
//parameters.WarningLevel = 1; // Should be 4?
parameters.TreatWarningsAsErrors = false;
CompilerResults results = converter.Compile(parameters, Script);
parameters = null;
//
// WARNINGS AND ERRORS
//
if (results.Errors.Count > 0)
{
string srcFileName = FilePrefix + "_source_" +
Path.GetFileNameWithoutExtension(assembly) + ext;
try
{
File.WriteAllText(Path.Combine(m_scriptEngine.ScriptEnginesPath,
srcFileName), Script);
}
catch (Exception ex) //NOTLEGIT - Should be just FileIOException
{
m_log.Error("[Compiler]: Exception while " +
"trying to write script source to file \"" +
srcFileName + "\": " + ex.ToString());
}
foreach (CompilerError CompErr in results.Errors)
{
string severity = CompErr.IsWarning ? "Warning" : "Error";
KeyValuePair<int, int> lslPos;
// Show 5 errors max, but check entire list for errors
string errtext = String.Empty;
if (severity == "Error")
{
string text = CompErr.ErrorText;
int LineN = 0;
int CharN = 0;
// Use LSL type names
if (converter.Name == "lsl")
{
text = ReplaceTypes(CompErr.ErrorText);
text = CleanError(text);
lslPos = FindErrorPosition(CompErr.Line, CompErr.Column, PositionMap);
LineN = lslPos.Key - 1;
CharN = lslPos.Value - 1;
if (LineN <= 0 && CharN != 0)
{
string[] lines = originalScript.Split('\n');
int charCntr = 0;
int lineCntr = 0;
foreach(string line in lines)
{
if (charCntr + line.Length > CharN)
{
//Its in this line
CharN -= charCntr;
LineN = lineCntr;
break;
}
charCntr += line.Length - 1;
lineCntr++;
}
}
}
else
{
LineN = CompErr.Line;
CharN = CompErr.Column;
}
//This will crash some viewers if the pos is 0,0!
if (LineN <= 0 && CharN <= 0)
{
CharN = 1;
LineN = 1;
}
// The Second Life viewer's script editor begins
// countingn lines and columns at 0, so we subtract 1.
errtext += String.Format("({0},{1}): {3}: {2}\n",
LineN, CharN, text, severity);
AddError(errtext);
}
else
{
string text = CompErr.ErrorText;
int LineN = 0;
int CharN = 0;
// Use LSL type names
if (converter.Name == "lsl")
{
text = ReplaceTypes(CompErr.ErrorText);
text = CleanError(text);
lslPos = FindErrorPosition(CompErr.Line, CompErr.Column, PositionMap);
LineN = lslPos.Key - 1;
CharN = lslPos.Value - 1;
if (LineN <= 0 && CharN != 0)
{
string[] lines = originalScript.Split('\n');
int charCntr = 0;
int lineCntr = 0;
foreach(string line in lines)
{
if (charCntr + line.Length > CharN)
{
//Its in this line
CharN -= charCntr;
LineN = lineCntr;
break;
}
charCntr += line.Length - 1;
lineCntr++;
}
}
}
else
{
LineN = CompErr.Line;
CharN = CompErr.Column;
}
//This will crash some viewers if the pos is 0,0!
if (LineN == 0 && CharN == 0)
{
CharN = 1;
LineN = 1;
}
// The Second Life viewer's script editor begins
// countingn lines and columns at 0, so we subtract 1.
errtext += String.Format("({0},{1}): {3}: {2}\n",
LineN, CharN, text, severity);
AddWarning(errtext);
}
}
}
results = null;
if (m_errors.Count != 0) // Quit early then
return;
// On today's highly asynchronous systems, the result of
// the compile may not be immediately apparent. Wait a
// reasonable amount of time before giving up on it.
if (!inMemory)
{
if (!File.Exists(assembly))
{
for (int i = 0; i < 500 && !File.Exists(assembly); i++)
{
System.Threading.Thread.Sleep(10);
}
AddError("No compile error. But not able to locate compiled file.");
}
}
}
internal void FinishCompile (ScriptData scriptData, IScript Script)
{
FindConverterForScript (scriptData.Source).FinishCompile (m_scriptEngine, scriptData, Script);
}
private class kvpSorter : IComparer<KeyValuePair<int, int>>
{
public int Compare(KeyValuePair<int, int> a,
KeyValuePair<int, int> b)
{
return a.Key.CompareTo(b.Key);
}
}
public static KeyValuePair<int, int> FindErrorPosition(int line,
int col, Dictionary<KeyValuePair<int, int>,
KeyValuePair<int, int>> positionMap)
{
if (positionMap == null || positionMap.Count == 0)
return new KeyValuePair<int, int>(line, col);
KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
out ret))
return ret;
List<KeyValuePair<int, int>> sorted =
new List<KeyValuePair<int, int>>(positionMap.Keys);
sorted.Sort(new kvpSorter());
int l = 1;
int c = 1;
foreach (KeyValuePair<int, int> cspos in sorted)
{
if (cspos.Key >= line)
{
if (cspos.Key > line)
return new KeyValuePair<int, int>(l, c);
if (cspos.Value > col)
return new KeyValuePair<int, int>(l, c);
c = cspos.Value;
if (c == 0)
c++;
}
else
{
l = cspos.Key;
}
}
return new KeyValuePair<int, int>(l, c);
}
string ReplaceTypes(string message)
{
message = message.Replace(
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString",
"string");
message = message.Replace(
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLInteger",
"integer");
message = message.Replace(
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLFloat",
"float");
message = message.Replace(
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.list",
"list");
return message;
}
string CleanError(string message)
{
//Remove these long strings
message = message.Replace(
"Aurora.ScriptEngine.AuroraDotNetEngine.Runtime.ScriptBaseClass.",
"");
message = message.Replace(
"Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.",
"");
if (message.Contains("The best overloaded method match for"))
{
string[] messageSplit = message.Split('\'');
string Function = messageSplit[1];
string[] FunctionSplit = Function.Split('(');
string FunctionName = FunctionSplit[0];
string Arguments = FunctionSplit[1].Split(')')[0];
message = "Incorrect argument in " + FunctionName + ", arguments should be " + Arguments + "\n";
}
if (message == "Unexpected EOF")
{
message = "Missing one or more }." + "\n";
}
return message;
}
#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 Xunit;
namespace System.Diagnostics.TraceSourceTests
{
using Method = TestTraceListener.Method;
public class TraceListenerClassTests
{
[Fact]
public void NameTest()
{
var listener = new TestTraceListener();
listener.Name = null;
Assert.Equal("", listener.Name);
}
[Fact]
public void IndentLevelTest()
{
var listener = new TestTraceListener();
listener.IndentLevel = 0;
Assert.Equal(0, listener.IndentLevel);
listener.IndentLevel = 2;
Assert.Equal(2, listener.IndentLevel);
listener.IndentLevel = -1;
Assert.Equal(0, listener.IndentLevel);
}
[Fact]
public void IndentSizeTest()
{
var listener = new TestTraceListener();
listener.IndentSize = 0;
Assert.Equal(0, listener.IndentSize);
listener.IndentSize = 2;
Assert.Equal(2, listener.IndentSize);
Assert.Throws<ArgumentOutOfRangeException>(() => listener.IndentSize = -1);
}
[Fact]
public void FilterTest()
{
var listener = new TestTraceListener();
listener.Filter = new SourceFilter("TestSource");
Assert.NotNull(listener.Filter);
}
[Fact]
public void TraceOutputOptionsTest()
{
var listener = new TestTraceListener();
listener.TraceOutputOptions = TraceOptions.None;
// NOTE: TraceOptions includes values for 0x01 and 0x20 in .Net 4.5, but not in CoreFX
// These assertions test for those missing values, and the exceptional condition that
// maintains compatibility with 4.5
var missingValue = (TraceOptions)0x01;
listener.TraceOutputOptions = missingValue;
missingValue = (TraceOptions)0x20;
listener.TraceOutputOptions = missingValue;
var badValue = (TraceOptions)0x80;
Assert.Throws<ArgumentOutOfRangeException>(() => listener.TraceOutputOptions = badValue);
}
[Fact]
public void WriteObjectTest()
{
var listener = new TestTraceListener();
listener.Filter = new TestTraceFilter(false);
listener.Write((object)"Message");
Assert.Equal(0, listener.GetCallCount(Method.Write));
listener.Filter = new TestTraceFilter(true);
listener.Write((object)null);
Assert.Equal(0, listener.GetCallCount(Method.Write));
listener.Write((object)"Message");
Assert.Equal(1, listener.GetCallCount(Method.Write));
}
[Fact]
public void WriteCategoryTest()
{
var listener = new TestTraceListener();
listener.Filter = new TestTraceFilter(false);
listener.Write("Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.Write));
listener.Filter = new TestTraceFilter(true);
listener.Write("Message", null);
Assert.Equal(1, listener.GetCallCount(Method.Write));
listener.Write("Message", "Category");
Assert.Equal(2, listener.GetCallCount(Method.Write));
listener.Write(null, "Category");
Assert.Equal(3, listener.GetCallCount(Method.Write));
}
[Fact]
public void WriteCategoryTest2()
{
var listener = new TestTraceListener();
listener.Filter = new TestTraceFilter(false);
listener.Write((object)"Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.Write));
listener.Filter = new TestTraceFilter(true);
listener.Write((object)"Message", null);
Assert.Equal(1, listener.GetCallCount(Method.Write));
listener.Write((object)"Message", "Category");
Assert.Equal(2, listener.GetCallCount(Method.Write));
listener.Write((object)null, "Category");
Assert.Equal(3, listener.GetCallCount(Method.Write));
}
[Fact]
public void IndentTest()
{
var listener = new TestTextTraceListener();
listener.IndentLevel = 2;
listener.IndentSize = 4;
listener.Write("Message");
listener.Flush();
Assert.Equal(" Message", listener.Output);
listener = new TestTextTraceListener();
listener.IndentLevel = 1;
listener.IndentSize = 3;
listener.Write("Message");
listener.Flush();
Assert.Equal(" Message", listener.Output);
}
[Fact]
public void WriteLineObjectTest()
{
var listener = new TestTraceListener();
listener.Filter = new TestTraceFilter(false);
listener.WriteLine((object)"Message");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
listener.Filter = new TestTraceFilter(true);
// NOTE: Writing null will result in a newline being written
listener.WriteLine((object)null);
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
listener.WriteLine((object)"Message");
Assert.Equal(2, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void WriteLineCategoryTest()
{
var listener = new TestTraceListener();
listener.Filter = new TestTraceFilter(false);
listener.WriteLine("Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
listener.Filter = new TestTraceFilter(true);
listener.WriteLine("Message", null);
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
listener.WriteLine("Message", "Category");
Assert.Equal(2, listener.GetCallCount(Method.WriteLine));
listener.WriteLine(null, "Category");
Assert.Equal(3, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void WriteLineCategoryTest2()
{
var listener = new TestTraceListener();
listener.Filter = new TestTraceFilter(false);
listener.WriteLine((object)"Message", "Category");
Assert.Equal(0, listener.GetCallCount(Method.WriteLine));
listener.Filter = new TestTraceFilter(true);
listener.WriteLine((object)"Message", null);
Assert.Equal(1, listener.GetCallCount(Method.WriteLine));
listener.WriteLine((object)"Message", "Category");
Assert.Equal(2, listener.GetCallCount(Method.WriteLine));
listener.WriteLine((object)null, "Category");
Assert.Equal(3, listener.GetCallCount(Method.WriteLine));
}
[Fact]
public void TraceDataTest()
{
var cache = new TraceEventCache();
var listener = new TestTextTraceListener();
listener.Filter = new TestTraceFilter(false);
listener.TraceData(cache, "Source", TraceEventType.Critical, 1, new object());
Assert.Equal(0, listener.WriteCount);
listener = new TestTextTraceListener();
listener.TraceData(cache, "Source", TraceEventType.Critical, 1, new object());
var expected = 2; // header and message.
Assert.Equal(expected, listener.WriteCount);
listener = new TestTextTraceListener();
listener.TraceData(cache, "Source", TraceEventType.Critical, 1, (object)null);
Assert.Equal(expected, listener.WriteCount);
}
[Fact]
public void TraceDataTest2()
{
var cache = new TraceEventCache();
var listener = new TestTextTraceListener();
listener.Filter = new TestTraceFilter(false);
listener.TraceData(cache, "Source", TraceEventType.Critical, 1, new object[0]);
Assert.Equal(0, listener.WriteCount);
listener = new TestTextTraceListener();
listener.TraceData(cache, "Source", TraceEventType.Critical, 1, (object[])null);
var expected = 2; // header and message.
Assert.Equal(expected, listener.WriteCount);
listener = new TestTextTraceListener();
listener.TraceData(cache, "Source", TraceEventType.Critical, 1, "Arg1", "Arg2");
Assert.Equal(expected, listener.WriteCount);
listener = new TestTextTraceListener();
listener.TraceData(cache, "Source", TraceEventType.Critical, 1, "Arg1", null);
Assert.Equal(expected, listener.WriteCount);
}
[Fact]
public void TraceEventTest()
{
var cache = new TraceEventCache();
var listener = new TestTextTraceListener();
listener.Filter = new TestTraceFilter(false);
listener.TraceEvent(cache, "Source", TraceEventType.Critical, 1);
Assert.Equal(0, listener.WriteCount);
listener = new TestTextTraceListener();
listener.TraceEvent(cache, "Source", TraceEventType.Critical, 1);
var expected = 2; // header and message.
Assert.Equal(expected, listener.WriteCount);
}
[Fact]
public void TraceEventTest2()
{
var cache = new TraceEventCache();
var listener = new TestTextTraceListener();
listener.Filter = new TestTraceFilter(false);
listener.TraceEvent(cache, "Source", TraceEventType.Critical, 1, "Format", "arg1");
Assert.Equal(0, listener.WriteCount);
listener = new TestTextTraceListener();
listener.TraceEvent(cache, "Source", TraceEventType.Critical, 1, "Format", "arg1");
var expected = 2; // header and message.
Assert.Equal(expected, listener.WriteCount);
}
[Theory]
[InlineData(TraceOptions.None, 0)]
[InlineData(TraceOptions.Timestamp, 1)]
[InlineData(TraceOptions.ProcessId | TraceOptions.ThreadId, 2)]
[InlineData(TraceOptions.DateTime | TraceOptions.Timestamp, 2)]
public void WriteFooterTest(TraceOptions opts, int flagCount)
{
var cache = new TraceEventCache();
var listener = new TestTextTraceListener();
listener.TraceOutputOptions = opts;
listener.Filter = new TestTraceFilter(false);
listener.TraceEvent(cache, "Source", TraceEventType.Critical, 1);
Assert.Equal(0, listener.WriteCount);
var baseExpected = 2; // header + message
var expected = baseExpected;
listener = new TestTextTraceListener();
listener.TraceOutputOptions = opts;
listener.TraceEvent(null, "Source", TraceEventType.Critical, 1);
Assert.Equal(expected, listener.WriteCount);
// Two calls to write per flag, one call for writing the indent, one for the message.
expected = baseExpected + flagCount * 2;
listener = new TestTextTraceListener();
listener.TraceOutputOptions = opts;
listener.TraceEvent(cache, "Source", TraceEventType.Critical, 1);
Assert.Equal(expected, listener.WriteCount);
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.ML.Data;
using Encog.ML.Train.Strategy.End;
namespace Encog.ML.Train.Strategy
{
/// <summary>
/// Stop early when validation set no longer improves.
///
/// Based on the following paper:
///
/// @techreport{Prechelt94c,
/// author = {Lutz Prechelt},
/// title = {{PROBEN1} --- {A} Set of Benchmarks and Benchmarking
/// Rules for Neural Network Training Algorithms},
/// institution = {Fakult\"at f\"ur Informatik, Universit\"at Karlsruhe},
/// year = {1994},
/// number = {21/94},
/// address = {D-76128 Karlsruhe, Germany},
/// month = sep,
/// note = {Anonymous FTP: /pub/pa\-pers/tech\-reports/1994/1994-21.ps.Z
/// on ftp.ira.uka.de},
/// }
///
/// </summary>
public class EarlyStoppingStrategy : IEndTrainingStrategy
{
/// <summary>
/// Alpha value, calculated for early stopping. Once "gl" is above alpha, training will stop.
/// </summary>
private readonly double _alpha;
private readonly double _minEfficiency;
/// <summary>
/// Validation strip length.
/// </summary>
private readonly int _stripLength;
/// <summary>
/// The test set.
/// </summary>
private readonly IMLDataSet _testSet;
/// <summary>
/// The validation set.
/// </summary>
private readonly IMLDataSet _validationSet;
/// <summary>
/// The error calculation.
/// </summary>
private IMLError _calc;
/// <summary>
/// eOpt value, calculated for early stopping.
/// The lowest validation error so far.
/// </summary>
private double _eOpt;
/// <summary>
/// gl value, calculated for early stopping.
/// </summary>
private double _gl;
/// <summary>
/// The last time the test set was checked.
/// </summary>
private int _lastCheck;
/// <summary>
/// Has training stopped.
/// </summary>
private bool _stop;
private double _stripEfficiency;
private double _stripOpt;
private double _stripTotal;
/// <summary>
/// Current test error.
/// </summary>
private double _testError;
/// <summary>
/// The trainer.
/// </summary>
private IMLTrain _train;
/// <summary>
/// Current training error.
/// </summary>
private double _trainingError;
/// <summary>
/// Current validation error.
/// </summary>
private double _validationError;
/// <summary>
/// Construct the early stopping strategy.
/// Use default operating parameters.
/// </summary>
/// <param name="theValidationSet">The validation set.</param>
/// <param name="theTestSet">The test set.</param>
public EarlyStoppingStrategy(IMLDataSet theValidationSet,
IMLDataSet theTestSet)
: this(theValidationSet, theTestSet, 5, 5, 0.1)
{
}
/// <summary>
/// Construct the early stopping strategy.
/// </summary>
/// <param name="theValidationSet">The validation set.</param>
/// <param name="theTestSet">The test set.</param>
/// <param name="theStripLength">The number of training set elements to validate.</param>
/// <param name="theAlpha">Stop once GL is below this value.</param>
/// <param name="theMinEfficiency">The minimum training efficiency to stop.</param>
public EarlyStoppingStrategy(IMLDataSet theValidationSet,
IMLDataSet theTestSet, int theStripLength, double theAlpha,
double theMinEfficiency)
{
_validationSet = theValidationSet;
_testSet = theTestSet;
_alpha = theAlpha;
_stripLength = theStripLength;
_minEfficiency = theMinEfficiency;
}
/// <summary>
/// The training error.
/// </summary>
public double TrainingError
{
get { return _trainingError; }
}
/// <summary>
/// The test error.
/// </summary>
public double TestError
{
get { return _testError; }
}
/// <summary>
/// The validation error.
/// </summary>
public double ValidationError
{
get { return _validationError; }
}
/// <summary>
/// The Opt.
/// </summary>
public double Opt
{
get { return _eOpt; }
}
/// <summary>
/// The GL.
/// </summary>
public double Gl
{
get { return _gl; }
}
/// <summary>
/// The strip length.
/// </summary>
public int StripLength
{
get { return _stripLength; }
}
/// <summary>
/// StripOpt.
/// </summary>
public double StripOpt
{
get { return _stripOpt; }
}
/// <summary>
/// The strip efficiency.
/// </summary>
public double StripEfficiency
{
get { return _stripEfficiency; }
}
/// <summary>
/// The minimum efficicency to allow before stopping.
/// </summary>
public double MinEfficiency
{
get { return _minEfficiency; }
}
#region IEndTrainingStrategy Members
/// <inheritdoc/>
public void Init(IMLTrain theTrain)
{
_train = theTrain;
_calc = (IMLError) _train.Method;
_eOpt = Double.PositiveInfinity;
_stripOpt = Double.PositiveInfinity;
_stop = false;
_lastCheck = 0;
}
/// <inheritdoc/>
public void PreIteration()
{
}
/// <inheritdoc/>
public void PostIteration()
{
_lastCheck++;
_trainingError = _train.Error;
_stripOpt = Math.Min(_stripOpt, _trainingError);
_stripTotal += _trainingError;
if (_lastCheck > _stripLength)
{
_validationError = _calc.CalculateError(_validationSet);
_testError = _calc.CalculateError(_testSet);
_eOpt = Math.Min(_validationError, _eOpt);
_gl = 100.0*((_validationError/_eOpt) - 1.0);
_stripEfficiency = (_stripTotal)
/(_stripLength*_stripOpt);
//System.out.println("eff=" + this.stripEfficiency + ", gl=" + this.gl);
// setup for next time
_stripTotal = 0;
_lastCheck = 0;
// should we stop?
_stop = (_gl > _alpha)
|| (_stripEfficiency < _minEfficiency);
}
}
/// <summary>
/// Returns true if we should stop.
/// </summary>
/// <returns>Returns true if we should stop.</returns>
public bool ShouldStop()
{
return _stop;
}
#endregion
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using PlayFab.Json.Utilities;
namespace PlayFab.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// </summary>
public class JsonTextWriter : JsonWriter
{
private readonly TextWriter _writer;
private Base64Encoder _base64Encoder;
private char _indentChar;
private int _indentation;
private char _quoteChar;
private bool _quoteName;
private Base64Encoder Base64Encoder
{
get
{
if (_base64Encoder == null)
_base64Encoder = new Base64Encoder(_writer);
return _base64Encoder;
}
}
/// <summary>
/// Gets or sets how many IndentChars to write for each level in the hierarchy when <see cref="Formatting"/> is set to <c>Formatting.Indented</c>.
/// </summary>
public int Indentation
{
get { return _indentation; }
set
{
if (value < 0)
throw new ArgumentException("Indentation value must be greater than 0.");
_indentation = value;
}
}
/// <summary>
/// Gets or sets which character to use to quote attribute values.
/// </summary>
public char QuoteChar
{
get { return _quoteChar; }
set
{
if (value != '"' && value != '\'')
throw new ArgumentException(@"Invalid JavaScript string quote character. Valid quote characters are ' and "".");
_quoteChar = value;
}
}
/// <summary>
/// Gets or sets which character to use for indenting when <see cref="Formatting"/> is set to <c>Formatting.Indented</c>.
/// </summary>
public char IndentChar
{
get { return _indentChar; }
set { _indentChar = value; }
}
/// <summary>
/// Gets or sets a value indicating whether object names will be surrounded with quotes.
/// </summary>
public bool QuoteName
{
get { return _quoteName; }
set { _quoteName = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class using the specified <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">The <c>TextWriter</c> to write to.</param>
public JsonTextWriter(TextWriter textWriter)
{
if (textWriter == null)
throw new ArgumentNullException("textWriter");
_writer = textWriter;
_quoteChar = '"';
_quoteName = true;
_indentChar = ' ';
_indentation = 2;
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public override void Flush()
{
_writer.Flush();
}
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public override void Close()
{
base.Close();
if (CloseOutput && _writer != null)
_writer.Close();
}
/// <summary>
/// Writes the beginning of a Json object.
/// </summary>
public override void WriteStartObject()
{
base.WriteStartObject();
_writer.Write("{");
}
/// <summary>
/// Writes the beginning of a Json array.
/// </summary>
public override void WriteStartArray()
{
base.WriteStartArray();
_writer.Write("[");
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public override void WriteStartConstructor(string name)
{
base.WriteStartConstructor(name);
_writer.Write("new ");
_writer.Write(name);
_writer.Write("(");
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected override void WriteEnd(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
_writer.Write("}");
break;
case JsonToken.EndArray:
_writer.Write("]");
break;
case JsonToken.EndConstructor:
_writer.Write(")");
break;
default:
throw new JsonWriterException("Invalid JsonToken: " + token);
}
}
/// <summary>
/// Writes the property name of a name/value pair on a Json object.
/// </summary>
/// <param name="name">The name of the property.</param>
public override void WritePropertyName(string name)
{
base.WritePropertyName(name);
JavaScriptUtils.WriteEscapedJavaScriptString(_writer, name, _quoteChar, _quoteName);
_writer.Write(':');
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected override void WriteIndent()
{
if (Formatting == Formatting.Indented)
{
_writer.Write(Environment.NewLine);
// levels of indentation multiplied by the indent count
int currentIndentCount = Top * _indentation;
for (int i = 0; i < currentIndentCount; i++)
{
_writer.Write(_indentChar);
}
}
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected override void WriteValueDelimiter()
{
_writer.Write(',');
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected override void WriteIndentSpace()
{
_writer.Write(' ');
}
private void WriteValueInternal(string value, JsonToken token)
{
_writer.Write(value);
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public override void WriteNull()
{
base.WriteNull();
WriteValueInternal(JsonConvert.Null, JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public override void WriteUndefined()
{
base.WriteUndefined();
WriteValueInternal(JsonConvert.Undefined, JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRaw(string json)
{
base.WriteRaw(json);
_writer.Write(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public override void WriteValue(string value)
{
base.WriteValue(value);
if (value == null)
WriteValueInternal(JsonConvert.Null, JsonToken.Null);
else
JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, true);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public override void WriteValue(int value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
//
public override void WriteValue(uint value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public override void WriteValue(long value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
//
public override void WriteValue(ulong value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public override void WriteValue(float value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public override void WriteValue(double value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public override void WriteValue(bool value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public override void WriteValue(short value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
//
public override void WriteValue(ushort value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public override void WriteValue(char value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public override void WriteValue(byte value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
//
public override void WriteValue(sbyte value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public override void WriteValue(decimal value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public override void WriteValue(DateTime value)
{
base.WriteValue(value);
JsonConvert.WriteDateTimeString(_writer, value);
}
/// <summary>
/// Writes a <see cref="T:Byte[]"/> value.
/// </summary>
/// <param name="value">The <see cref="T:Byte[]"/> value to write.</param>
public override void WriteValue(byte[] value)
{
base.WriteValue(value);
if (value != null)
{
_writer.Write(_quoteChar);
Base64Encoder.Encode(value, 0, value.Length);
Base64Encoder.Flush();
_writer.Write(_quoteChar);
}
}
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public override void WriteValue(DateTimeOffset value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Date);
}
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public override void WriteValue(Guid value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public override void WriteValue(TimeSpan value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Date);
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public override void WriteValue(Uri value)
{
base.WriteValue(value);
WriteValueInternal(JsonConvert.ToString(value), JsonToken.Date);
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public override void WriteComment(string text)
{
base.WriteComment(text);
_writer.Write("/*");
_writer.Write(text);
_writer.Write("*/");
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public override void WriteWhitespace(string ws)
{
base.WriteWhitespace(ws);
_writer.Write(ws);
}
}
}
#endif
| |
namespace Hqub.Lastfm
{
using Hqub.Lastfm.Cache;
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
class Request
{
class ResponseError
{
public int Error { get; set; }
public string Message { get; set; }
}
const string ROOT = "http://ws.audioscrobbler.com/2.0/";
const string ROOT_SSL = "https://ws.audioscrobbler.com/2.0/";
private string method;
private Session session;
private HttpClient client;
private IRequestCache cache;
public RequestParameters Parameters { get; private set; }
public Request(string method, HttpClient client, Session session, IRequestCache cache)
{
this.method = method;
this.session = session;
this.client = client;
this.cache = cache ?? NullRequestCache.Default;
Parameters = new RequestParameters();
Parameters["method"] = this.method;
Parameters["api_key"] = this.session.ApiKey;
}
public void SetPagination(int limit, int limitDefault, int page, int pageDefault)
{
if (limit > 0 && limit != limitDefault)
{
Parameters["limit"] = limit.ToString();
}
if (page > 0 && page != pageDefault)
{
Parameters["page"] = page.ToString();
}
}
public async Task<XDocument> GetAsync(CancellationToken ct = default, bool secure = false)
{
try
{
var query = Parameters.ToString();
if (await cache.TryGetCachedItem(query, out Stream stream).ConfigureAwait(false))
{
var result = GetXDocument(stream);
stream.Close();
return result;
}
var url = GetRequestString(secure, query);
using (var response = await client.GetAsync(url, ct).ConfigureAwait(false))
{
stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
throw CreateServiceException(stream, response);
}
await cache.Add(query, stream).ConfigureAwait(false);
// Reset the stream position, in case the cache forgot to do so!
stream.Position = 0;
return GetXDocument(stream);
}
}
catch (Exception e)
{
throw e;
}
}
public async Task<XDocument> PostAsync(CancellationToken ct = default)
{
if (session.Authenticated)
{
Parameters["sk"] = session.SessionKey;
Sign();
}
var content = new FormUrlEncodedContent(Parameters);
using (var response = await client.PostAsync(new Uri(ROOT_SSL), content, ct).ConfigureAwait(false))
{
var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
throw CreateServiceException(stream, response);
}
return GetXDocument(stream);
}
}
internal void EnsureAuthenticated()
{
if (!session.Authenticated)
{
throw new NotAuthenticatedException();
}
}
internal void Sign()
{
var sb = new StringBuilder();
foreach (var item in Parameters)
{
sb.Append(item.Key);
sb.Append(item.Value);
}
sb.Append(session.ApiSecret);
Parameters["api_sig"] = MD5.ComputeHash(sb.ToString());
}
#region Helper
private string GetRequestString(bool secure, string query = null)
{
string url = secure ? ROOT_SSL : ROOT;
return string.IsNullOrEmpty(query) ? url : url + "?" + query;
}
private XDocument GetXDocument(Stream stream)
{
TextReader treader = new StreamReader(stream);
var settings = new XmlReaderSettings();
if (IsSearchRequest())
{
treader = FixOpenSearchNamespace(treader.ReadToEnd());
var schema = new XmlSchema();
schema.Namespaces.Add("opensearch", "http://a9.com/-/spec/opensearch/1.1/");
settings.Schemas.Add(schema);
}
var xreader = XmlReader.Create(treader, settings);
return XDocument.Load(xreader);
}
private ServiceException CreateServiceException(Stream stream, HttpResponseMessage response)
{
var doc = GetXDocument(stream);
var e = ParseResponseError(doc);
return new ServiceException(method, e.Error, response.StatusCode, e.Message ?? response.ReasonPhrase);
}
private ResponseError ParseResponseError(XDocument doc)
{
var e = doc.Descendants("lfm").FirstOrDefault();
string status = e.HasAttributes ? e.Attribute("status").Value : string.Empty;
var re = new ResponseError();
if (status == "failed")
{
var error = e.Element("error");
if (error != null)
{
re.Error = int.Parse(error.Attribute("code").Value);
re.Message = error.Value;
}
}
return re;
}
private bool IsSearchRequest()
{
return method.EndsWith(".search");
}
/// <summary>
/// Since last.fm doesn't set the opensearch namespace, add it manually.
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
private TextReader FixOpenSearchNamespace(string xml)
{
if (xml.Contains("xmlns:opensearch="))
{
return new StringReader(xml);
}
int i = xml.IndexOf("<results");
if (i < 0)
{
throw new Exception("Search response has unknown XML format.");
}
return new StringReader(xml.Insert(i + 8, " xmlns:opensearch=\"http://a9.com/-/spec/opensearch/1.1/\""));
}
#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 JYaas.API.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Globalization;
using System.IO;
using System.Text;
using ServiceStack.Text.Common;
namespace ServiceStack.Text.Json
{
internal class JsonTypeSerializer
: ITypeSerializer
{
public static ITypeSerializer Instance = new JsonTypeSerializer();
public bool IncludeNullValues
{
get { return JsConfig.IncludeNullValues; }
}
public string TypeAttrInObject
{
get { return JsConfig.JsonTypeAttrInObject; }
}
internal static string GetTypeAttrInObject(string typeAttr)
{
return string.Format("{{\"{0}\":", typeAttr);
}
public static readonly bool[] WhiteSpaceFlags = new bool[' ' + 1];
static JsonTypeSerializer()
{
WhiteSpaceFlags[' '] = true;
WhiteSpaceFlags['\t'] = true;
WhiteSpaceFlags['\r'] = true;
WhiteSpaceFlags['\n'] = true;
}
public WriteObjectDelegate GetWriteFn<T>()
{
return JsonWriter<T>.WriteFn();
}
public WriteObjectDelegate GetWriteFn(Type type)
{
return JsonWriter.GetWriteFn(type);
}
public TypeInfo GetTypeInfo(Type type)
{
return JsonWriter.GetTypeInfo(type);
}
/// <summary>
/// Shortcut escape when we're sure value doesn't contain any escaped chars
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
public void WriteRawString(TextWriter writer, string value)
{
writer.Write(JsWriter.QuoteChar);
writer.Write(value);
writer.Write(JsWriter.QuoteChar);
}
public void WritePropertyName(TextWriter writer, string value)
{
if (JsState.WritingKeyCount > 0)
{
writer.Write(JsWriter.EscapedQuoteString);
writer.Write(value);
writer.Write(JsWriter.EscapedQuoteString);
}
else
{
WriteRawString(writer, value);
}
}
public void WriteString(TextWriter writer, string value)
{
JsonUtils.WriteString(writer, value);
}
public void WriteBuiltIn(TextWriter writer, object value)
{
if (JsState.WritingKeyCount > 0 && !JsState.IsWritingValue) writer.Write(JsonUtils.QuoteChar);
WriteRawString(writer, value.ToString());
if (JsState.WritingKeyCount > 0 && !JsState.IsWritingValue) writer.Write(JsonUtils.QuoteChar);
}
public void WriteObjectString(TextWriter writer, object value)
{
JsonUtils.WriteString(writer, value != null ? value.ToString() : null);
}
public void WriteFormattableObjectString(TextWriter writer, object value)
{
var formattable = value as IFormattable;
JsonUtils.WriteString(writer, formattable != null ? formattable.ToString(null, CultureInfo.InvariantCulture) : null);
}
public void WriteException(TextWriter writer, object value)
{
WriteString(writer, ((Exception)value).Message);
}
public void WriteDateTime(TextWriter writer, object oDateTime)
{
writer.Write(JsWriter.QuoteString);
DateTimeSerializer.WriteWcfJsonDate(writer, (DateTime)oDateTime);
writer.Write(JsWriter.QuoteString);
}
public void WriteNullableDateTime(TextWriter writer, object dateTime)
{
if (dateTime == null)
writer.Write(JsonUtils.Null);
else
WriteDateTime(writer, dateTime);
}
public void WriteDateTimeOffset(TextWriter writer, object oDateTimeOffset)
{
writer.Write(JsWriter.QuoteString);
DateTimeSerializer.WriteWcfJsonDateTimeOffset(writer, (DateTimeOffset)oDateTimeOffset);
writer.Write(JsWriter.QuoteString);
}
public void WriteNullableDateTimeOffset(TextWriter writer, object dateTimeOffset)
{
if (dateTimeOffset == null)
writer.Write(JsonUtils.Null);
else
WriteDateTimeOffset(writer, dateTimeOffset);
}
public void WriteTimeSpan(TextWriter writer, object oTimeSpan)
{
var stringValue = JsConfig.TimeSpanHandler == JsonTimeSpanHandler.StandardFormat
? oTimeSpan.ToString()
: DateTimeSerializer.ToXsdTimeSpanString((TimeSpan)oTimeSpan);
WriteRawString(writer, stringValue);
}
public void WriteNullableTimeSpan(TextWriter writer, object oTimeSpan)
{
if (oTimeSpan == null) return;
WriteTimeSpan(writer, ((TimeSpan?)oTimeSpan).Value);
}
public void WriteGuid(TextWriter writer, object oValue)
{
WriteRawString(writer, ((Guid)oValue).ToString("N"));
}
public void WriteNullableGuid(TextWriter writer, object oValue)
{
if (oValue == null) return;
WriteRawString(writer, ((Guid)oValue).ToString("N"));
}
public void WriteBytes(TextWriter writer, object oByteValue)
{
if (oByteValue == null) return;
WriteRawString(writer, Convert.ToBase64String((byte[])oByteValue));
}
public void WriteChar(TextWriter writer, object charValue)
{
if (charValue == null)
writer.Write(JsonUtils.Null);
else
WriteRawString(writer, ((char)charValue).ToString());
}
public void WriteByte(TextWriter writer, object byteValue)
{
if (byteValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((byte)byteValue);
}
public void WriteInt16(TextWriter writer, object intValue)
{
if (intValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((short)intValue);
}
public void WriteUInt16(TextWriter writer, object intValue)
{
if (intValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((ushort)intValue);
}
public void WriteInt32(TextWriter writer, object intValue)
{
if (intValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((int)intValue);
}
public void WriteUInt32(TextWriter writer, object uintValue)
{
if (uintValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((uint)uintValue);
}
public void WriteInt64(TextWriter writer, object integerValue)
{
if (integerValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write((long)integerValue);
}
public void WriteUInt64(TextWriter writer, object ulongValue)
{
if (ulongValue == null)
{
writer.Write(JsonUtils.Null);
}
else
writer.Write((ulong)ulongValue);
}
public void WriteBool(TextWriter writer, object boolValue)
{
if (boolValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write(((bool)boolValue) ? JsonUtils.True : JsonUtils.False);
}
public void WriteFloat(TextWriter writer, object floatValue)
{
if (floatValue == null)
writer.Write(JsonUtils.Null);
else
{
var floatVal = (float)floatValue;
if (Equals(floatVal, float.MaxValue) || Equals(floatVal, float.MinValue))
writer.Write(floatVal.ToString("r", CultureInfo.InvariantCulture));
else
writer.Write(floatVal.ToString(CultureInfo.InvariantCulture));
}
}
public void WriteDouble(TextWriter writer, object doubleValue)
{
if (doubleValue == null)
writer.Write(JsonUtils.Null);
else
{
var doubleVal = (double)doubleValue;
if (Equals(doubleVal, double.MaxValue) || Equals(doubleVal, double.MinValue))
writer.Write(doubleVal.ToString("r", CultureInfo.InvariantCulture));
else
writer.Write(doubleVal.ToString(CultureInfo.InvariantCulture));
}
}
public void WriteDecimal(TextWriter writer, object decimalValue)
{
if (decimalValue == null)
writer.Write(JsonUtils.Null);
else
writer.Write(((decimal)decimalValue).ToString(CultureInfo.InvariantCulture));
}
public void WriteEnum(TextWriter writer, object enumValue)
{
if (enumValue == null) return;
if (GetTypeInfo(enumValue.GetType()).IsNumeric)
JsWriter.WriteEnumFlags(writer, enumValue);
else
WriteRawString(writer, enumValue.ToString());
}
public void WriteEnumFlags(TextWriter writer, object enumFlagValue)
{
JsWriter.WriteEnumFlags(writer, enumFlagValue);
}
public void WriteLinqBinary(TextWriter writer, object linqBinaryValue)
{
#if !MONOTOUCH && !SILVERLIGHT && !XBOX && !ANDROID
WriteRawString(writer, Convert.ToBase64String(((System.Data.Linq.Binary)linqBinaryValue).ToArray()));
#endif
}
public ParseStringDelegate GetParseFn<T>()
{
return JsonReader.Instance.GetParseFn<T>();
}
public ParseStringDelegate GetParseFn(Type type)
{
return JsonReader.GetParseFn(type);
}
public string ParseRawString(string value)
{
return value;
}
public string ParseString(string value)
{
return string.IsNullOrEmpty(value) ? value : ParseRawString(value);
}
internal static bool IsEmptyMap(string value, int i = 1)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
if (value.Length == i) return true;
return value[i++] == JsWriter.MapEndChar;
}
internal static string ParseString(string json, ref int index)
{
var jsonLength = json.Length;
if (json[index] != JsonUtils.QuoteChar)
throw new Exception("Invalid unquoted string starting with: " + json.SafeSubstring(50));
var startIndex = ++index;
do
{
char c = json[index];
if (c == JsonUtils.QuoteChar) break;
if (c != JsonUtils.EscapeChar) continue;
c = json[index++];
if (c == 'u')
{
index += 4;
}
} while (index++ < jsonLength);
index++;
return json.Substring(startIndex, Math.Min(index, jsonLength) - startIndex - 1);
}
public string UnescapeString(string value)
{
var i = 0;
return UnEscapeJsonString(value, ref i);
}
public string UnescapeSafeString(string value)
{
if (string.IsNullOrEmpty(value)) return value;
return value[0] == JsonUtils.QuoteChar && value[value.Length - 1] == JsonUtils.QuoteChar
? value.Substring(1, value.Length - 2)
: value;
//if (value[0] != JsonUtils.QuoteChar)
// throw new Exception("Invalid unquoted string starting with: " + value.SafeSubstring(50));
//return value.Substring(1, value.Length - 2);
}
static readonly char[] IsSafeJsonChars = new[] { JsonUtils.QuoteChar, JsonUtils.EscapeChar };
internal static string ParseJsonString(string json, ref int index)
{
for (; index < json.Length; index++) { var ch = json[index]; if (ch >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[ch]) break; } //Whitespace inline
return UnEscapeJsonString(json, ref index);
}
private static string UnEscapeJsonString(string json, ref int index)
{
if (string.IsNullOrEmpty(json)) return json;
var jsonLength = json.Length;
var firstChar = json[index];
if (firstChar == JsonUtils.QuoteChar)
{
index++;
//MicroOp: See if we can short-circuit evaluation (to avoid StringBuilder)
var strEndPos = json.IndexOfAny(IsSafeJsonChars, index);
if (strEndPos == -1) return json.Substring(index, jsonLength - index);
if (json[strEndPos] == JsonUtils.QuoteChar)
{
var potentialValue = json.Substring(index, strEndPos - index);
index = strEndPos + 1;
return potentialValue;
}
}
return Unescape(json);
}
public static string Unescape(string input)
{
var length = input.Length;
int start = 0;
int count = 0;
StringBuilder output = new StringBuilder(length);
for ( ; count < length; )
{
if (input[count] == JsonUtils.QuoteChar)
{
if (start != count)
{
output.Append(input, start, count - start);
}
count++;
start = count;
continue;
}
if (input[count] == JsonUtils.EscapeChar)
{
if (start != count)
{
output.Append(input, start, count - start);
}
start = count;
count++;
if (count >= length) continue;
//we will always be parsing an escaped char here
var c = input[count];
switch (c)
{
case 'a':
output.Append('\a');
count++;
break;
case 'b':
output.Append('\b');
count++;
break;
case 'f':
output.Append('\f');
count++;
break;
case 'n':
output.Append('\n');
count++;
break;
case 'r':
output.Append('\r');
count++;
break;
case 'v':
output.Append('\v');
count++;
break;
case 't':
output.Append('\t');
count++;
break;
case 'u':
if (count + 4 < length)
{
var unicodeString = input.Substring(count+1, 4);
var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber);
output.Append(JsonTypeSerializer.ConvertFromUtf32((int) unicodeIntVal));
count += 5;
}
else
{
output.Append(c);
}
break;
case 'x':
if (count + 4 < length)
{
var unicodeString = input.Substring(count+1, 4);
var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber);
output.Append(JsonTypeSerializer.ConvertFromUtf32((int) unicodeIntVal));
count += 5;
}
else
if (count + 2 < length)
{
var unicodeString = input.Substring(count+1, 2);
var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber);
output.Append(JsonTypeSerializer.ConvertFromUtf32((int) unicodeIntVal));
count += 3;
}
else
{
output.Append(input, start, count - start);
}
break;
default:
output.Append(c);
count++;
break;
}
start = count;
}
else
{
count++;
}
}
output.Append(input, start, length - start);
return output.ToString();
}
/// <summary>
/// Given a character as utf32, returns the equivalent string provided that the character
/// is legal json.
/// </summary>
/// <param name="utf32"></param>
/// <returns></returns>
public static string ConvertFromUtf32(int utf32)
{
if (utf32 < 0 || utf32 > 0x10FFFF)
throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF.");
if (utf32 < 0x10000)
return new string((char)utf32, 1);
utf32 -= 0x10000;
return new string(new[] {(char) ((utf32 >> 10) + 0xD800),
(char) (utf32 % 0x0400 + 0xDC00)});
}
public string EatTypeValue(string value, ref int i)
{
return EatValue(value, ref i);
}
public bool EatMapStartChar(string value, ref int i)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
return value[i++] == JsWriter.MapStartChar;
}
public string EatMapKey(string value, ref int i)
{
var valueLength = value.Length;
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
var tokenStartPos = i;
var valueChar = value[i];
var withinQuotes = false;
var endsToEat = 1;
switch (valueChar)
{
//If we are at the end, return.
case JsWriter.ItemSeperator:
case JsWriter.MapEndChar:
return null;
//Is Within Quotes, i.e. "..."
case JsWriter.QuoteChar:
return ParseString(value, ref i);
}
//Is Value
while (++i < valueLength)
{
valueChar = value[i];
if (valueChar == JsWriter.ItemSeperator
//If it doesn't have quotes it's either a keyword or number so also has a ws boundary
|| (valueChar < WhiteSpaceFlags.Length && WhiteSpaceFlags[valueChar])
)
{
break;
}
}
return value.Substring(tokenStartPos, i - tokenStartPos);
}
public bool EatMapKeySeperator(string value, ref int i)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
if (value.Length == i) return false;
return value[i++] == JsWriter.MapKeySeperator;
}
public bool EatItemSeperatorOrMapEndChar(string value, ref int i)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
if (i == value.Length) return false;
var success = value[i] == JsWriter.ItemSeperator
|| value[i] == JsWriter.MapEndChar;
i++;
if (success)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
}
return success;
}
public void EatWhitespace(string value, ref int i)
{
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
}
public string EatValue(string value, ref int i)
{
var valueLength = value.Length;
if (i == valueLength) return null;
for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline
if (i == valueLength) return null;
var tokenStartPos = i;
var valueChar = value[i];
var withinQuotes = false;
var endsToEat = 1;
switch (valueChar)
{
//If we are at the end, return.
case JsWriter.ItemSeperator:
case JsWriter.MapEndChar:
return null;
//Is Within Quotes, i.e. "..."
case JsWriter.QuoteChar:
return ParseString(value, ref i);
//Is Type/Map, i.e. {...}
case JsWriter.MapStartChar:
while (++i < valueLength && endsToEat > 0)
{
valueChar = value[i];
if (valueChar == JsonUtils.EscapeChar)
{
i++;
continue;
}
if (valueChar == JsWriter.QuoteChar)
withinQuotes = !withinQuotes;
if (withinQuotes)
continue;
if (valueChar == JsWriter.MapStartChar)
endsToEat++;
if (valueChar == JsWriter.MapEndChar)
endsToEat--;
}
return value.Substring(tokenStartPos, i - tokenStartPos);
//Is List, i.e. [...]
case JsWriter.ListStartChar:
while (++i < valueLength && endsToEat > 0)
{
valueChar = value[i];
if (valueChar == JsonUtils.EscapeChar)
{
i++;
continue;
}
if (valueChar == JsWriter.QuoteChar)
withinQuotes = !withinQuotes;
if (withinQuotes)
continue;
if (valueChar == JsWriter.ListStartChar)
endsToEat++;
if (valueChar == JsWriter.ListEndChar)
endsToEat--;
}
return value.Substring(tokenStartPos, i - tokenStartPos);
}
//Is Value
while (++i < valueLength)
{
valueChar = value[i];
if (valueChar == JsWriter.ItemSeperator
|| valueChar == JsWriter.MapEndChar
//If it doesn't have quotes it's either a keyword or number so also has a ws boundary
|| (valueChar < WhiteSpaceFlags.Length && WhiteSpaceFlags[valueChar])
)
{
break;
}
}
var strValue = value.Substring(tokenStartPos, i - tokenStartPos);
return strValue == JsonUtils.Null ? null : strValue;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace Azure.Data.Tables.Queryable
{
internal class ExpressionWriter : LinqExpressionVisitor
{
internal readonly StringBuilder _builder;
private readonly Stack<Expression> _expressionStack;
private bool _cantTranslateExpression;
protected ExpressionWriter()
{
_builder = new StringBuilder();
_expressionStack = new Stack<Expression>();
_expressionStack.Push(null);
}
internal static string ExpressionToString(Expression e)
{
ExpressionWriter ew = new ExpressionWriter();
return ew.ConvertExpressionToString(e);
}
internal string ConvertExpressionToString(Expression e)
{
string serialized = Translate(e);
if (_cantTranslateExpression)
{
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCantTranslateExpression, e.ToString()));
}
return serialized;
}
internal override Expression Visit(Expression exp)
{
_expressionStack.Push(exp);
Expression result = base.Visit(exp);
_expressionStack.Pop();
return result;
}
internal override Expression VisitMethodCall(MethodCallExpression m)
{
if (m.Method == ReflectionUtil.DictionaryGetItemMethodInfo && m.Arguments.Count == 1 && m.Arguments[0] is ConstantExpression ce)
{
_builder.Append(ce.Value as string);
}
else
{
return base.VisitMethodCall(m);
}
return m;
}
internal override Expression VisitMemberAccess(MemberExpression m)
{
if (m.Member is FieldInfo)
{
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCantReferToPublicField, m.Member.Name));
}
Expression e = Visit(m.Expression);
if (m.Member.Name == "Value" && m.Member.DeclaringType.IsGenericType
&& m.Member.DeclaringType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return m;
}
if (!IsInputReference(e) && e.NodeType != ExpressionType.Convert && e.NodeType != ExpressionType.ConvertChecked)
{
_builder.Append(UriHelper.FORWARDSLASH);
}
_builder.Append(TranslateMemberName(m.Member.Name));
return m;
}
internal override Expression VisitConstant(ConstantExpression c)
{
string result;
if (c.Value == null)
{
_builder.Append(UriHelper.NULL);
return c;
}
else if (!ClientConvert.TryKeyPrimitiveToString(c.Value, out result))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ALinqCouldNotConvert, c.Value));
}
Debug.Assert(result != null, "result != null");
// A Difference from WCF Data Services is that we will escape later when we execute the fully parsed query.
_builder.Append(result);
return c;
}
internal override Expression VisitUnary(UnaryExpression u)
{
switch (u.NodeType)
{
case ExpressionType.Not:
_builder.Append(UriHelper.NOT);
_builder.Append(UriHelper.SPACE);
VisitOperand(u.Operand);
break;
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
_builder.Append(UriHelper.SPACE);
_builder.Append(TranslateOperator(u.NodeType));
VisitOperand(u.Operand);
break;
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.UnaryPlus:
break;
default:
_cantTranslateExpression = true;
break;
}
return u;
}
internal override Expression VisitBinary(BinaryExpression b)
{
VisitOperand(b.Left);
_builder.Append(UriHelper.SPACE);
string operatorString = TranslateOperator(b.NodeType);
if (string.IsNullOrEmpty(operatorString))
{
_cantTranslateExpression = true;
}
else
{
_builder.Append(operatorString);
}
_builder.Append(UriHelper.SPACE);
VisitOperand(b.Right);
return b;
}
internal override Expression VisitParameter(ParameterExpression p)
{
return p;
}
private static bool IsInputReference(Expression exp)
{
return exp is ParameterExpression;
}
private void VisitOperand(Expression e)
{
if (e is BinaryExpression || e is UnaryExpression)
{
if (e is UnaryExpression unary && unary.NodeType == ExpressionType.TypeAs)
{
Visit(unary.Operand);
}
else
{
_builder.Append(UriHelper.LEFTPAREN);
Visit(e);
_builder.Append(UriHelper.RIGHTPAREN);
}
}
else
{
Visit(e);
}
}
private string Translate(Expression e)
{
Visit(e);
return _builder.ToString();
}
protected virtual string TranslateMemberName(string memberName)
{
return memberName;
}
protected virtual string TranslateOperator(ExpressionType type)
{
switch (type)
{
case ExpressionType.AndAlso:
case ExpressionType.And:
return UriHelper.AND;
case ExpressionType.OrElse:
case ExpressionType.Or:
return UriHelper.OR;
case ExpressionType.Equal:
return UriHelper.EQ;
case ExpressionType.NotEqual:
return UriHelper.NE;
case ExpressionType.LessThan:
return UriHelper.LT;
case ExpressionType.LessThanOrEqual:
return UriHelper.LE;
case ExpressionType.GreaterThan:
return UriHelper.GT;
case ExpressionType.GreaterThanOrEqual:
return UriHelper.GE;
case ExpressionType.Add:
case ExpressionType.AddChecked:
return UriHelper.ADD;
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
return UriHelper.SUB;
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return UriHelper.MUL;
case ExpressionType.Divide:
return UriHelper.DIV;
case ExpressionType.Modulo:
return UriHelper.MOD;
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
return UriHelper.NEGATE;
case ExpressionType.ArrayIndex:
case ExpressionType.Power:
case ExpressionType.Coalesce:
case ExpressionType.ExclusiveOr:
case ExpressionType.LeftShift:
case ExpressionType.RightShift:
default:
return null;
}
}
}
}
| |
//---------------------------------------------------------------------
// Authors: Oisin Grehan, jachymko
//
// Description: Interfaces and Classes needed to support querying of
// the Global Assembly Cache
//
// Creation Date: Jan 31, 2007
// Modifed: UCOMIStream -> IStream (UCOMIStream deprecated in 2.0)
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using Pscx.Interop;
// Source: Microsoft KB Article KB317540
// with modifications by oisin.
/*
SUMMARY
The native code application programming interfaces (APIs) that allow you to interact with the Global Assembly Cache (GAC) are not documented
in the .NET Framework Software Development Kit (SDK) documentation.
MORE INFORMATION
CAUTION: Do not use these APIs in your application to perform assembly binds or to test for the presence of assemblies or other run time,
development, or design-time operations. Only administrative tools and setup programs must use these APIs. If you use the GAC, this directly
exposes your application to assembly binding fragility or may cause your application to work improperly on future versions of the .NET
Framework.
The GAC stores assemblies that are shared across all applications on a computer. The actual storage location and structure of the GAC is
not documented and is subject to change in future versions of the .NET Framework and the Microsoft Windows operating system.
The only supported method to access assemblies in the GAC is through the APIs that are documented in this article.
Most applications do not have to use these APIs because the assembly binding is performed automatically by the common language runtime.
Only custom setup programs or management tools must use these APIs. Microsoft Windows Installer has native support for installing assemblies
to the GAC.
For more information about assemblies and the GAC, see the .NET Framework SDK.
Use the GAC API in the following scenarios:
When you install an assembly to the GAC.
When you remove an assembly from the GAC.
When you export an assembly from the GAC.
When you enumerate assemblies that are available in the GAC.
NOTE: CoInitialize(Ex) must be called before you use any of the functions and interfaces that are described in this specification.
*/
namespace Pscx.Reflection
{
public class AssemblyCache : IDisposable
{
private readonly IAssemblyCache _native;
#region GUID Definition
/// <summary>
/// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE
/// The assembly is referenced by an application that has been installed by using Windows Installer.
/// The szIdentifier field is set to MSI, and szNonCannonicalData is set to Windows Installer.
/// This scheme must only be used by Windows Installer itself.
/// </summary>
public static Guid FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID
{
get
{
return new Guid("8cedc215-ac4b-488b-93c0-a50a49cb2fb8");
}
}
/// <summary>
/// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE
///
/// </summary>
public static Guid FUSION_REFCOUNT_FILEPATH_GUID
{
get
{
return new Guid("b02f9d65-fb77-4f7a-afa5-b391309f11c9");
}
}
/// <summary>
/// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE
///
/// </summary>
public static Guid FUSION_REFCOUNT_OPAQUE_STRING_GUID
{
get
{
return new Guid("2ec93463-b0c3-45e1-8364-327e96aea856");
}
}
/// <summary>
/// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE
///
/// </summary>
public static Guid FUSION_REFCOUNT_MSI_GUID
{
get
{
return new Guid("25df0fc1-7f97-4070-add7-4b13bbfd7cb8");
}
}
#endregion
/// <summary>
/// Use this method as a start for the GAC API
/// </summary>
/// <returns>IAssemblyCache COM interface</returns>
public AssemblyCache()
{
NativeMethods.CreateAssemblyCache(out _native, 0);
}
public void Dispose()
{
Marshal.ReleaseComObject(_native);
}
public string QueryAssemblyPath(string displayName)
{
AssemblyInfo info = AssemblyInfo.Create();
if (NativeMethods.SUCCESS == _native.QueryAssemblyInfo(QueryAsmInfoFlag.Validate, displayName, ref info))
{
return info.pszCurrentAssemblyPathBuf;
}
return null;
}
public static string GlobalCachePath
{
get { return GetCachePath(AssemblyCacheType.Gac); }
}
public static IEnumerable<AssemblyName> GetGlobalAssemblies()
{
return GetGlobalAssemblies(null);
}
public static IEnumerable<AssemblyName> GetGlobalAssemblies(string partialName)
{
return GetAssemblies(partialName, AssemblyCacheType.Gac);
}
public static string DownloadCachePath
{
get { return GetCachePath(AssemblyCacheType.Download); }
}
public static IEnumerable<AssemblyName> GetDownloadedAssemblies()
{
return GetDownloadedAssemblies(null);
}
public static IEnumerable<AssemblyName> GetDownloadedAssemblies(string partialName)
{
return GetAssemblies(partialName, AssemblyCacheType.Download);
}
public static string NGenCachePath
{
get { return GetCachePath(AssemblyCacheType.NGen); }
}
public static IEnumerable<AssemblyName> GetNGenAssemblies()
{
return GetNGenAssemblies(null);
}
public static IEnumerable<AssemblyName> GetNGenAssemblies(string partialName)
{
return GetAssemblies(partialName, AssemblyCacheType.NGen);
}
public static IEnumerable<AssemblyName> GetAssemblies(AssemblyCacheType cacheType)
{
return GetAssemblies(null, cacheType);
}
public static IEnumerable<AssemblyName> GetAssemblies(string partialName, AssemblyCacheType cacheType)
{
IAssemblyEnum enumerator;
IAssemblyName assemblyName = null;
if (partialName != null)
{
assemblyName = AssemblyCache.CreateAssemblyName(partialName);
}
NativeMethods.CreateAssemblyEnum(out enumerator, IntPtr.Zero, assemblyName, cacheType, IntPtr.Zero);
return new AssemblyCacheSearcher(enumerator);
}
private static IAssemblyName CreateAssemblyName(string name)
{
IAssemblyName an;
// oisin: replaced 0x2 with CREATE_ASM_NAME_OBJ_FLAGS enum for clarity
NativeMethods.CreateAssemblyNameObject(out an, name,
CreateAssemblyNameFlags.SetDefaultValues, IntPtr.Zero);
return an;
}
private static string GetCachePath(AssemblyCacheType cache)
{
int bufferSize = NativeMethods.MAX_PATH;
StringBuilder buffer = new StringBuilder(bufferSize);
NativeMethods.GetCachePath(cache, buffer, ref bufferSize);
return buffer.ToString();
}
}
}
| |
/*
Copyright 2010 Eric Smith
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace TheLimberLambda.Utils
{
internal class PythonConverser : LineOrientedSocketConverser, INameBinder
{
private const string ShowPrefix = ">> ";
private readonly ScriptRuntime _ScriptRuntime;
private ScriptScope _ScriptScope;
#region Nested types
private class SocketConverserStream: Stream
{
private readonly Socket _Socket;
public SocketConverserStream(Socket socket)
{
_Socket = socket;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override long Length
{
get { throw new NotImplementedException(); }
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
_Socket.BeginSend(buffer, offset, count, SocketFlags.None, SentCallback, _Socket);
}
private static void SentCallback(IAsyncResult ar)
{
((Socket) ar.AsyncState).EndReceive(ar);
}
}
#endregion
internal PythonConverser(Socket socket, IEnumerable<NameBinding> nameBindings):
base(socket)
{
_ScriptRuntime = IronPython.Hosting.Python.CreateRuntime();
InitialiseScriptRuntime(socket);
BindScriptScopeNames(nameBindings);
}
private void BindScriptScopeNames(IEnumerable<NameBinding> nameBindings)
{
foreach (var binding in nameBindings)
_ScriptScope.SetVariable(binding.Name, binding.Target);
}
private void InitialiseScriptRuntime(Socket socket)
{
_ScriptRuntime.IO.SetOutput(new SocketConverserStream(socket), Encoding.ASCII);
_ScriptRuntime.IO.SetErrorOutput(new SocketConverserStream(socket), Encoding.ASCII);
_ScriptScope = _ScriptRuntime.CreateScope("py");
}
protected override void SomethingWasSaid(string whatWasSaid)
{
var scriptSource = _ScriptScope.Engine.CreateScriptSourceFromString(whatWasSaid);
ExecuteScriptInCurrentScope(scriptSource);
}
private void ExecuteScriptInCurrentScope(ScriptSource scriptSource)
{
try
{
object result = scriptSource.Execute(_ScriptScope);
if (result != null)
Show(result);
}
catch (Exception e)
{
ShowScriptException(e);
}
}
private void Show(object result)
{
if (WantToSeeAsList(result))
ShowAsList(result);
else
ShowSingle(result);
}
private static bool WantToSeeAsList(object result)
{
if (result == null)
throw new ArgumentNullException("result");
return !(result is string) && result is IEnumerable;
}
private void ShowSingle(object toShow)
{
SayWithPrefix(toShow);
}
private void ShowAsList(object toShow)
{
SayWithPrefix(Bracket(String.Join(", ", QuoteAll(RenderAsStrings(toShow)).ToArray())));
}
private void SayWithPrefix(object toSay)
{
Say(ShowPrefix + toSay);
}
private static object Bracket(string toBracket)
{
return "[" + toBracket + "]";
}
private static IEnumerable<string> QuoteAll(IEnumerable<string> toQuote)
{
return toQuote.Select(element => "\"" + element + "\"");
}
private static IEnumerable<string> RenderAsStrings(object toRender)
{
return ((IEnumerable) toRender).Cast<object>().Select(element => element.ToString());
}
private void ShowScriptException(Exception anException)
{
Say(anException.ToString());
}
#region INameBinder implementation
public void BindName(string name, object target)
{
_ScriptScope.SetVariable(name, target);
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using ShellUtil;
namespace SFML
{
namespace Graphics
{
////////////////////////////////////////////////////////////
/// <summary>
/// This class defines a sprite : texture, transformations,
/// color, and draw on screen
/// </summary>
////////////////////////////////////////////////////////////
public class Sprite : Transformable, Drawable
{
////////////////////////////////////////////////////////////
private Texture myTexture = null;
#region Imports
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr sfSprite_create();
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr sfSprite_copy(IntPtr Sprite);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern void sfSprite_destroy(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern void sfSprite_setColor(IntPtr CPointer, Color Color);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern Color sfSprite_getColor(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern void sfRenderWindow_drawSprite(
IntPtr CPointer, IntPtr Sprite, ref RenderStates.MarshalData states);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern void sfRenderTexture_drawSprite(
IntPtr CPointer, IntPtr Sprite, ref RenderStates.MarshalData states);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern void sfSprite_setTexture(IntPtr CPointer, IntPtr Texture, bool AdjustToNewSize);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern void sfSprite_setTextureRect(IntPtr CPointer, IntRect Rect);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern IntRect sfSprite_getTextureRect(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl)]
[SuppressUnmanagedCodeSecurity]
private static extern FloatRect sfSprite_getLocalBounds(IntPtr CPointer);
#endregion
/// <summary>
/// Default constructor
/// </summary>
////////////////////////////////////////////////////////////
public Sprite()
: base(sfSprite_create()) {}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the sprite from a source texture
/// </summary>
/// <param name="texture">Source texture to assign to the sprite</param>
////////////////////////////////////////////////////////////
public Sprite(Texture texture)
: base(sfSprite_create())
{
Texture = texture;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the sprite from a source texture
/// </summary>
/// <param name="texture">Source texture to assign to the sprite</param>
/// <param name="rectangle">Sub-rectangle of the texture to assign to the sprite</param>
////////////////////////////////////////////////////////////
public Sprite(Texture texture, IntRect rectangle)
: base(sfSprite_create())
{
Texture = texture;
TextureRect = rectangle;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the sprite from another sprite
/// </summary>
/// <param name="copy">Sprite to copy</param>
////////////////////////////////////////////////////////////
public Sprite(Sprite copy)
: base(sfSprite_copy(copy.CPointer))
{
Origin = copy.Origin;
Position = copy.Position;
Rotation = copy.Rotation;
Scale = copy.Scale;
Texture = copy.Texture;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Global color of the object
/// </summary>
////////////////////////////////////////////////////////////
public Color Color
{
get { return sfSprite_getColor(CPointer); }
set { sfSprite_setColor(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Source texture displayed by the sprite
/// </summary>
////////////////////////////////////////////////////////////
public Texture Texture
{
get { return this.myTexture; }
set
{
this.myTexture = value;
sfSprite_setTexture(CPointer, value != null ? value.CPointer : IntPtr.Zero, false);
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Sub-rectangle of the source image displayed by the sprite
/// </summary>
////////////////////////////////////////////////////////////
public IntRect TextureRect
{
get { return sfSprite_getTextureRect(CPointer); }
set { sfSprite_setTextureRect(CPointer, value); }
}
/// <summmary>
/// Draw the object to a render target
/// This is a pure virtual function that has to be implemented
/// by the derived class to define how the drawable should be
/// drawn.
/// </summmary>
/// <param name="target">Render target to draw to</param>
/// <param name="states">Current render states</param>
////////////////////////////////////////////////////////////
public void Draw(IRenderTarget target, RenderStates states)
{
states.Transform *= Transform;
RenderStates.MarshalData marshaledStates = states.Marshal();
if (target is RenderWindow)
{
sfRenderWindow_drawSprite(((RenderWindow)target).CPointer, CPointer, ref marshaledStates);
}
else if (target is RenderTexture)
{
sfRenderTexture_drawSprite(((RenderTexture)target).CPointer, CPointer, ref marshaledStates);
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get the local bounding rectangle of the entity.
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
/// </summary>
/// <returns>Local bounding rectangle of the entity</returns>
////////////////////////////////////////////////////////////
public FloatRect GetLocalBounds()
{
return sfSprite_getLocalBounds(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get the global bounding rectangle of the entity.
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
/// </summary>
/// <returns>Global bounding rectangle of the entity</returns>
////////////////////////////////////////////////////////////
public FloatRect GetGlobalBounds()
{
// we don't use the native getGlobalBounds function,
// because we override the object's transform
return Transform.TransformRect(GetLocalBounds());
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[Sprite]" + " Color(" + Color + ")" + " Texture(" + Texture + ")" + " TextureRect(" +
TextureRect + ")";
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
/// <summary>
/// Handle the destruction of the object
/// </summary>
/// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param>
////////////////////////////////////////////////////////////
protected override void Destroy(bool disposing)
{
sfSprite_destroy(CPointer);
}
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using gciv = Google.Cloud.Iam.V1;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Iap.V1
{
/// <summary>Settings for <see cref="IdentityAwareProxyAdminServiceClient"/> instances.</summary>
public sealed partial class IdentityAwareProxyAdminServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="IdentityAwareProxyAdminServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="IdentityAwareProxyAdminServiceSettings"/>.</returns>
public static IdentityAwareProxyAdminServiceSettings GetDefault() => new IdentityAwareProxyAdminServiceSettings();
/// <summary>
/// Constructs a new <see cref="IdentityAwareProxyAdminServiceSettings"/> object with default settings.
/// </summary>
public IdentityAwareProxyAdminServiceSettings()
{
}
private IdentityAwareProxyAdminServiceSettings(IdentityAwareProxyAdminServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
SetIamPolicySettings = existing.SetIamPolicySettings;
GetIamPolicySettings = existing.GetIamPolicySettings;
TestIamPermissionsSettings = existing.TestIamPermissionsSettings;
GetIapSettingsSettings = existing.GetIapSettingsSettings;
UpdateIapSettingsSettings = existing.UpdateIapSettingsSettings;
OnCopy(existing);
}
partial void OnCopy(IdentityAwareProxyAdminServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IdentityAwareProxyAdminServiceClient.SetIamPolicy</c> and
/// <c>IdentityAwareProxyAdminServiceClient.SetIamPolicyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings SetIamPolicySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IdentityAwareProxyAdminServiceClient.GetIamPolicy</c> and
/// <c>IdentityAwareProxyAdminServiceClient.GetIamPolicyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetIamPolicySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IdentityAwareProxyAdminServiceClient.TestIamPermissions</c> and
/// <c>IdentityAwareProxyAdminServiceClient.TestIamPermissionsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings TestIamPermissionsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IdentityAwareProxyAdminServiceClient.GetIapSettings</c> and
/// <c>IdentityAwareProxyAdminServiceClient.GetIapSettingsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetIapSettingsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IdentityAwareProxyAdminServiceClient.UpdateIapSettings</c> and
/// <c>IdentityAwareProxyAdminServiceClient.UpdateIapSettingsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateIapSettingsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="IdentityAwareProxyAdminServiceSettings"/> object.</returns>
public IdentityAwareProxyAdminServiceSettings Clone() => new IdentityAwareProxyAdminServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="IdentityAwareProxyAdminServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
public sealed partial class IdentityAwareProxyAdminServiceClientBuilder : gaxgrpc::ClientBuilderBase<IdentityAwareProxyAdminServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public IdentityAwareProxyAdminServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public IdentityAwareProxyAdminServiceClientBuilder()
{
UseJwtAccessWithScopes = IdentityAwareProxyAdminServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref IdentityAwareProxyAdminServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<IdentityAwareProxyAdminServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override IdentityAwareProxyAdminServiceClient Build()
{
IdentityAwareProxyAdminServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<IdentityAwareProxyAdminServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<IdentityAwareProxyAdminServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private IdentityAwareProxyAdminServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return IdentityAwareProxyAdminServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<IdentityAwareProxyAdminServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return IdentityAwareProxyAdminServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => IdentityAwareProxyAdminServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
IdentityAwareProxyAdminServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => IdentityAwareProxyAdminServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>IdentityAwareProxyAdminService client wrapper, for convenient use.</summary>
/// <remarks>
/// APIs for Identity-Aware Proxy Admin configurations.
/// </remarks>
public abstract partial class IdentityAwareProxyAdminServiceClient
{
/// <summary>
/// The default endpoint for the IdentityAwareProxyAdminService service, which is a host of "iap.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "iap.googleapis.com:443";
/// <summary>The default IdentityAwareProxyAdminService scopes.</summary>
/// <remarks>
/// The default IdentityAwareProxyAdminService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="IdentityAwareProxyAdminServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="IdentityAwareProxyAdminServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="IdentityAwareProxyAdminServiceClient"/>.</returns>
public static stt::Task<IdentityAwareProxyAdminServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new IdentityAwareProxyAdminServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="IdentityAwareProxyAdminServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="IdentityAwareProxyAdminServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="IdentityAwareProxyAdminServiceClient"/>.</returns>
public static IdentityAwareProxyAdminServiceClient Create() =>
new IdentityAwareProxyAdminServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="IdentityAwareProxyAdminServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="IdentityAwareProxyAdminServiceSettings"/>.</param>
/// <returns>The created <see cref="IdentityAwareProxyAdminServiceClient"/>.</returns>
internal static IdentityAwareProxyAdminServiceClient Create(grpccore::CallInvoker callInvoker, IdentityAwareProxyAdminServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient grpcClient = new IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient(callInvoker);
return new IdentityAwareProxyAdminServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC IdentityAwareProxyAdminService client</summary>
public virtual IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Sets the access control policy for an Identity-Aware Proxy protected
/// resource. Replaces any existing policy.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gciv::Policy SetIamPolicy(gciv::SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Sets the access control policy for an Identity-Aware Proxy protected
/// resource. Replaces any existing policy.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gciv::Policy> SetIamPolicyAsync(gciv::SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Sets the access control policy for an Identity-Aware Proxy protected
/// resource. Replaces any existing policy.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gciv::Policy> SetIamPolicyAsync(gciv::SetIamPolicyRequest request, st::CancellationToken cancellationToken) =>
SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the access control policy for an Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gciv::Policy GetIamPolicy(gciv::GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the access control policy for an Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gciv::Policy> GetIamPolicyAsync(gciv::GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the access control policy for an Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gciv::Policy> GetIamPolicyAsync(gciv::GetIamPolicyRequest request, st::CancellationToken cancellationToken) =>
GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns permissions that a caller has on the Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gciv::TestIamPermissionsResponse TestIamPermissions(gciv::TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns permissions that a caller has on the Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gciv::TestIamPermissionsResponse> TestIamPermissionsAsync(gciv::TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns permissions that a caller has on the Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gciv::TestIamPermissionsResponse> TestIamPermissionsAsync(gciv::TestIamPermissionsRequest request, st::CancellationToken cancellationToken) =>
TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the IAP settings on a particular IAP protected resource.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual IapSettings GetIapSettings(GetIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the IAP settings on a particular IAP protected resource.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<IapSettings> GetIapSettingsAsync(GetIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the IAP settings on a particular IAP protected resource.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<IapSettings> GetIapSettingsAsync(GetIapSettingsRequest request, st::CancellationToken cancellationToken) =>
GetIapSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates the IAP settings on a particular IAP protected resource. It
/// replaces all fields unless the `update_mask` is set.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual IapSettings UpdateIapSettings(UpdateIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the IAP settings on a particular IAP protected resource. It
/// replaces all fields unless the `update_mask` is set.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<IapSettings> UpdateIapSettingsAsync(UpdateIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the IAP settings on a particular IAP protected resource. It
/// replaces all fields unless the `update_mask` is set.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<IapSettings> UpdateIapSettingsAsync(UpdateIapSettingsRequest request, st::CancellationToken cancellationToken) =>
UpdateIapSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>IdentityAwareProxyAdminService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// APIs for Identity-Aware Proxy Admin configurations.
/// </remarks>
public sealed partial class IdentityAwareProxyAdminServiceClientImpl : IdentityAwareProxyAdminServiceClient
{
private readonly gaxgrpc::ApiCall<gciv::SetIamPolicyRequest, gciv::Policy> _callSetIamPolicy;
private readonly gaxgrpc::ApiCall<gciv::GetIamPolicyRequest, gciv::Policy> _callGetIamPolicy;
private readonly gaxgrpc::ApiCall<gciv::TestIamPermissionsRequest, gciv::TestIamPermissionsResponse> _callTestIamPermissions;
private readonly gaxgrpc::ApiCall<GetIapSettingsRequest, IapSettings> _callGetIapSettings;
private readonly gaxgrpc::ApiCall<UpdateIapSettingsRequest, IapSettings> _callUpdateIapSettings;
/// <summary>
/// Constructs a client wrapper for the IdentityAwareProxyAdminService service, with the specified gRPC client
/// and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="IdentityAwareProxyAdminServiceSettings"/> used within this client.
/// </param>
public IdentityAwareProxyAdminServiceClientImpl(IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient grpcClient, IdentityAwareProxyAdminServiceSettings settings)
{
GrpcClient = grpcClient;
IdentityAwareProxyAdminServiceSettings effectiveSettings = settings ?? IdentityAwareProxyAdminServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callSetIamPolicy = clientHelper.BuildApiCall<gciv::SetIamPolicyRequest, gciv::Policy>(grpcClient.SetIamPolicyAsync, grpcClient.SetIamPolicy, effectiveSettings.SetIamPolicySettings).WithGoogleRequestParam("resource", request => request.Resource);
Modify_ApiCall(ref _callSetIamPolicy);
Modify_SetIamPolicyApiCall(ref _callSetIamPolicy);
_callGetIamPolicy = clientHelper.BuildApiCall<gciv::GetIamPolicyRequest, gciv::Policy>(grpcClient.GetIamPolicyAsync, grpcClient.GetIamPolicy, effectiveSettings.GetIamPolicySettings).WithGoogleRequestParam("resource", request => request.Resource);
Modify_ApiCall(ref _callGetIamPolicy);
Modify_GetIamPolicyApiCall(ref _callGetIamPolicy);
_callTestIamPermissions = clientHelper.BuildApiCall<gciv::TestIamPermissionsRequest, gciv::TestIamPermissionsResponse>(grpcClient.TestIamPermissionsAsync, grpcClient.TestIamPermissions, effectiveSettings.TestIamPermissionsSettings).WithGoogleRequestParam("resource", request => request.Resource);
Modify_ApiCall(ref _callTestIamPermissions);
Modify_TestIamPermissionsApiCall(ref _callTestIamPermissions);
_callGetIapSettings = clientHelper.BuildApiCall<GetIapSettingsRequest, IapSettings>(grpcClient.GetIapSettingsAsync, grpcClient.GetIapSettings, effectiveSettings.GetIapSettingsSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetIapSettings);
Modify_GetIapSettingsApiCall(ref _callGetIapSettings);
_callUpdateIapSettings = clientHelper.BuildApiCall<UpdateIapSettingsRequest, IapSettings>(grpcClient.UpdateIapSettingsAsync, grpcClient.UpdateIapSettings, effectiveSettings.UpdateIapSettingsSettings).WithGoogleRequestParam("iap_settings.name", request => request.IapSettings?.Name);
Modify_ApiCall(ref _callUpdateIapSettings);
Modify_UpdateIapSettingsApiCall(ref _callUpdateIapSettings);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_SetIamPolicyApiCall(ref gaxgrpc::ApiCall<gciv::SetIamPolicyRequest, gciv::Policy> call);
partial void Modify_GetIamPolicyApiCall(ref gaxgrpc::ApiCall<gciv::GetIamPolicyRequest, gciv::Policy> call);
partial void Modify_TestIamPermissionsApiCall(ref gaxgrpc::ApiCall<gciv::TestIamPermissionsRequest, gciv::TestIamPermissionsResponse> call);
partial void Modify_GetIapSettingsApiCall(ref gaxgrpc::ApiCall<GetIapSettingsRequest, IapSettings> call);
partial void Modify_UpdateIapSettingsApiCall(ref gaxgrpc::ApiCall<UpdateIapSettingsRequest, IapSettings> call);
partial void OnConstruction(IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient grpcClient, IdentityAwareProxyAdminServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC IdentityAwareProxyAdminService client</summary>
public override IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient GrpcClient { get; }
partial void Modify_SetIamPolicyRequest(ref gciv::SetIamPolicyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetIamPolicyRequest(ref gciv::GetIamPolicyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_TestIamPermissionsRequest(ref gciv::TestIamPermissionsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetIapSettingsRequest(ref GetIapSettingsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateIapSettingsRequest(ref UpdateIapSettingsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Sets the access control policy for an Identity-Aware Proxy protected
/// resource. Replaces any existing policy.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gciv::Policy SetIamPolicy(gciv::SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SetIamPolicyRequest(ref request, ref callSettings);
return _callSetIamPolicy.Sync(request, callSettings);
}
/// <summary>
/// Sets the access control policy for an Identity-Aware Proxy protected
/// resource. Replaces any existing policy.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gciv::Policy> SetIamPolicyAsync(gciv::SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SetIamPolicyRequest(ref request, ref callSettings);
return _callSetIamPolicy.Async(request, callSettings);
}
/// <summary>
/// Gets the access control policy for an Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gciv::Policy GetIamPolicy(gciv::GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIamPolicyRequest(ref request, ref callSettings);
return _callGetIamPolicy.Sync(request, callSettings);
}
/// <summary>
/// Gets the access control policy for an Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gciv::Policy> GetIamPolicyAsync(gciv::GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIamPolicyRequest(ref request, ref callSettings);
return _callGetIamPolicy.Async(request, callSettings);
}
/// <summary>
/// Returns permissions that a caller has on the Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gciv::TestIamPermissionsResponse TestIamPermissions(gciv::TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_TestIamPermissionsRequest(ref request, ref callSettings);
return _callTestIamPermissions.Sync(request, callSettings);
}
/// <summary>
/// Returns permissions that a caller has on the Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gciv::TestIamPermissionsResponse> TestIamPermissionsAsync(gciv::TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_TestIamPermissionsRequest(ref request, ref callSettings);
return _callTestIamPermissions.Async(request, callSettings);
}
/// <summary>
/// Gets the IAP settings on a particular IAP protected resource.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override IapSettings GetIapSettings(GetIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIapSettingsRequest(ref request, ref callSettings);
return _callGetIapSettings.Sync(request, callSettings);
}
/// <summary>
/// Gets the IAP settings on a particular IAP protected resource.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<IapSettings> GetIapSettingsAsync(GetIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIapSettingsRequest(ref request, ref callSettings);
return _callGetIapSettings.Async(request, callSettings);
}
/// <summary>
/// Updates the IAP settings on a particular IAP protected resource. It
/// replaces all fields unless the `update_mask` is set.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override IapSettings UpdateIapSettings(UpdateIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateIapSettingsRequest(ref request, ref callSettings);
return _callUpdateIapSettings.Sync(request, callSettings);
}
/// <summary>
/// Updates the IAP settings on a particular IAP protected resource. It
/// replaces all fields unless the `update_mask` is set.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<IapSettings> UpdateIapSettingsAsync(UpdateIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateIapSettingsRequest(ref request, ref callSettings);
return _callUpdateIapSettings.Async(request, callSettings);
}
}
}
| |
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 help.Areas.HelpPage.ModelDescriptions;
using help.Areas.HelpPage.Models;
namespace help.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);
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Statistics.Algo
File: IPnLStatisticParameter.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Statistics
{
using System;
using Ecng.Serialization;
using StockSharp.Localization;
/// <summary>
/// The interface, describing statistic parameter, calculated based on the profit-loss value (maximal contraction, Sharp coefficient etc.).
/// </summary>
public interface IPnLStatisticParameter
{
/// <summary>
/// To add new data to the parameter.
/// </summary>
/// <param name="marketTime">The exchange time.</param>
/// <param name="pnl">The profit-loss value.</param>
void Add(DateTimeOffset marketTime, decimal pnl);
}
/// <summary>
/// The maximal profit value for the entire period.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str958Key)]
[DescriptionLoc(LocalizedStrings.Str959Key)]
[CategoryLoc(LocalizedStrings.PnLKey)]
public class MaxProfitParameter : BaseStatisticParameter<decimal>, IPnLStatisticParameter
{
/// <inheritdoc />
public void Add(DateTimeOffset marketTime, decimal pnl)
{
Value = Math.Max(Value, pnl);
}
}
/// <summary>
/// Maximum absolute drawdown during the whole period.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str960Key)]
[DescriptionLoc(LocalizedStrings.Str961Key)]
[CategoryLoc(LocalizedStrings.PnLKey)]
public class MaxDrawdownParameter : BaseStatisticParameter<decimal>, IPnLStatisticParameter
{
private decimal _maxEquity = decimal.MinValue;
/// <inheritdoc />
public override void Reset()
{
_maxEquity = decimal.MinValue;
base.Reset();
}
/// <inheritdoc />
public void Add(DateTimeOffset marketTime, decimal pnl)
{
_maxEquity = Math.Max(_maxEquity, pnl);
Value = Math.Max(Value, _maxEquity - pnl);
}
/// <inheritdoc />
public override void Save(SettingsStorage storage)
{
storage.SetValue("MaxEquity", _maxEquity);
base.Save(storage);
}
/// <inheritdoc />
public override void Load(SettingsStorage storage)
{
_maxEquity = storage.GetValue<decimal>("MaxEquity");
base.Load(storage);
}
}
/// <summary>
/// Maximum relative equity drawdown during the whole period.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str962Key)]
[DescriptionLoc(LocalizedStrings.Str963Key)]
[CategoryLoc(LocalizedStrings.PnLKey)]
public class MaxRelativeDrawdownParameter : BaseStatisticParameter<decimal>, IPnLStatisticParameter
{
private decimal _maxEquity = decimal.MinValue;
/// <inheritdoc />
public override void Reset()
{
_maxEquity = decimal.MinValue;
base.Reset();
}
/// <inheritdoc />
public void Add(DateTimeOffset marketTime, decimal pnl)
{
_maxEquity = Math.Max(_maxEquity, pnl);
var drawdown = _maxEquity - pnl;
Value = Math.Max(Value, _maxEquity != 0 ? drawdown / _maxEquity : 0);
}
/// <inheritdoc />
public override void Save(SettingsStorage storage)
{
storage.SetValue("MaxEquity", _maxEquity);
base.Save(storage);
}
/// <inheritdoc />
public override void Load(SettingsStorage storage)
{
_maxEquity = storage.GetValue<decimal>("MaxEquity");
base.Load(storage);
}
}
/// <summary>
/// Relative income for the whole time period.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str964Key)]
[DescriptionLoc(LocalizedStrings.Str965Key)]
[CategoryLoc(LocalizedStrings.PnLKey)]
public class ReturnParameter : BaseStatisticParameter<decimal>, IPnLStatisticParameter
{
private decimal _minEquity = decimal.MaxValue;
/// <inheritdoc />
public override void Reset()
{
_minEquity = decimal.MaxValue;
base.Reset();
}
/// <inheritdoc />
public void Add(DateTimeOffset marketTime, decimal pnl)
{
_minEquity = Math.Min(_minEquity, pnl);
var profit = pnl - _minEquity;
Value = Math.Max(Value, _minEquity != 0 ? profit / _minEquity : 0);
}
/// <inheritdoc />
public override void Save(SettingsStorage storage)
{
storage.SetValue("MinEquity", _minEquity);
base.Save(storage);
}
/// <inheritdoc />
public override void Load(SettingsStorage storage)
{
_minEquity = storage.GetValue<decimal>("MinEquity");
base.Load(storage);
}
}
/// <summary>
/// Recovery factor (net profit / maximum drawdown).
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str966Key)]
[DescriptionLoc(LocalizedStrings.Str967Key)]
[CategoryLoc(LocalizedStrings.PnLKey)]
public class RecoveryFactorParameter : BaseStatisticParameter<decimal>, IPnLStatisticParameter
{
private readonly MaxDrawdownParameter _maxDrawdown = new();
private readonly NetProfitParameter _netProfit = new();
/// <inheritdoc />
public override void Reset()
{
_maxDrawdown.Reset();
_netProfit.Reset();
base.Reset();
}
/// <inheritdoc />
public void Add(DateTimeOffset marketTime, decimal pnl)
{
_maxDrawdown.Add(marketTime, pnl);
_netProfit.Add(marketTime, pnl);
Value = _maxDrawdown.Value != 0 ? _netProfit.Value / _maxDrawdown.Value : 0;
}
/// <inheritdoc />
public override void Save(SettingsStorage storage)
{
storage.SetValue("MaxDrawdown", _maxDrawdown.Save());
storage.SetValue("NetProfit", _netProfit.Save());
base.Save(storage);
}
/// <inheritdoc />
public override void Load(SettingsStorage storage)
{
_maxDrawdown.Load(storage.GetValue<SettingsStorage>("MaxDrawdown"));
_netProfit.Load(storage.GetValue<SettingsStorage>("NetProfit"));
base.Load(storage);
}
}
/// <summary>
/// Net profit for whole time period.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str968Key)]
[DescriptionLoc(LocalizedStrings.Str969Key)]
[CategoryLoc(LocalizedStrings.PnLKey)]
public class NetProfitParameter : BaseStatisticParameter<decimal>, IPnLStatisticParameter
{
private decimal? _firstPnL;
/// <inheritdoc />
public override void Reset()
{
_firstPnL = null;
base.Reset();
}
/// <inheritdoc />
public void Add(DateTimeOffset marketTime, decimal pnl)
{
if (_firstPnL == null)
_firstPnL = pnl;
Value = pnl - _firstPnL.Value;
}
/// <inheritdoc />
public override void Save(SettingsStorage storage)
{
storage.SetValue("FirstPnL", _firstPnL);
base.Save(storage);
}
/// <inheritdoc />
public override void Load(SettingsStorage storage)
{
_firstPnL = storage.GetValue<decimal?>("FirstPnL");
base.Load(storage);
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudhsm-2014-05-30.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.CloudHSM
{
/// <summary>
/// Constants used for properties of type ClientVersion.
/// </summary>
public class ClientVersion : ConstantClass
{
/// <summary>
/// Constant v5_1 for ClientVersion
/// </summary>
public static readonly ClientVersion v5_1 = new ClientVersion("5.1");
/// <summary>
/// Constant v5_3 for ClientVersion
/// </summary>
public static readonly ClientVersion v5_3 = new ClientVersion("5.3");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ClientVersion(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ClientVersion FindValue(string value)
{
return FindValue<ClientVersion>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ClientVersion(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type CloudHsmObjectState.
/// </summary>
public class CloudHsmObjectState : ConstantClass
{
/// <summary>
/// Constant DEGRADED for CloudHsmObjectState
/// </summary>
public static readonly CloudHsmObjectState DEGRADED = new CloudHsmObjectState("DEGRADED");
/// <summary>
/// Constant READY for CloudHsmObjectState
/// </summary>
public static readonly CloudHsmObjectState READY = new CloudHsmObjectState("READY");
/// <summary>
/// Constant UPDATING for CloudHsmObjectState
/// </summary>
public static readonly CloudHsmObjectState UPDATING = new CloudHsmObjectState("UPDATING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public CloudHsmObjectState(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static CloudHsmObjectState FindValue(string value)
{
return FindValue<CloudHsmObjectState>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator CloudHsmObjectState(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type HsmStatus.
/// </summary>
public class HsmStatus : ConstantClass
{
/// <summary>
/// Constant DEGRADED for HsmStatus
/// </summary>
public static readonly HsmStatus DEGRADED = new HsmStatus("DEGRADED");
/// <summary>
/// Constant PENDING for HsmStatus
/// </summary>
public static readonly HsmStatus PENDING = new HsmStatus("PENDING");
/// <summary>
/// Constant RUNNING for HsmStatus
/// </summary>
public static readonly HsmStatus RUNNING = new HsmStatus("RUNNING");
/// <summary>
/// Constant SUSPENDED for HsmStatus
/// </summary>
public static readonly HsmStatus SUSPENDED = new HsmStatus("SUSPENDED");
/// <summary>
/// Constant TERMINATED for HsmStatus
/// </summary>
public static readonly HsmStatus TERMINATED = new HsmStatus("TERMINATED");
/// <summary>
/// Constant TERMINATING for HsmStatus
/// </summary>
public static readonly HsmStatus TERMINATING = new HsmStatus("TERMINATING");
/// <summary>
/// Constant UPDATING for HsmStatus
/// </summary>
public static readonly HsmStatus UPDATING = new HsmStatus("UPDATING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public HsmStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static HsmStatus FindValue(string value)
{
return FindValue<HsmStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator HsmStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SubscriptionType.
/// </summary>
public class SubscriptionType : ConstantClass
{
/// <summary>
/// Constant PRODUCTION for SubscriptionType
/// </summary>
public static readonly SubscriptionType PRODUCTION = new SubscriptionType("PRODUCTION");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public SubscriptionType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SubscriptionType FindValue(string value)
{
return FindValue<SubscriptionType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SubscriptionType(string value)
{
return FindValue(value);
}
}
}
| |
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. 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.
*
*/
#endregion
using System;
namespace Quartz.Impl.Triggers
{
/// <summary>
/// A concrete <see cref="ITrigger" /> that is used to fire a <see cref="IJobDetail" />
/// at a given moment in time, and optionally repeated at a specified interval.
/// </summary>
/// <seealso cref="ITrigger" />
/// <seealso cref="ICronTrigger" />
/// <author>James House</author>
/// <author>Contributions by Lieven Govaerts of Ebitec Nv, Belgium.</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
public class SimpleTriggerImpl : AbstractTrigger, ISimpleTrigger
{
/// <summary>
/// Used to indicate the 'repeat count' of the trigger is indefinite. Or in
/// other words, the trigger should repeat continually until the trigger's
/// ending timestamp.
/// </summary>
public const int RepeatIndefinitely = -1;
private const int YearToGiveupSchedulingAt = 2299;
private DateTimeOffset? nextFireTimeUtc; // Making a public property which called GetNextFireTime/SetNextFireTime would make the json attribute unnecessary
private DateTimeOffset? previousFireTimeUtc; // Making a public property which called GetPreviousFireTime/SetPreviousFireTime would make the json attribute unnecessary
private int repeatCount;
private TimeSpan repeatInterval = TimeSpan.Zero;
private int timesTriggered;
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> with no settings.
/// </summary>
public SimpleTriggerImpl()
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// not repeat.
/// </summary>
public SimpleTriggerImpl(string name) : this(name, SchedulerConstants.DefaultGroup)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// not repeat.
/// </summary>
public SimpleTriggerImpl(string name, string group)
: this(name, group, SystemTime.UtcNow(), null, 0, TimeSpan.Zero)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// repeat at the given interval the given number of times.
/// </summary>
public SimpleTriggerImpl(string name, int repeatCount, TimeSpan repeatInterval)
: this(name, null, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// repeat at the given interval the given number of times.
/// </summary>
public SimpleTriggerImpl(string name, string? group, int repeatCount, TimeSpan repeatInterval)
: this(name, group, SystemTime.UtcNow(), null, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and not repeat.
/// </summary>
public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc)
: this(name, null, startTimeUtc)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and not repeat.
/// </summary>
public SimpleTriggerImpl(string name, string? group, DateTimeOffset startTimeUtc)
: this(name, group, startTimeUtc, null, 0, TimeSpan.Zero)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and repeat at the given interval the given number of times, or until
/// the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
/// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc, int repeatCount, TimeSpan repeatInterval)
: this(name, null, startTimeUtc, endTimeUtc, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and repeat at the given interval the given number of times, or until
/// the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">The group.</param>
/// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
/// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(
string name,
string? group,
DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc,
int repeatCount,
TimeSpan repeatInterval)
: base(name, group)
{
StartTimeUtc = startTimeUtc;
EndTimeUtc = endTimeUtc;
RepeatCount = repeatCount;
RepeatInterval = repeatInterval;
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// fire the identified <see cref="IJob" /> and repeat at the given
/// interval the given number of times, or until the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">The group.</param>
/// <param name="jobName">Name of the job.</param>
/// <param name="jobGroup">The job group.</param>
/// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to fire.</param>
/// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use RepeatIndefinitely for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, string group, string jobName, string jobGroup, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc,
int repeatCount, TimeSpan repeatInterval)
: base(name, group, jobName, jobGroup)
{
StartTimeUtc = startTimeUtc;
EndTimeUtc = endTimeUtc;
RepeatCount = repeatCount;
RepeatInterval = repeatInterval;
}
/// <summary>
/// Get or set the number of times the <see cref="SimpleTriggerImpl" /> should
/// repeat, after which it will be automatically deleted.
/// </summary>
/// <seealso cref="RepeatIndefinitely" />
public int RepeatCount
{
get => repeatCount;
set
{
if (value < 0 && value != RepeatIndefinitely)
{
throw new ArgumentException("Repeat count must be >= 0, use the constant RepeatIndefinitely for infinite.");
}
repeatCount = value;
}
}
/// <summary>
/// Get or set the time interval at which the <see cref="ISimpleTrigger" /> should repeat.
/// </summary>
public TimeSpan RepeatInterval
{
get => repeatInterval;
set
{
if (value < TimeSpan.Zero)
{
throw new ArgumentException("Repeat interval must be >= 0");
}
repeatInterval = value;
}
}
/// <summary>
/// Get or set the number of times the <see cref="ISimpleTrigger" /> has already
/// fired.
/// </summary>
public virtual int TimesTriggered
{
get => timesTriggered;
set => timesTriggered = value;
}
public override IScheduleBuilder GetScheduleBuilder()
{
SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create()
.WithInterval(RepeatInterval)
.WithRepeatCount(RepeatCount);
switch (MisfireInstruction)
{
case Quartz.MisfireInstruction.SimpleTrigger.FireNow:
sb.WithMisfireHandlingInstructionFireNow();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount:
sb.WithMisfireHandlingInstructionNextWithExistingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount:
sb.WithMisfireHandlingInstructionNextWithRemainingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount:
sb.WithMisfireHandlingInstructionNowWithExistingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount:
sb.WithMisfireHandlingInstructionNowWithRemainingCount();
break;
case Quartz.MisfireInstruction.IgnoreMisfirePolicy:
sb.WithMisfireHandlingInstructionIgnoreMisfires();
break;
}
return sb;
}
/// <summary>
/// Returns the final UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, if repeatCount is RepeatIndefinitely, null will be returned.
/// <para>
/// Note that the return time may be in the past.
/// </para>
/// </summary>
public override DateTimeOffset? FinalFireTimeUtc
{
get
{
if (repeatCount == 0)
{
return StartTimeUtc;
}
if (repeatCount == RepeatIndefinitely && !EndTimeUtc.HasValue)
{
return null;
}
if (repeatCount == RepeatIndefinitely)
{
return GetFireTimeBefore(EndTimeUtc);
}
DateTimeOffset lastTrigger = StartTimeUtc.AddMilliseconds(repeatCount * repeatInterval.TotalMilliseconds);
if (!EndTimeUtc.HasValue || lastTrigger < EndTimeUtc.Value)
{
return lastTrigger;
}
return GetFireTimeBefore(EndTimeUtc);
}
}
/// <summary>
/// Tells whether this Trigger instance can handle events
/// in millisecond precision.
/// </summary>
/// <value></value>
public override bool HasMillisecondPrecision => true;
/// <summary>
/// Validates the misfire instruction.
/// </summary>
/// <param name="misfireInstruction">The misfire instruction.</param>
/// <returns></returns>
protected override bool ValidateMisfireInstruction(int misfireInstruction)
{
if (misfireInstruction < Quartz.MisfireInstruction.IgnoreMisfirePolicy)
{
return false;
}
if (misfireInstruction > Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
{
return false;
}
return true;
}
/// <summary>
/// Updates the <see cref="ISimpleTrigger" />'s state based on the
/// MisfireInstruction value that was selected when the <see cref="ISimpleTrigger" />
/// was created.
/// </summary>
/// <remarks>
/// If MisfireSmartPolicyEnabled is set to true,
/// then the following scheme will be used: <br />
/// <ul>
/// <li>If the Repeat Count is 0, then the instruction will
/// be interpreted as <see cref="MisfireInstruction.SimpleTrigger.FireNow" />.</li>
/// <li>If the Repeat Count is <see cref="RepeatIndefinitely" />, then
/// the instruction will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount" />.
/// <b>WARNING:</b> using MisfirePolicy.SimpleTrigger.RescheduleNowWithRemainingRepeatCount
/// with a trigger that has a non-null end-time may cause the trigger to
/// never fire again if the end-time arrived during the misfire time span.
/// </li>
/// <li>If the Repeat Count is > 0, then the instruction
/// will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount" />.
/// </li>
/// </ul>
/// </remarks>
public override void UpdateAfterMisfire(ICalendar? cal)
{
int instr = MisfireInstruction;
if (instr == Quartz.MisfireInstruction.SmartPolicy)
{
if (RepeatCount == 0)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.FireNow;
}
else if (RepeatCount == RepeatIndefinitely)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount;
}
else
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount;
}
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow && RepeatCount != 0)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount;
}
if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow)
{
nextFireTimeUtc = SystemTime.UtcNow();
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
if (!newFireTime.HasValue)
{
break;
}
//avoid infinite loop
if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
{
newFireTime = null;
}
}
nextFireTimeUtc = newFireTime;
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
if (!newFireTime.HasValue)
{
break;
}
//avoid infinite loop
if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
{
newFireTime = null;
}
}
if (newFireTime.HasValue)
{
int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc!.Value, newFireTime!.Value);
TimesTriggered = TimesTriggered + timesMissed;
}
nextFireTimeUtc = newFireTime;
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount)
{
DateTimeOffset newFireTime = SystemTime.UtcNow();
if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
{
RepeatCount = RepeatCount - TimesTriggered;
TimesTriggered = 0;
}
if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
{
nextFireTimeUtc = null; // We are past the end time
}
else
{
StartTimeUtc = newFireTime;
nextFireTimeUtc = newFireTime;
}
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount)
{
DateTimeOffset newFireTime = SystemTime.UtcNow();
int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc!.Value, newFireTime);
if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
{
int remainingCount = RepeatCount - (TimesTriggered + timesMissed);
if (remainingCount <= 0)
{
remainingCount = 0;
}
RepeatCount = remainingCount;
TimesTriggered = 0;
}
if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
{
nextFireTimeUtc = null; // We are past the end time
}
else
{
StartTimeUtc = newFireTime;
nextFireTimeUtc = newFireTime;
}
}
}
/// <summary>
/// Called when the <see cref="IScheduler" /> has decided to 'fire'
/// the trigger (Execute the associated <see cref="IJob" />), in order to
/// give the <see cref="ITrigger" /> a chance to update itself for its next
/// triggering (if any).
/// </summary>
/// <seealso cref="JobExecutionException" />
public override void Triggered(ICalendar? cal)
{
timesTriggered++;
previousFireTimeUtc = nextFireTimeUtc;
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
while (nextFireTimeUtc.HasValue && cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
}
}
/// <summary>
/// Updates the instance with new calendar.
/// </summary>
/// <param name="calendar">The calendar.</param>
/// <param name="misfireThreshold">The misfire threshold.</param>
public override void UpdateWithNewCalendar(ICalendar calendar, TimeSpan misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(previousFireTimeUtc);
if (nextFireTimeUtc == null || calendar == null)
{
return;
}
DateTimeOffset now = SystemTime.UtcNow();
while (nextFireTimeUtc.HasValue && !calendar.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
if (nextFireTimeUtc != null && nextFireTimeUtc.Value < now)
{
TimeSpan diff = now - nextFireTimeUtc.Value;
if (diff >= misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
}
}
}
}
/// <summary>
/// Called by the scheduler at the time a <see cref="ITrigger" /> is first
/// added to the scheduler, in order to have the <see cref="ITrigger" />
/// compute its first fire time, based on any associated calendar.
/// <para>
/// After this method has been called, <see cref="GetNextFireTimeUtc" />
/// should return a valid answer.
/// </para>
/// </summary>
/// <returns>
/// The first time at which the <see cref="ITrigger" /> will be fired
/// by the scheduler, which is also the same value <see cref="GetNextFireTimeUtc" />
/// will return (until after the first firing of the <see cref="ITrigger" />).
/// </returns>
public override DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar? cal)
{
nextFireTimeUtc = StartTimeUtc;
while (cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
return null;
}
}
return nextFireTimeUtc;
}
/// <summary>
/// Returns the next time at which the <see cref="ISimpleTrigger" /> will
/// fire. If the trigger will not fire again, <see langword="null" /> will be
/// returned. The value returned is not guaranteed to be valid until after
/// the <see cref="ITrigger" /> has been added to the scheduler.
/// </summary>
public override DateTimeOffset? GetNextFireTimeUtc()
{
return nextFireTimeUtc;
}
public override void SetNextFireTimeUtc(DateTimeOffset? nextFireTime)
{
nextFireTimeUtc = nextFireTime;
}
public override void SetPreviousFireTimeUtc(DateTimeOffset? previousFireTime)
{
previousFireTimeUtc = previousFireTime;
}
/// <summary>
/// Returns the previous time at which the <see cref="ISimpleTrigger" /> fired.
/// If the trigger has not yet fired, <see langword="null" /> will be
/// returned.
/// </summary>
public override DateTimeOffset? GetPreviousFireTimeUtc()
{
return previousFireTimeUtc;
}
/// <summary>
/// Returns the next UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, after the given UTC time. If the trigger will not fire after the given
/// time, <see langword="null" /> will be returned.
/// </summary>
public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTimeUtc)
{
if (timesTriggered > repeatCount && repeatCount != RepeatIndefinitely)
{
return null;
}
if (!afterTimeUtc.HasValue)
{
afterTimeUtc = SystemTime.UtcNow();
}
if (repeatCount == 0 && afterTimeUtc.Value.CompareTo(StartTimeUtc) >= 0)
{
return null;
}
DateTimeOffset startMillis = StartTimeUtc;
DateTimeOffset afterMillis = afterTimeUtc.Value;
DateTimeOffset endMillis = EndTimeUtc ?? DateTimeOffset.MaxValue;
if (endMillis <= afterMillis)
{
return null;
}
if (afterMillis < startMillis)
{
return startMillis;
}
long numberOfTimesExecuted = (long) ((long) (afterMillis - startMillis).TotalMilliseconds / repeatInterval.TotalMilliseconds + 1);
if (numberOfTimesExecuted > repeatCount &&
repeatCount != RepeatIndefinitely)
{
return null;
}
DateTimeOffset time = startMillis.AddMilliseconds(numberOfTimesExecuted * repeatInterval.TotalMilliseconds);
if (endMillis <= time)
{
return null;
}
return time;
}
/// <summary>
/// Returns the last UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, before the given time. If the trigger will not fire before the
/// given time, <see langword="null" /> will be returned.
/// </summary>
public virtual DateTimeOffset? GetFireTimeBefore(DateTimeOffset? endUtc)
{
if (endUtc != null && endUtc.Value < StartTimeUtc)
{
return null;
}
int numFires = ComputeNumTimesFiredBetween(StartTimeUtc, endUtc!.Value);
return StartTimeUtc.AddMilliseconds(numFires*repeatInterval.TotalMilliseconds);
}
/// <summary>
/// Computes the number of times fired between the two UTC date times.
/// </summary>
/// <param name="startTimeUtc">The UTC start date and time.</param>
/// <param name="endTimeUtc">The UTC end date and time.</param>
/// <returns></returns>
public virtual int ComputeNumTimesFiredBetween(DateTimeOffset startTimeUtc, DateTimeOffset endTimeUtc)
{
long time = (long) (endTimeUtc - startTimeUtc).TotalMilliseconds;
return (int) (time/repeatInterval.TotalMilliseconds);
}
/// <summary>
/// Determines whether or not the <see cref="ISimpleTrigger" /> will occur
/// again.
/// </summary>
public override bool GetMayFireAgain()
{
return GetNextFireTimeUtc().HasValue;
}
/// <summary>
/// Validates whether the properties of the <see cref="IJobDetail" /> are
/// valid for submission into a <see cref="IScheduler" />.
/// </summary>
public override void Validate()
{
base.Validate();
if (repeatCount != 0 && repeatInterval.TotalMilliseconds < 1)
{
throw new SchedulerException("Repeat Interval cannot be zero.");
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public partial class SqlManagementClient : ServiceClient<SqlManagementClient>, ISqlManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IAuditingPolicyOperations _auditingPolicy;
/// <summary>
/// Represents all the operations to manage Azure SQL Database and
/// Database Server Audit policy. Contains operations to: Create,
/// Retrieve and Update audit policy.
/// </summary>
public virtual IAuditingPolicyOperations AuditingPolicy
{
get { return this._auditingPolicy; }
}
private ICapabilitiesOperations _capabilities;
/// <summary>
/// Represents all the operations for determining the set of
/// capabilites available in a specified region.
/// </summary>
public virtual ICapabilitiesOperations Capabilities
{
get { return this._capabilities; }
}
private IDatabaseActivationOperations _databaseActivation;
/// <summary>
/// Represents all the operations for operating pertaining to
/// activation on Azure SQL Data Warehouse databases. Contains
/// operations to: Pause and Resume databases
/// </summary>
public virtual IDatabaseActivationOperations DatabaseActivation
{
get { return this._databaseActivation; }
}
private IDatabaseBackupOperations _databaseBackup;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// database backups.
/// </summary>
public virtual IDatabaseBackupOperations DatabaseBackup
{
get { return this._databaseBackup; }
}
private IDatabaseOperations _databases;
/// <summary>
/// Represents all the operations for operating on Azure SQL Databases.
/// Contains operations to: Create, Retrieve, Update, and Delete
/// databases, and also includes the ability to get the event logs for
/// a database.
/// </summary>
public virtual IDatabaseOperations Databases
{
get { return this._databases; }
}
private IDataMaskingOperations _dataMasking;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// data masking. Contains operations to: Create, Retrieve, Update,
/// and Delete data masking rules, as well as Create, Retreive and
/// Update data masking policy.
/// </summary>
public virtual IDataMaskingOperations DataMasking
{
get { return this._dataMasking; }
}
private IElasticPoolOperations _elasticPools;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Elastic Pools. Contains operations to: Create, Retrieve, Update,
/// and Delete.
/// </summary>
public virtual IElasticPoolOperations ElasticPools
{
get { return this._elasticPools; }
}
private IFirewallRuleOperations _firewallRules;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Server Firewall Rules. Contains operations to: Create, Retrieve,
/// Update, and Delete firewall rules.
/// </summary>
public virtual IFirewallRuleOperations FirewallRules
{
get { return this._firewallRules; }
}
private IRecommendedElasticPoolOperations _recommendedElasticPools;
/// <summary>
/// Represents all the operations for operating on Azure SQL
/// Recommended Elastic Pools. Contains operations to: Retrieve.
/// </summary>
public virtual IRecommendedElasticPoolOperations RecommendedElasticPools
{
get { return this._recommendedElasticPools; }
}
private IRecommendedIndexOperations _recommendedIndexes;
/// <summary>
/// Represents all the operations for managing recommended indexes on
/// Azure SQL Databases. Contains operations to retrieve recommended
/// index and update state.
/// </summary>
public virtual IRecommendedIndexOperations RecommendedIndexes
{
get { return this._recommendedIndexes; }
}
private IReplicationLinkOperations _databaseReplicationLinks;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Replication Links. Contains operations to: Delete and Retrieve
/// replication links.
/// </summary>
public virtual IReplicationLinkOperations DatabaseReplicationLinks
{
get { return this._databaseReplicationLinks; }
}
private ISecureConnectionPolicyOperations _secureConnection;
/// <summary>
/// Represents all the operations for managing Azure SQL Database
/// secure connection. Contains operations to: Create, Retrieve and
/// Update secure connection policy .
/// </summary>
public virtual ISecureConnectionPolicyOperations SecureConnection
{
get { return this._secureConnection; }
}
private ISecurityAlertPolicyOperations _securityAlertPolicy;
/// <summary>
/// Represents all the operations to manage Azure SQL Database and
/// Database Server Security Alert policy. Contains operations to:
/// Create, Retrieve and Update policy.
/// </summary>
public virtual ISecurityAlertPolicyOperations SecurityAlertPolicy
{
get { return this._securityAlertPolicy; }
}
private IServerAdministratorOperations _serverAdministrators;
/// <summary>
/// Represents all the operations for operating on Azure SQL Server
/// Active Directory Administrators. Contains operations to: Create,
/// Retrieve, Update, and Delete Azure SQL Server Active Directory
/// Administrators.
/// </summary>
public virtual IServerAdministratorOperations ServerAdministrators
{
get { return this._serverAdministrators; }
}
private IServerCommunicationLinkOperations _communicationLinks;
/// <summary>
/// Represents all the operations for operating on Azure SQL Server
/// communication links. Contains operations to: Create, Retrieve,
/// Update, and Delete.
/// </summary>
public virtual IServerCommunicationLinkOperations CommunicationLinks
{
get { return this._communicationLinks; }
}
private IServerDisasterRecoveryConfigurationOperations _serverDisasterRecoveryConfigurations;
/// <summary>
/// Represents all the operations for operating on Azure SQL Server
/// disaster recovery configurations. Contains operations to: Create,
/// Retrieve, Update, and Delete.
/// </summary>
public virtual IServerDisasterRecoveryConfigurationOperations ServerDisasterRecoveryConfigurations
{
get { return this._serverDisasterRecoveryConfigurations; }
}
private IServerOperations _servers;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Servers. Contains operations to: Create, Retrieve, Update, and
/// Delete servers.
/// </summary>
public virtual IServerOperations Servers
{
get { return this._servers; }
}
private IServerUpgradeOperations _serverUpgrades;
/// <summary>
/// Represents all the operations for Azure SQL Database Server Upgrade
/// </summary>
public virtual IServerUpgradeOperations ServerUpgrades
{
get { return this._serverUpgrades; }
}
private IServiceObjectiveOperations _serviceObjectives;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Service Objectives. Contains operations to: Retrieve service
/// objectives.
/// </summary>
public virtual IServiceObjectiveOperations ServiceObjectives
{
get { return this._serviceObjectives; }
}
private IServiceTierAdvisorOperations _serviceTierAdvisors;
/// <summary>
/// Represents all the operations for operating on service tier
/// advisors. Contains operations to: Retrieve.
/// </summary>
public virtual IServiceTierAdvisorOperations ServiceTierAdvisors
{
get { return this._serviceTierAdvisors; }
}
private ITransparentDataEncryptionOperations _transparentDataEncryption;
/// <summary>
/// Represents all the operations of Azure SQL Database Transparent
/// Data Encryption. Contains operations to: Retrieve, and Update
/// Transparent Data Encryption.
/// </summary>
public virtual ITransparentDataEncryptionOperations TransparentDataEncryption
{
get { return this._transparentDataEncryption; }
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
public SqlManagementClient()
: base()
{
this._auditingPolicy = new AuditingPolicyOperations(this);
this._capabilities = new CapabilitiesOperations(this);
this._databaseActivation = new DatabaseActivationOperations(this);
this._databaseBackup = new DatabaseBackupOperations(this);
this._databases = new DatabaseOperations(this);
this._dataMasking = new DataMaskingOperations(this);
this._elasticPools = new ElasticPoolOperations(this);
this._firewallRules = new FirewallRuleOperations(this);
this._recommendedElasticPools = new RecommendedElasticPoolOperations(this);
this._recommendedIndexes = new RecommendedIndexOperations(this);
this._databaseReplicationLinks = new ReplicationLinkOperations(this);
this._secureConnection = new SecureConnectionPolicyOperations(this);
this._securityAlertPolicy = new SecurityAlertPolicyOperations(this);
this._serverAdministrators = new ServerAdministratorOperations(this);
this._communicationLinks = new ServerCommunicationLinkOperations(this);
this._serverDisasterRecoveryConfigurations = new ServerDisasterRecoveryConfigurationOperations(this);
this._servers = new ServerOperations(this);
this._serverUpgrades = new ServerUpgradeOperations(this);
this._serviceObjectives = new ServiceObjectiveOperations(this);
this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this);
this._transparentDataEncryption = new TransparentDataEncryptionOperations(this);
this._apiVersion = "2014-04-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._auditingPolicy = new AuditingPolicyOperations(this);
this._capabilities = new CapabilitiesOperations(this);
this._databaseActivation = new DatabaseActivationOperations(this);
this._databaseBackup = new DatabaseBackupOperations(this);
this._databases = new DatabaseOperations(this);
this._dataMasking = new DataMaskingOperations(this);
this._elasticPools = new ElasticPoolOperations(this);
this._firewallRules = new FirewallRuleOperations(this);
this._recommendedElasticPools = new RecommendedElasticPoolOperations(this);
this._recommendedIndexes = new RecommendedIndexOperations(this);
this._databaseReplicationLinks = new ReplicationLinkOperations(this);
this._secureConnection = new SecureConnectionPolicyOperations(this);
this._securityAlertPolicy = new SecurityAlertPolicyOperations(this);
this._serverAdministrators = new ServerAdministratorOperations(this);
this._communicationLinks = new ServerCommunicationLinkOperations(this);
this._serverDisasterRecoveryConfigurations = new ServerDisasterRecoveryConfigurationOperations(this);
this._servers = new ServerOperations(this);
this._serverUpgrades = new ServerUpgradeOperations(this);
this._serviceObjectives = new ServiceObjectiveOperations(this);
this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this);
this._transparentDataEncryption = new TransparentDataEncryptionOperations(this);
this._apiVersion = "2014-04-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// SqlManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of SqlManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<SqlManagementClient> client)
{
base.Clone(client);
if (client is SqlManagementClient)
{
SqlManagementClient clonedClient = ((SqlManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System;
using NPOI.POIFS.Storage;
using System.IO;
namespace NPOI.POIFS.FileSystem
{
/**
* This class provides methods to read a DocumentEntry managed by a
* {@link POIFSFileSystem} instance.
*
* @author Marc Johnson (mjohnson at apache dot org)
*/
internal class ODocumentInputStream : DocumentInputStream//DocumentReader
{
/** current offset into the Document */
private long _current_offset;
/** current marked offset into the Document (used by mark and Reset) */
private long _marked_offset;
/** the Document's size */
private int _document_size;
/** have we been closed? */
private bool _closed;
/** the actual Document */
private POIFSDocument _document;
/** the data block Containing the current stream pointer */
private DataInputBlock _currentBlock;
/**
* Create an InputStream from the specified DocumentEntry
*
* @param document the DocumentEntry to be read
*
* @exception IOException if the DocumentEntry cannot be opened (like, maybe it has
* been deleted?)
*/
public ODocumentInputStream(DocumentEntry document)
{
if (!(document is DocumentNode))
{
throw new IOException("Cannot open internal document storage");
}
DocumentNode documentNode = (DocumentNode)document;
if (documentNode.Document == null)
{
throw new IOException("Cannot open internal document storage");
}
_current_offset = 0;
_marked_offset = 0;
_document_size = document.Size;
_closed = false;
_document = documentNode.Document;
_currentBlock = GetDataInputBlock(0);
}
public override long Length
{
get
{
return _document_size;
}
}
/**
* Create an InputStream from the specified Document
*
* @param document the Document to be read
*/
public ODocumentInputStream(POIFSDocument document)
{
_current_offset = 0;
_marked_offset = 0;
_document_size = document.Size;
_closed = false;
_document = document;
_currentBlock = GetDataInputBlock(0);
}
public override int Available()
{
if (_closed)
{
throw new InvalidOperationException("cannot perform requested operation on a closed stream");
}
return _document_size - (int)_current_offset;
}
public override void Close()
{
_closed = true;
}
public override void Mark(int ignoredReadlimit)
{
_marked_offset = _current_offset;
}
private DataInputBlock GetDataInputBlock(long offset)
{
return _document.GetDataInputBlock((int)offset);
}
public override int Read()
{
dieIfClosed();
if (atEOD())
{
return EOF;
}
int result = _currentBlock.ReadUByte();
_current_offset++;
if (_currentBlock.Available() < 1)
{
_currentBlock = GetDataInputBlock(_current_offset);
}
return result;
}
public override int Read(byte[] b, int off, int len)
{
dieIfClosed();
if (b == null)
{
throw new ArgumentException("buffer must not be null");
}
if (off < 0 || len < 0 || b.Length < off + len)
{
throw new IndexOutOfRangeException("can't read past buffer boundaries");
}
if (len == 0)
{
return 0;
}
if (atEOD())
{
return EOF;
}
int limit = Math.Min(Available(), len);
ReadFully(b, off, limit);
return limit;
}
/**
* Repositions this stream to the position at the time the mark() method was
* last called on this input stream. If mark() has not been called this
* method repositions the stream to its beginning.
*/
public override void Reset()
{
_current_offset = _marked_offset;
_currentBlock = GetDataInputBlock(_current_offset);
}
public override long Skip(long n)
{
dieIfClosed();
if (n < 0)
{
return 0;
}
long new_offset = _current_offset + (int)n;
if (new_offset < _current_offset)
{
// wrap around in Converting a VERY large long to an int
new_offset = _document_size;
}
else if (new_offset > _document_size)
{
new_offset = _document_size;
}
long rval = new_offset - _current_offset;
_current_offset = new_offset;
_currentBlock = GetDataInputBlock(_current_offset);
return rval;
}
private void dieIfClosed()
{
if (_closed)
{
throw new IOException("cannot perform requested operation on a closed stream");
}
}
private bool atEOD()
{
return _current_offset == _document_size;
}
private void CheckAvaliable(int requestedSize)
{
if (_closed)
{
throw new InvalidOperationException("cannot perform requested operation on a closed stream");
}
if (requestedSize > _document_size - _current_offset)
{
throw new Exception("Buffer underrun - requested " + requestedSize
+ " bytes but " + (_document_size - _current_offset) + " was available");
}
}
public override int ReadByte()
{
return ReadUByte();
}
public override double ReadDouble()
{
return BitConverter.Int64BitsToDouble(ReadLong());
}
public override short ReadShort()
{
return (short)ReadUShort();
}
public override void ReadFully(byte[] buf, int off, int len)
{
CheckAvaliable(len);
int blockAvailable = _currentBlock.Available();
if (blockAvailable > len)
{
_currentBlock.ReadFully(buf, off, len);
_current_offset += len;
return;
}
// else read big amount in chunks
int remaining = len;
int WritePos = off;
while (remaining > 0)
{
bool blockIsExpiring = remaining >= blockAvailable;
int reqSize;
if (blockIsExpiring)
{
reqSize = blockAvailable;
}
else
{
reqSize = remaining;
}
_currentBlock.ReadFully(buf, WritePos, reqSize);
remaining -= reqSize;
WritePos += reqSize;
_current_offset += reqSize;
if (blockIsExpiring)
{
if (_current_offset == _document_size)
{
if (remaining > 0)
{
throw new InvalidOperationException(
"reached end of document stream unexpectedly");
}
_currentBlock = null;
break;
}
_currentBlock = GetDataInputBlock(_current_offset);
blockAvailable = _currentBlock.Available();
}
}
}
public override long ReadLong()
{
CheckAvaliable(SIZE_LONG);
int blockAvailable = _currentBlock.Available();
long result;
if (blockAvailable > SIZE_LONG)
{
result = _currentBlock.ReadLongLE();
}
else
{
DataInputBlock nextBlock = GetDataInputBlock(_current_offset + blockAvailable);
if (blockAvailable == SIZE_LONG)
{
result = _currentBlock.ReadLongLE();
}
else
{
result = nextBlock.ReadLongLE(_currentBlock, blockAvailable);
}
_currentBlock = nextBlock;
}
_current_offset += SIZE_LONG;
return result;
}
public override int ReadInt()
{
CheckAvaliable(SIZE_INT);
int blockAvailable = _currentBlock.Available();
int result;
if (blockAvailable > SIZE_INT)
{
result = _currentBlock.ReadIntLE();
}
else
{
DataInputBlock nextBlock = GetDataInputBlock(_current_offset + blockAvailable);
if (blockAvailable == SIZE_INT)
{
result = _currentBlock.ReadIntLE();
}
else
{
result = nextBlock.ReadIntLE(_currentBlock, blockAvailable);
}
_currentBlock = nextBlock;
}
_current_offset += SIZE_INT;
return result;
}
public override int ReadUShort()
{
CheckAvaliable(SIZE_SHORT);
int blockAvailable = _currentBlock.Available();
int result;
if (blockAvailable > SIZE_SHORT)
{
result = _currentBlock.ReadUshortLE();
}
else
{
DataInputBlock nextBlock = GetDataInputBlock(_current_offset + blockAvailable);
if (blockAvailable == SIZE_SHORT)
{
result = _currentBlock.ReadUshortLE();
}
else
{
result = nextBlock.ReadUshortLE(_currentBlock);
}
_currentBlock = nextBlock;
}
_current_offset += SIZE_SHORT;
return result;
}
public override int ReadUByte()
{
CheckAvaliable(1);
int result = _currentBlock.ReadUByte();
_current_offset++;
if (_currentBlock.Available() < 1)
{
_currentBlock = GetDataInputBlock(_current_offset);
}
return result;
}
public override long Seek(long offset, SeekOrigin origin)
{
if (origin == SeekOrigin.Current)
{
if (_current_offset + offset >= this.Length || _current_offset + offset < 0)
throw new ArgumentException("invalid offset");
_current_offset += (int)offset;
}
else if (origin == SeekOrigin.Begin)
{
if (offset >= this.Length || offset < 0)
throw new ArgumentException("invalid offset");
_current_offset = offset;
}
else if (origin == SeekOrigin.End)
{
if (this.Length + offset >= this.Length || this.Length + offset < 0)
throw new ArgumentException("invalid offset");
_current_offset = this.Length + offset;
}
return _current_offset;
}
public override long Position
{
get
{
if (_closed)
{
throw new InvalidOperationException("cannot perform requested operation on a closed stream");
}
return _current_offset;
}
set
{
_current_offset = (int)value;
}
}
}
}
| |
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.ServiceModel.Activation;
using System.ServiceModel;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
abstract class ConnectionOrientedTransportManager<TChannelListener> : TransportManager
where TChannelListener : ConnectionOrientedTransportChannelListener
{
UriPrefixTable<TChannelListener> addressTable;
int connectionBufferSize;
TimeSpan channelInitializationTimeout;
int maxPendingConnections;
TimeSpan maxOutputDelay;
int maxPendingAccepts;
TimeSpan idleTimeout;
int maxPooledConnections;
Action messageReceivedCallback;
protected ConnectionOrientedTransportManager()
{
this.addressTable = new UriPrefixTable<TChannelListener>();
}
UriPrefixTable<TChannelListener> AddressTable
{
get { return addressTable; }
}
protected TimeSpan ChannelInitializationTimeout
{
get
{
return channelInitializationTimeout;
}
}
internal void ApplyListenerSettings(IConnectionOrientedListenerSettings listenerSettings)
{
this.connectionBufferSize = listenerSettings.ConnectionBufferSize;
this.channelInitializationTimeout = listenerSettings.ChannelInitializationTimeout;
this.maxPendingConnections = listenerSettings.MaxPendingConnections;
this.maxOutputDelay = listenerSettings.MaxOutputDelay;
this.maxPendingAccepts = listenerSettings.MaxPendingAccepts;
this.idleTimeout = listenerSettings.IdleTimeout;
this.maxPooledConnections = listenerSettings.MaxPooledConnections;
}
internal int ConnectionBufferSize
{
get
{
return this.connectionBufferSize;
}
}
internal int MaxPendingConnections
{
get
{
return this.maxPendingConnections;
}
}
internal TimeSpan MaxOutputDelay
{
get
{
return maxOutputDelay;
}
}
internal int MaxPendingAccepts
{
get
{
return this.maxPendingAccepts;
}
}
internal TimeSpan IdleTimeout
{
get { return this.idleTimeout; }
}
internal int MaxPooledConnections
{
get { return this.maxPooledConnections; }
}
internal bool IsCompatible(ConnectionOrientedTransportChannelListener channelListener)
{
if (channelListener.InheritBaseAddressSettings)
return true;
return (
(this.ChannelInitializationTimeout == channelListener.ChannelInitializationTimeout) &&
(this.ConnectionBufferSize == channelListener.ConnectionBufferSize) &&
(this.MaxPendingConnections == channelListener.MaxPendingConnections) &&
(this.MaxOutputDelay == channelListener.MaxOutputDelay) &&
(this.MaxPendingAccepts == channelListener.MaxPendingAccepts) &&
(this.idleTimeout == channelListener.IdleTimeout) &&
(this.maxPooledConnections == channelListener.MaxPooledConnections)
);
}
TChannelListener GetChannelListener(Uri via)
{
TChannelListener channelListener = null;
if (AddressTable.TryLookupUri(via, HostNameComparisonMode.StrongWildcard, out channelListener))
{
return channelListener;
}
if (AddressTable.TryLookupUri(via, HostNameComparisonMode.Exact, out channelListener))
{
return channelListener;
}
AddressTable.TryLookupUri(via, HostNameComparisonMode.WeakWildcard, out channelListener);
return channelListener;
}
internal void OnDemuxerError(Exception exception)
{
lock (ThisLock)
{
this.Fault(this.AddressTable, exception);
}
}
internal ISingletonChannelListener OnGetSingletonMessageHandler(ServerSingletonPreambleConnectionReader serverSingletonPreambleReader)
{
Uri via = serverSingletonPreambleReader.Via;
TChannelListener channelListener = GetChannelListener(via);
if (channelListener != null)
{
if (channelListener is IChannelListener<IReplyChannel>)
{
channelListener.RaiseMessageReceived();
return (ISingletonChannelListener)channelListener;
}
else
{
serverSingletonPreambleReader.SendFault(FramingEncodingString.UnsupportedModeFault);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.FramingModeNotSupported, FramingMode.Singleton)));
}
}
else
{
serverSingletonPreambleReader.SendFault(FramingEncodingString.EndpointNotFoundFault);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new EndpointNotFoundException(SR.GetString(SR.EndpointNotFound, via)));
}
}
internal void OnHandleServerSessionPreamble(ServerSessionPreambleConnectionReader serverSessionPreambleReader,
ConnectionDemuxer connectionDemuxer)
{
Uri via = serverSessionPreambleReader.Via;
TChannelListener channelListener = GetChannelListener(via);
if (channelListener != null)
{
ISessionPreambleHandler sessionPreambleHandler = channelListener as ISessionPreambleHandler;
if (sessionPreambleHandler != null && channelListener is IChannelListener<IDuplexSessionChannel>)
{
sessionPreambleHandler.HandleServerSessionPreamble(serverSessionPreambleReader, connectionDemuxer);
}
else
{
serverSessionPreambleReader.SendFault(FramingEncodingString.UnsupportedModeFault);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.FramingModeNotSupported, FramingMode.Duplex)));
}
}
else
{
serverSessionPreambleReader.SendFault(FramingEncodingString.EndpointNotFoundFault);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(SR.GetString(SR.DuplexSessionListenerNotFound, via.ToString())));
}
}
internal IConnectionOrientedTransportFactorySettings OnGetTransportFactorySettings(Uri via)
{
return GetChannelListener(via);
}
internal override void Register(TransportChannelListener channelListener)
{
AddressTable.RegisterUri(channelListener.Uri, channelListener.HostNameComparisonModeInternal,
(TChannelListener)channelListener);
channelListener.SetMessageReceivedCallback(new Action(OnMessageReceived));
}
internal override void Unregister(TransportChannelListener channelListener)
{
EnsureRegistered(AddressTable, (TChannelListener)channelListener, channelListener.HostNameComparisonModeInternal);
AddressTable.UnregisterUri(channelListener.Uri, channelListener.HostNameComparisonModeInternal);
channelListener.SetMessageReceivedCallback(null);
}
internal void SetMessageReceivedCallback(Action messageReceivedCallback)
{
this.messageReceivedCallback = messageReceivedCallback;
}
void OnMessageReceived()
{
Action callback = this.messageReceivedCallback;
if (callback != null)
{
callback();
}
}
}
}
| |
// 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 Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class ExpressionTreeRewriter : ExprVisitorBase
{
public static ExprBinOp Rewrite(ExprBoundLambda expr) => new ExpressionTreeRewriter().VisitBoundLambda(expr);
protected override Expr Dispatch(Expr expr)
{
Debug.Assert(expr != null);
Expr result = base.Dispatch(expr);
if (result == expr)
{
throw Error.InternalCompilerError();
}
return result;
}
/////////////////////////////////////////////////////////////////////////////////
// Statement types.
protected override Expr VisitASSIGNMENT(ExprAssignment assignment)
{
Debug.Assert(assignment != null);
// For assignments, we either have a member assignment or an indexed assignment.
//Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL());
Expr lhs;
if (assignment.LHS is ExprProperty prop)
{
if (prop.OptionalArguments== null)
{
// Regular property.
lhs = Visit(prop);
}
else
{
// Indexed assignment. Here we need to find the instance of the object, create the
// PropInfo for the thing, and get the array of expressions that make up the index arguments.
//
// The LHS becomes Expression.Property(instance, indexerInfo, arguments).
Expr instance = Visit(prop.MemberGroup.OptionalObject);
Expr propInfo = ExprFactory.CreatePropertyInfo(prop.PropWithTypeSlot.Prop(), prop.PropWithTypeSlot.Ats);
Expr arguments = GenerateParamsArray(
GenerateArgsList(prop.OptionalArguments),
PredefinedType.PT_EXPRESSION);
lhs = GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, instance, propInfo, arguments);
}
}
else
{
lhs = Visit(assignment.LHS);
}
Expr rhs = Visit(assignment.RHS);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs);
}
protected override Expr VisitMULTIGET(ExprMultiGet pExpr)
{
return Visit(pExpr.OptionalMulti.Left);
}
protected override Expr VisitMULTI(ExprMulti pExpr)
{
Expr rhs = Visit(pExpr.Operator);
Expr lhs = Visit(pExpr.Left);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs);
}
/////////////////////////////////////////////////////////////////////////////////
// Expression types.
private ExprBinOp VisitBoundLambda(ExprBoundLambda anonmeth)
{
Debug.Assert(anonmeth != null);
MethodSymbol lambdaMethod = GetPreDefMethod(PREDEFMETH.PM_EXPRESSION_LAMBDA);
AggregateType delegateType = anonmeth.DelegateType;
TypeArray lambdaTypeParams = TypeArray.Allocate(delegateType);
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
MethWithInst mwi = new MethWithInst(lambdaMethod, expressionType, lambdaTypeParams);
Expr createParameters = CreateWraps(anonmeth);
Debug.Assert(createParameters != null);
Debug.Assert(anonmeth.Expression != null);
Expr body = Visit(anonmeth.Expression);
Debug.Assert(anonmeth.ArgumentScope.nextChild == null);
Expr parameters = GenerateParamsArray(null, PredefinedType.PT_PARAMETEREXPRESSION);
Expr args = ExprFactory.CreateList(body, parameters);
CType typeRet = TypeManager.SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, typeRet, args, pMemGroup, mwi);
call.PredefinedMethod = PREDEFMETH.PM_EXPRESSION_LAMBDA;
return ExprFactory.CreateSequence(createParameters, call);
}
protected override Expr VisitCONSTANT(ExprConstant expr)
{
Debug.Assert(expr != null);
return GenerateConstant(expr);
}
protected override Expr VisitLOCAL(ExprLocal local)
{
Debug.Assert(local != null);
Debug.Assert(local.Local.wrap != null);
return local.Local.wrap;
}
protected override Expr VisitFIELD(ExprField expr)
{
Debug.Assert(expr != null);
Expr pObject;
if (expr.OptionalObject== null)
{
pObject = ExprFactory.CreateNull();
}
else
{
pObject = Visit(expr.OptionalObject);
}
ExprFieldInfo pFieldInfo = ExprFactory.CreateFieldInfo(expr.FieldWithType.Field(), expr.FieldWithType.GetType());
return GenerateCall(PREDEFMETH.PM_EXPRESSION_FIELD, pObject, pFieldInfo);
}
protected override Expr VisitUSERDEFINEDCONVERSION(ExprUserDefinedConversion expr)
{
Debug.Assert(expr != null);
return GenerateUserDefinedConversion(expr, expr.Argument);
}
protected override Expr VisitCAST(ExprCast pExpr)
{
Debug.Assert(pExpr != null);
Expr pArgument = pExpr.Argument;
// If we have generated an identity cast or reference cast to a base class
// we can omit the cast.
if (pArgument.Type == pExpr.Type ||
SymbolLoader.IsBaseClassOfClass(pArgument.Type, pExpr.Type) ||
CConversions.FImpRefConv(pArgument.Type, pExpr.Type))
{
return Visit(pArgument);
}
// If we have a cast to PredefinedType.PT_G_EXPRESSION and the thing that we're casting is
// a EXPRBOUNDLAMBDA that is an expression tree, then just visit the expression tree.
if (pExpr.Type != null &&
pExpr.Type.IsPredefType(PredefinedType.PT_G_EXPRESSION) &&
pArgument is ExprBoundLambda)
{
return Visit(pArgument);
}
Expr result = GenerateConversion(pArgument, pExpr.Type, pExpr.isChecked());
if ((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0)
{
// Propagate the unbox flag to the call for the ExpressionTreeCallRewriter.
result.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME;
}
return result;
}
protected override Expr VisitCONCAT(ExprConcat expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
if (expr.FirstArgument.Type.IsPredefType(PredefinedType.PT_STRING) && expr.SecondArgument.Type.IsPredefType(PredefinedType.PT_STRING))
{
pdm = PREDEFMETH.PM_STRING_CONCAT_STRING_2;
}
else
{
pdm = PREDEFMETH.PM_STRING_CONCAT_OBJECT_2;
}
Expr p1 = Visit(expr.FirstArgument);
Expr p2 = Visit(expr.SecondArgument);
MethodSymbol method = GetPreDefMethod(pdm);
Expr methodInfo = ExprFactory.CreateMethodInfo(method, SymbolLoader.GetPredefindType(PredefinedType.PT_STRING), null);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, p1, p2, methodInfo);
}
protected override Expr VisitBINOP(ExprBinOp expr)
{
Debug.Assert(expr != null);
if (expr.UserDefinedCallMethod != null)
{
return GenerateUserDefinedBinaryOperator(expr);
}
else
{
return GenerateBuiltInBinaryOperator(expr);
}
}
protected override Expr VisitUNARYOP(ExprUnaryOp pExpr)
{
Debug.Assert(pExpr != null);
if (pExpr.UserDefinedCallMethod != null)
{
return GenerateUserDefinedUnaryOperator(pExpr);
}
else
{
return GenerateBuiltInUnaryOperator(pExpr);
}
}
protected override Expr VisitARRAYINDEX(ExprArrayIndex pExpr)
{
Debug.Assert(pExpr != null);
Expr arr = Visit(pExpr.Array);
Expr args = GenerateIndexList(pExpr.Index);
if (args is ExprList)
{
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, arr, Params);
}
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, arr, args);
}
protected override Expr VisitCALL(ExprCall expr)
{
Debug.Assert(expr != null);
switch (expr.NullableCallLiftKind)
{
default:
break;
case NullableCallLiftKind.NullableIntermediateConversion:
case NullableCallLiftKind.NullableConversion:
case NullableCallLiftKind.NullableConversionConstructor:
return GenerateConversion(expr.OptionalArguments, expr.Type, expr.isChecked());
case NullableCallLiftKind.NotLiftedIntermediateConversion:
case NullableCallLiftKind.UserDefinedConversion:
return GenerateUserDefinedConversion(expr.OptionalArguments, expr.Type, expr.MethWithInst);
}
if (expr.MethWithInst.Meth().IsConstructor())
{
return GenerateConstructor(expr);
}
ExprMemberGroup memberGroup = expr.MemberGroup;
if (memberGroup.IsDelegate)
{
return GenerateDelegateInvoke(expr);
}
Expr pObject;
if (expr.MethWithInst.Meth().isStatic || expr.MemberGroup.OptionalObject== null)
{
pObject = ExprFactory.CreateNull();
}
else
{
pObject = expr.MemberGroup.OptionalObject;
// If we have, say, an int? which is the object of a call to ToString
// then we do NOT want to generate ((object)i).ToString() because that
// will convert a null-valued int? to a null object. Rather what we want
// to do is box it to a ValueType and call ValueType.ToString.
//
// To implement this we say that if the object of the call is an implicit boxing cast
// then just generate the object, not the cast. If the cast is explicit in the
// source code then it will be an EXPLICITCAST and we will visit it normally.
//
// It might be better to rewrite the expression tree API so that it
// can handle in the general case all implicit boxing conversions. Right now it
// requires that all arguments to a call that need to be boxed be explicitly boxed.
if (pObject != null && pObject is ExprCast cast && cast.IsBoxingCast)
{
pObject = cast.Argument;
}
pObject = Visit(pObject);
}
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.MethWithInst);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
PREDEFMETH pdm = PREDEFMETH.PM_EXPRESSION_CALL;
Debug.Assert(!expr.MethWithInst.Meth().isVirtual || expr.MemberGroup.OptionalObject != null);
return GenerateCall(pdm, pObject, methodInfo, Params);
}
protected override Expr VisitPROP(ExprProperty expr)
{
Debug.Assert(expr != null);
Expr pObject;
if (expr.PropWithTypeSlot.Prop().isStatic || expr.MemberGroup.OptionalObject== null)
{
pObject = ExprFactory.CreateNull();
}
else
{
pObject = Visit(expr.MemberGroup.OptionalObject);
}
Expr propInfo = ExprFactory.CreatePropertyInfo(expr.PropWithTypeSlot.Prop(), expr.PropWithTypeSlot.GetType());
if (expr.OptionalArguments != null)
{
// It is an indexer property. Turn it into a virtual method call.
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo, Params);
}
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo);
}
protected override Expr VisitARRINIT(ExprArrayInit expr)
{
Debug.Assert(expr != null);
// POSSIBLE ERROR: Multi-d should be an error?
Expr pTypeOf = CreateTypeOf(((ArrayType)expr.Type).ElementType);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, pTypeOf, Params);
}
protected override Expr VisitZEROINIT(ExprZeroInit expr)
{
Debug.Assert(expr != null);
return GenerateConstant(expr);
}
protected override Expr VisitTYPEOF(ExprTypeOf expr)
{
Debug.Assert(expr != null);
return GenerateConstant(expr);
}
private Expr GenerateDelegateInvoke(ExprCall expr)
{
Debug.Assert(expr != null);
ExprMemberGroup memberGroup = expr.MemberGroup;
Debug.Assert(memberGroup.IsDelegate);
Expr oldObject = memberGroup.OptionalObject;
Debug.Assert(oldObject != null);
Expr pObject = Visit(oldObject);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_INVOKE, pObject, Params);
}
private Expr GenerateBuiltInBinaryOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
switch (expr.Kind)
{
case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT; break;
case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT; break;
case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR; break;
case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR; break;
case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND; break;
case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO; break;
case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE; break;
case ExpressionKind.StringEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break;
case ExpressionKind.Eq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break;
case ExpressionKind.StringNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break;
case ExpressionKind.NotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break;
case ExpressionKind.GreaterThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL; break;
case ExpressionKind.LessThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL; break;
case ExpressionKind.LessThan: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN; break;
case ExpressionKind.GreaterThan: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN; break;
case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO; break;
case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE; break;
case ExpressionKind.Multiply:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED : PREDEFMETH.PM_EXPRESSION_MULTIPLY;
break;
case ExpressionKind.Subtract:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED : PREDEFMETH.PM_EXPRESSION_SUBTRACT;
break;
case ExpressionKind.Add:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED : PREDEFMETH.PM_EXPRESSION_ADD;
break;
default:
throw Error.InternalCompilerError();
}
Expr origL = expr.OptionalLeftChild;
Expr origR = expr.OptionalRightChild;
Debug.Assert(origL != null);
Debug.Assert(origR != null);
CType typeL = origL.Type;
CType typeR = origR.Type;
Expr newL = Visit(origL);
Expr newR = Visit(origR);
bool didEnumConversion = false;
CType convertL = null;
CType convertR = null;
if (typeL.IsEnumType)
{
// We have already inserted casts if not lifted, so we should never see an enum.
Debug.Assert(expr.IsLifted);
convertL = TypeManager.GetNullable(typeL.UnderlyingEnumType);
typeL = convertL;
didEnumConversion = true;
}
else if (typeL is NullableType nubL && nubL.UnderlyingType.IsEnumType)
{
Debug.Assert(expr.IsLifted);
convertL = TypeManager.GetNullable(nubL.UnderlyingType.UnderlyingEnumType);
typeL = convertL;
didEnumConversion = true;
}
if (typeR.IsEnumType)
{
Debug.Assert(expr.IsLifted);
convertR = TypeManager.GetNullable(typeR.UnderlyingEnumType);
typeR = convertR;
didEnumConversion = true;
}
else if (typeR is NullableType nubR && nubR.UnderlyingType.IsEnumType)
{
Debug.Assert(expr.IsLifted);
convertR = TypeManager.GetNullable(nubR.UnderlyingType.UnderlyingEnumType);
typeR = convertR;
didEnumConversion = true;
}
if (typeL is NullableType nubL2 && nubL2.UnderlyingType == typeR)
{
convertR = typeL;
}
if (typeR is NullableType nubR2 && nubR2.UnderlyingType == typeL)
{
convertL = typeR;
}
if (convertL != null)
{
newL = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newL, CreateTypeOf(convertL));
}
if (convertR != null)
{
newR = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newR, CreateTypeOf(convertR));
}
Expr call = GenerateCall(pdm, newL, newR);
if (didEnumConversion && expr.Type.StripNubs().IsEnumType)
{
call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(expr.Type));
}
return call;
}
private Expr GenerateBuiltInUnaryOperator(ExprUnaryOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
switch (expr.Kind)
{
case ExpressionKind.UnaryPlus:
return Visit(expr.Child);
case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break;
case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break;
case ExpressionKind.Negate:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED : PREDEFMETH.PM_EXPRESSION_NEGATE;
break;
default:
throw Error.InternalCompilerError();
}
Expr origOp = expr.Child;
// Such operations are always already casts on operations on casts.
Debug.Assert(!(origOp.Type is NullableType nub) || !nub.UnderlyingType.IsEnumType);
return GenerateCall(pdm, Visit(origOp));
}
private Expr GenerateUserDefinedBinaryOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
switch (expr.Kind)
{
case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED; break;
case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED; break;
case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED; break;
case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED; break;
case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED; break;
case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED; break;
case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED; break;
case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED; break;
case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED; break;
case ExpressionKind.StringEq:
case ExpressionKind.StringNotEq:
case ExpressionKind.DelegateEq:
case ExpressionKind.DelegateNotEq:
case ExpressionKind.Eq:
case ExpressionKind.NotEq:
case ExpressionKind.GreaterThanOrEqual:
case ExpressionKind.GreaterThan:
case ExpressionKind.LessThanOrEqual:
case ExpressionKind.LessThan:
return GenerateUserDefinedComparisonOperator(expr);
case ExpressionKind.DelegateSubtract:
case ExpressionKind.Subtract:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED;
break;
case ExpressionKind.DelegateAdd:
case ExpressionKind.Add:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED;
break;
case ExpressionKind.Multiply:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED;
break;
default:
throw Error.InternalCompilerError();
}
Expr p1 = expr.OptionalLeftChild;
Expr p2 = expr.OptionalRightChild;
Expr udcall = expr.OptionalUserDefinedCall;
if (udcall != null)
{
Debug.Assert(udcall.Kind == ExpressionKind.Call || udcall.Kind == ExpressionKind.UserLogicalOp);
if (udcall is ExprCall ascall)
{
ExprList args = (ExprList)ascall.OptionalArguments;
Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
p1 = args.OptionalElement;
p2 = args.OptionalNextListNode;
}
else
{
ExprUserLogicalOp userLogOp = udcall as ExprUserLogicalOp;
Debug.Assert(userLogOp != null);
ExprList args = (ExprList)userLogOp.OperatorCall.OptionalArguments;
Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
p1 = ((ExprWrap)args.OptionalElement).OptionalExpression;
p2 = args.OptionalNextListNode;
}
}
p1 = Visit(p1);
p2 = Visit(p2);
FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2);
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod);
Expr call = GenerateCall(pdm, p1, p2, methodInfo);
// Delegate add/subtract generates a call to Combine/Remove, which returns System.Delegate,
// not the operand delegate CType. We must cast to the delegate CType.
if (expr.Kind == ExpressionKind.DelegateSubtract || expr.Kind == ExpressionKind.DelegateAdd)
{
Expr pTypeOf = CreateTypeOf(expr.Type);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf);
}
return call;
}
private Expr GenerateUserDefinedUnaryOperator(ExprUnaryOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
Expr arg = expr.Child;
ExprCall call = (ExprCall)expr.OptionalUserDefinedCall;
if (call != null)
{
// Use the actual argument of the call; it may contain user-defined
// conversions or be a bound lambda, and that will not be in the original
// argument stashed away in the left child of the operator.
arg = call.OptionalArguments;
}
Debug.Assert(arg != null && arg.Kind != ExpressionKind.List);
switch (expr.Kind)
{
case ExpressionKind.True:
case ExpressionKind.False:
return Visit(call);
case ExpressionKind.UnaryPlus:
pdm = PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED;
break;
case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break;
case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break;
case ExpressionKind.DecimalNegate:
case ExpressionKind.Negate:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED;
break;
case ExpressionKind.Inc:
case ExpressionKind.Dec:
case ExpressionKind.DecimalInc:
case ExpressionKind.DecimalDec:
pdm = PREDEFMETH.PM_EXPRESSION_CALL;
break;
default:
throw Error.InternalCompilerError();
}
Expr op = Visit(arg);
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod);
if (expr.Kind == ExpressionKind.Inc || expr.Kind == ExpressionKind.Dec ||
expr.Kind == ExpressionKind.DecimalInc || expr.Kind == ExpressionKind.DecimalDec)
{
return GenerateCall(pdm, null, methodInfo, GenerateParamsArray(op, PredefinedType.PT_EXPRESSION));
}
return GenerateCall(pdm, op, methodInfo);
}
private Expr GenerateUserDefinedComparisonOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
switch (expr.Kind)
{
case ExpressionKind.StringEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break;
case ExpressionKind.StringNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break;
case ExpressionKind.DelegateEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break;
case ExpressionKind.DelegateNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break;
case ExpressionKind.Eq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break;
case ExpressionKind.NotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break;
case ExpressionKind.LessThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED; break;
case ExpressionKind.LessThan: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED; break;
case ExpressionKind.GreaterThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED; break;
case ExpressionKind.GreaterThan: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED; break;
default:
throw Error.InternalCompilerError();
}
Expr p1 = expr.OptionalLeftChild;
Expr p2 = expr.OptionalRightChild;
if (expr.OptionalUserDefinedCall != null)
{
ExprCall udcall = (ExprCall)expr.OptionalUserDefinedCall;
ExprList args = (ExprList)udcall.OptionalArguments;
Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
p1 = args.OptionalElement;
p2 = args.OptionalNextListNode;
}
p1 = Visit(p1);
p2 = Visit(p2);
FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2);
Expr lift = ExprFactory.CreateBoolConstant(false); // We never lift to null in C#.
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod);
return GenerateCall(pdm, p1, p2, lift, methodInfo);
}
private Expr GenerateConversion(Expr arg, CType CType, bool bChecked) =>
GenerateConversionWithSource(Visit(arg), CType, bChecked || arg.isChecked());
private static Expr GenerateConversionWithSource(Expr pTarget, CType pType, bool bChecked)
{
PREDEFMETH pdm = bChecked ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT;
Expr pTypeOf = CreateTypeOf(pType);
return GenerateCall(pdm, pTarget, pTypeOf);
}
private Expr GenerateValueAccessConversion(Expr pArgument)
{
Debug.Assert(pArgument != null);
CType pStrippedTypeOfArgument = pArgument.Type.StripNubs();
Expr pStrippedTypeExpr = CreateTypeOf(pStrippedTypeOfArgument);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, Visit(pArgument), pStrippedTypeExpr);
}
private Expr GenerateUserDefinedConversion(Expr arg, CType type, MethWithInst method)
{
Expr target = Visit(arg);
return GenerateUserDefinedConversion(arg, type, target, method);
}
private static Expr GenerateUserDefinedConversion(Expr arg, CType CType, Expr target, MethWithInst method)
{
// The user-defined explicit conversion from enum? to decimal or decimal? requires
// that we convert the enum? to its nullable underlying CType.
if (isEnumToDecimalConversion(arg.Type, CType))
{
// Special case: If we have enum? to decimal? then we need to emit
// a conversion from enum? to its nullable underlying CType first.
// This is unfortunate; we ought to reorganize how conversions are
// represented in the Expr tree so that this is more transparent.
// converting an enum to its underlying CType never fails, so no need to check it.
CType underlyingType = arg.Type.StripNubs().UnderlyingEnumType;
CType nullableType = TypeManager.GetNullable(underlyingType);
Expr typeofNubEnum = CreateTypeOf(nullableType);
target = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, target, typeofNubEnum);
}
// If the methodinfo does not return the target CType AND this is not a lifted conversion
// from one value CType to another, then we need to wrap the whole thing in another conversion,
// e.g. if we have a user-defined conversion from int to S? and we have (S)myint, then we need to generate
// Convert(Convert(myint, typeof(S?), op_implicit), typeof(S))
CType pMethodReturnType = TypeManager.SubstType(method.Meth().RetType,
method.GetType(), method.TypeArgs);
bool fDontLiftReturnType = (pMethodReturnType == CType || (IsNullableValueType(arg.Type) && IsNullableValueType(CType)));
Expr typeofInner = CreateTypeOf(fDontLiftReturnType ? CType : pMethodReturnType);
Expr methodInfo = ExprFactory.CreateMethodInfo(method);
PREDEFMETH pdmInner = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED;
Expr callUserDefinedConversion = GenerateCall(pdmInner, target, typeofInner, methodInfo);
if (fDontLiftReturnType)
{
return callUserDefinedConversion;
}
PREDEFMETH pdmOuter = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT;
Expr typeofOuter = CreateTypeOf(CType);
return GenerateCall(pdmOuter, callUserDefinedConversion, typeofOuter);
}
private Expr GenerateUserDefinedConversion(ExprUserDefinedConversion pExpr, Expr pArgument)
{
Expr pCastCall = pExpr.UserDefinedCall;
Expr pCastArgument = pExpr.Argument;
Expr pConversionSource;
if (!isEnumToDecimalConversion(pArgument.Type, pExpr.Type)
&& IsNullableValueAccess(pCastArgument, pArgument))
{
// We have an implicit conversion of nullable CType to the value CType, generate a convert node for it.
pConversionSource = GenerateValueAccessConversion(pArgument);
}
else
{
ExprCall call = pCastCall as ExprCall;
Expr pUDConversion = call?.PConversions;
if (pUDConversion != null)
{
if (pUDConversion is ExprCall convCall)
{
Expr pUDConversionArgument = convCall.OptionalArguments;
if (IsNullableValueAccess(pUDConversionArgument, pArgument))
{
pConversionSource = GenerateValueAccessConversion(pArgument);
}
else
{
pConversionSource = Visit(pUDConversionArgument);
}
return GenerateConversionWithSource(pConversionSource, pCastCall.Type, call.isChecked());
}
// This can happen if we have a UD conversion from C to, say, int,
// and we have an explicit cast to decimal?. The conversion should
// then be bound as two chained user-defined conversions.
Debug.Assert(pUDConversion is ExprUserDefinedConversion);
// Just recurse.
return GenerateUserDefinedConversion((ExprUserDefinedConversion)pUDConversion, pArgument);
}
pConversionSource = Visit(pCastArgument);
}
return GenerateUserDefinedConversion(pCastArgument, pExpr.Type, pConversionSource, pExpr.UserDefinedCallMethod);
}
private static Expr GenerateParameter(string name, CType CType)
{
SymbolLoader.GetPredefindType(PredefinedType.PT_STRING); // force an ensure state
ExprConstant nameString = ExprFactory.CreateStringConstant(name);
ExprTypeOf pTypeOf = CreateTypeOf(CType);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PARAMETER, pTypeOf, nameString);
}
private static MethodSymbol GetPreDefMethod(PREDEFMETH pdm) => PredefinedMembers.GetMethod(pdm);
private static ExprTypeOf CreateTypeOf(CType type) => ExprFactory.CreateTypeOf(type);
private static Expr CreateWraps(ExprBoundLambda anonmeth)
{
Expr sequence = null;
for (Symbol sym = anonmeth.ArgumentScope.firstChild; sym != null; sym = sym.nextChild)
{
if (!(sym is LocalVariableSymbol local))
{
continue;
}
Debug.Assert(anonmeth.Expression != null);
Expr create = GenerateParameter(local.name.Text, local.GetType());
local.wrap = ExprFactory.CreateWrap(create);
Expr save = ExprFactory.CreateSave(local.wrap);
if (sequence == null)
{
sequence = save;
}
else
{
sequence = ExprFactory.CreateSequence(sequence, save);
}
}
return sequence;
}
private Expr GenerateConstructor(ExprCall expr)
{
Debug.Assert(expr != null);
Debug.Assert(expr.MethWithInst.Meth().IsConstructor());
Expr constructorInfo = ExprFactory.CreateMethodInfo(expr.MethWithInst);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params);
}
private Expr GenerateArgsList(Expr oldArgs)
{
Expr newArgs = null;
Expr newArgsTail = newArgs;
for (ExpressionIterator it = new ExpressionIterator(oldArgs); !it.AtEnd(); it.MoveNext())
{
Expr oldArg = it.Current();
ExprFactory.AppendItemToList(Visit(oldArg), ref newArgs, ref newArgsTail);
}
return newArgs;
}
private Expr GenerateIndexList(Expr oldIndices)
{
CType intType = SymbolLoader.GetPredefindType(PredefinedType.PT_INT);
Expr newIndices = null;
Expr newIndicesTail = newIndices;
for (ExpressionIterator it = new ExpressionIterator(oldIndices); !it.AtEnd(); it.MoveNext())
{
Expr newIndex = it.Current();
if (newIndex.Type != intType)
{
newIndex = ExprFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, intType, newIndex);
newIndex.Flags |= EXPRFLAG.EXF_CHECKOVERFLOW;
}
Expr rewrittenIndex = Visit(newIndex);
ExprFactory.AppendItemToList(rewrittenIndex, ref newIndices, ref newIndicesTail);
}
return newIndices;
}
private static Expr GenerateConstant(Expr expr)
{
EXPRFLAG flags = 0;
AggregateType pObject = SymbolLoader.GetPredefindType(PredefinedType.PT_OBJECT);
if (expr.Type is NullType)
{
ExprTypeOf pTypeOf = CreateTypeOf(pObject);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, expr, pTypeOf);
}
AggregateType stringType = SymbolLoader.GetPredefindType(PredefinedType.PT_STRING);
if (expr.Type != stringType)
{
flags = EXPRFLAG.EXF_BOX;
}
ExprCast cast = ExprFactory.CreateCast(flags, pObject, expr);
ExprTypeOf pTypeOf2 = CreateTypeOf(expr.Type);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, cast, pTypeOf2);
}
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1)
{
MethodSymbol method = GetPreDefMethod(pdm);
// this should be enforced in an earlier pass and the transform pass should not
// be handling this error
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, arg1, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
Expr args = ExprFactory.CreateList(arg1, arg2);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
Expr args = ExprFactory.CreateList(arg1, arg2, arg3);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3, Expr arg4)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
Expr args = ExprFactory.CreateList(arg1, arg2, arg3, arg4);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
private static ExprArrayInit GenerateParamsArray(Expr args, PredefinedType pt)
{
int parameterCount = ExpressionIterator.Count(args);
AggregateType paramsArrayElementType = SymbolLoader.GetPredefindType(pt);
ArrayType paramsArrayType = TypeManager.GetArray(paramsArrayElementType, 1, true);
ExprConstant paramsArrayArg = ExprFactory.CreateIntegerConstant(parameterCount);
return ExprFactory.CreateArrayInit(paramsArrayType, args, paramsArrayArg, new int[] { parameterCount }, parameterCount);
}
private static void FixLiftedUserDefinedBinaryOperators(ExprBinOp expr, ref Expr pp1, ref Expr pp2)
{
// If we have lifted T1 op T2 to T1? op T2?, and we have an expression T1 op T2? or T1? op T2 then
// we need to ensure that the unlifted actual arguments are promoted to their nullable CType.
Debug.Assert(expr != null);
Debug.Assert(pp1 != null);
Debug.Assert(pp1 != null);
Debug.Assert(pp2 != null);
Debug.Assert(pp2 != null);
MethodSymbol method = expr.UserDefinedCallMethod.Meth();
Expr orig1 = expr.OptionalLeftChild;
Expr orig2 = expr.OptionalRightChild;
Debug.Assert(orig1 != null && orig2 != null);
Expr new1 = pp1;
Expr new2 = pp2;
CType fptype1 = method.Params[0];
CType fptype2 = method.Params[1];
CType aatype1 = orig1.Type;
CType aatype2 = orig2.Type;
// Is the operator even a candidate for lifting?
if (!(fptype1 is AggregateType fat1)
|| !fat1.OwningAggregate.IsValueType()
|| !(fptype2 is AggregateType fat2)
|| !fat2.OwningAggregate.IsValueType())
{
return;
}
CType nubfptype1 = TypeManager.GetNullable(fptype1);
CType nubfptype2 = TypeManager.GetNullable(fptype2);
// If we have null op X, or T1 op T2?, or T1 op null, lift first arg to T1?
if (aatype1 is NullType || aatype1 == fptype1 && (aatype2 == nubfptype2 || aatype2 is NullType))
{
new1 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new1, CreateTypeOf(nubfptype1));
}
// If we have X op null, or T1? op T2, or null op T2, lift second arg to T2?
if (aatype2 is NullType || aatype2 == fptype2 && (aatype1 == nubfptype1 || aatype1 is NullType))
{
new2 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new2, CreateTypeOf(nubfptype2));
}
pp1 = new1;
pp2 = new2;
}
private static bool IsNullableValueType(CType pType) =>
pType is NullableType && pType.StripNubs() is AggregateType agg && agg.OwningAggregate.IsValueType();
private static bool IsNullableValueAccess(Expr pExpr, Expr pObject)
{
Debug.Assert(pExpr != null);
return pExpr is ExprProperty prop && prop.MemberGroup.OptionalObject == pObject && pObject.Type is NullableType;
}
private static bool isEnumToDecimalConversion(CType argtype, CType desttype) =>
argtype.StripNubs().IsEnumType && desttype.StripNubs().IsPredefType(PredefinedType.PT_DECIMAL);
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="LocalContext.cs" company="Asynkron HB">
// Copyright (C) 2015-2016 Asynkron HB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Proto.Mailbox;
using System.Collections.ObjectModel;
namespace Proto
{
public class Context : IMessageInvoker, IContext, ISupervisor
{
private readonly Stack<Receive> _behavior;
private readonly Receive _middleware;
private readonly Func<IActor> _producer;
private readonly ISupervisorStrategy _supervisorStrategy;
private HashSet<PID> _children;
private object _message;
private Receive _receive;
private Timer _receiveTimeoutTimer;
private bool _restarting;
private RestartStatistics _restartStatistics;
private Stack<object> _stash;
private bool _stopping;
private HashSet<PID> _watchers;
private HashSet<PID> _watching;
public Context(Func<IActor> producer, ISupervisorStrategy supervisorStrategy, Receive middleware, PID parent)
{
_producer = producer;
_supervisorStrategy = supervisorStrategy;
_middleware = middleware;
Parent = parent;
_behavior = new Stack<Receive>();
_behavior.Push(ActorReceive);
IncarnateActor();
}
public IReadOnlyCollection<PID> Children => _children?.ToList();
public IActor Actor { get; private set; }
public PID Parent { get; }
public PID Self { get; internal set; }
public object Message
{
get
{
var r = _message as MessageSender;
return r != null ? r.Message : _message;
}
private set { _message = value; }
}
public PID Sender => (_message as MessageSender)?.Sender;
public TimeSpan ReceiveTimeout { get; private set; }
public void Stash()
{
if (_stash == null)
{
_stash = new Stack<object>();
}
_stash.Push(Message);
}
public void Respond(object message)
{
Sender.Tell(message);
}
public PID Spawn(Props props)
{
var id = ProcessRegistry.Instance.NextId();
return SpawnNamed(props, id);
}
public PID SpawnPrefix(Props props, string prefix)
{
var name = prefix + ProcessRegistry.Instance.NextId();
return SpawnNamed(props, name);
}
public PID SpawnNamed(Props props, string name)
{
var pid = props.Spawn($"{Self.Id}/{name}", Self);
if (_children == null)
{
_children = new HashSet<PID>();
}
_children.Add(pid);
Watch(pid);
return pid;
}
public void SetBehavior(Receive receive)
{
_behavior.Clear();
_behavior.Push(receive);
_receive = receive;
}
public void PushBehavior(Receive receive)
{
_behavior.Push(receive);
_receive = receive;
}
public void PopBehavior()
{
if (_behavior.Count <= 1)
{
throw new Exception("Can not unbecome actor base behavior");
}
_receive = _behavior.Pop();
}
public void Watch(PID pid)
{
pid.SendSystemMessage(new Watch(Self));
if (_watching == null)
{
_watching = new HashSet<PID>();
}
_watching.Add(pid);
}
public void Unwatch(PID pid)
{
pid.SendSystemMessage(new Unwatch(Self));
if (_watching == null)
{
_watching = new HashSet<PID>();
}
_watching.Remove(pid);
}
public void SetReceiveTimeout(TimeSpan duration)
{
if (duration == ReceiveTimeout)
{
return;
}
if (duration > TimeSpan.Zero)
{
StopReceiveTimeout();
}
if (duration < TimeSpan.FromMilliseconds(1))
{
duration = TimeSpan.FromMilliseconds(1);
}
ReceiveTimeout = duration;
if (ReceiveTimeout > TimeSpan.Zero)
{
if (_receiveTimeoutTimer == null)
{
_receiveTimeoutTimer = new Timer(ReceiveTimeoutCallback, null, ReceiveTimeout, ReceiveTimeout);
}
else
{
ResetReceiveTimeout();
}
}
}
public Task ReceiveAsync(object message)
{
return ProcessMessageAsync(message);
}
public Task InvokeSystemMessageAsync(object msg)
{
try
{
switch (msg)
{
case Started s:
return InvokeUserMessageAsync(s);
case Stop _:
return HandleStopAsync();
case Terminated t:
return HandleTerminatedAsync(t);
case Watch w:
HandleWatch(w);
return Task.CompletedTask;
case Unwatch uw:
HandleUnwatch(uw);
return Task.CompletedTask;
case Failure f:
HandleFailure(f);
return Task.CompletedTask;
case Restart r:
return HandleRestartAsync();
case SuspendMailbox sm:
return Task.CompletedTask;
case ResumeMailbox rm:
return Task.CompletedTask;
default:
Console.WriteLine("Unknown system message {0}", msg);
return Task.CompletedTask;
}
}
catch (Exception x)
{
Console.WriteLine("Error handling SystemMessage {0}", x);
return Task.CompletedTask;
}
}
public Task InvokeUserMessageAsync(object msg)
{
var influenceTimeout = true;
if (ReceiveTimeout > TimeSpan.Zero)
{
var notInfluenceTimeout = msg is INotInfluenceReceiveTimeout;
influenceTimeout = !notInfluenceTimeout;
if (influenceTimeout)
{
StopReceiveTimeout();
}
}
var res = ProcessMessageAsync(msg);
if (ReceiveTimeout != TimeSpan.Zero && influenceTimeout)
{
//special handle non completed tasks that need to reset ReceiveTimout
if (!res.IsCompleted)
{
return res.ContinueWith(_ => ResetReceiveTimeout());
}
ResetReceiveTimeout();
}
return res;
}
public void EscalateFailure(Exception reason, object message)
{
if (_restartStatistics == null)
{
_restartStatistics = new RestartStatistics(0, null);
}
var failure = new Failure(Self, reason, _restartStatistics);
if (Parent == null)
{
HandleRootFailure(failure);
}
else
{
Self.SendSystemMessage(SuspendMailbox.Instance);
Parent.SendSystemMessage(failure);
}
}
public void EscalateFailure(PID who, Exception reason)
{
Self.SendSystemMessage(SuspendMailbox.Instance);
Parent.SendSystemMessage(new Failure(who, reason, _restartStatistics));
}
internal static Task DefaultReceive(IContext context)
{
var c = (Context)context;
if (c.Message is PoisonPill)
{
c.Self.Stop();
return Proto.Actor.Done;
}
return c._receive(context);
}
private Task ProcessMessageAsync(object msg)
{
Message = msg;
if (_middleware != null)
{
return _middleware(this);
}
return DefaultReceive(this);
}
private void IncarnateActor()
{
_restarting = false;
_stopping = false;
Actor = _producer();
SetBehavior(ActorReceive);
}
private async Task HandleRestartAsync()
{
_stopping = false;
_restarting = true;
await InvokeUserMessageAsync(Restarting.Instance);
if (_children != null)
{
foreach (var child in _children)
{
child.Stop();
}
}
await TryRestartOrTerminateAsync();
}
private void HandleUnwatch(Unwatch uw)
{
_watchers?.Remove(uw.Watcher);
}
private void HandleWatch(Watch w)
{
if (_watchers == null)
{
_watchers = new HashSet<PID>();
}
_watchers.Add(w.Watcher);
}
private void HandleFailure(Failure msg)
{
if (Actor is ISupervisorStrategy supervisor)
{
supervisor.HandleFailure(this, msg.Who, msg.RestartStatistics, msg.Reason);
return;
}
_supervisorStrategy.HandleFailure(this, msg.Who, msg.RestartStatistics, msg.Reason);
}
private async Task HandleTerminatedAsync(Terminated msg)
{
_children.Remove(msg.Who);
_watching.Remove(msg.Who);
await InvokeUserMessageAsync(msg);
await TryRestartOrTerminateAsync();
}
private void HandleRootFailure(Failure failure)
{
Supervision.DefaultStrategy.HandleFailure(this, failure.Who, failure.RestartStatistics, failure.Reason);
}
private async Task HandleStopAsync()
{
_restarting = false;
_stopping = true;
//this is intentional
await InvokeUserMessageAsync(Stopping.Instance);
if (_children != null)
{
foreach (var child in _children)
{
child.Stop();
}
}
await TryRestartOrTerminateAsync();
}
private async Task TryRestartOrTerminateAsync()
{
if (_receiveTimeoutTimer != null)
{
StopReceiveTimeout();
_receiveTimeoutTimer = null;
ReceiveTimeout = TimeSpan.Zero;
}
if (_children?.Count > 0)
{
return;
}
if (_restarting)
{
await RestartAsync();
return;
}
if (_stopping)
{
await StopAsync();
}
}
private async Task StopAsync()
{
ProcessRegistry.Instance.Remove(Self);
//This is intentional
await InvokeUserMessageAsync(Stopped.Instance);
//Notify watchers
}
private async Task RestartAsync()
{
IncarnateActor();
Self.SendSystemMessage(ResumeMailbox.Instance);
await InvokeUserMessageAsync(Started.Instance);
if (_stash != null)
{
while (_stash.Any())
{
var msg = _stash.Pop();
await InvokeUserMessageAsync(msg);
}
}
}
private Task ActorReceive(IContext ctx)
{
return Actor.ReceiveAsync(ctx);
}
private void ResetReceiveTimeout()
{
_receiveTimeoutTimer?.Change(ReceiveTimeout, ReceiveTimeout);
}
private void StopReceiveTimeout()
{
_receiveTimeoutTimer?.Change(-1, -1);
}
private void ReceiveTimeoutCallback(object state)
{
Self.Request(Proto.ReceiveTimeout.Instance, null);
}
}
}
| |
// ---------------------------------------------------------------------------------------------
#region // Copyright (c) 2014, SIL International. All Rights Reserved.
// <copyright from='2008' to='2014' company='SIL International'>
// Copyright (c) 2014, SIL International. All Rights Reserved.
//
// Distributable under the terms of the MIT License (http://sil.mit-license.org/)
// </copyright>
#endregion
//
// This class originated in FieldWorks (under the GNU Lesser General Public License), but we
// have decided to make it avaialble in SIL.ScriptureUtils as part of Palaso so it will be more
// readily available to other projects.
// ---------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace SIL.Scripture
{
/// <summary>
/// Manipulate information for standard chatper/verse schemes
/// </summary>
public class VersificationTable
{
private readonly ScrVers scrVers;
private List<int[]> bookList;
private Dictionary<string, string> toStandard;
private Dictionary<string, string> fromStandard;
private static string baseDir;
private static VersificationTable[] versifications = null;
// Names of the versificaiton files. These are in "\My Paratext Projects"
private static string[] versificationFiles = new string[] { "",
"org.vrs", "lxx.vrs", "vul.vrs", "eng.vrs", "rsc.vrs", "rso.vrs", "oth.vrs",
"oth2.vrs", "oth3.vrs", "oth4.vrs", "oth5.vrs", "oth6.vrs", "oth7.vrs", "oth8.vrs",
"oth9.vrs", "oth10.vrs", "oth11.vrs", "oth12.vrs", "oth13.vrs", "oth14.vrs",
"oth15.vrs", "oth16.vrs", "oth17.vrs", "oth18.vrs", "oth19.vrs", "oth20.vrs",
"oth21.vrs", "oth22.vrs", "oth23.vrs", "oth24.vrs" };
/// ------------------------------------------------------------------------------------
/// <summary>
/// This method should be called once before an application accesses anything that
/// requires versification info.
/// TODO: Paratext needs to call this with ScrTextCollection.SettingsDirectory.
/// </summary>
/// <param name="vrsFolder">Path to the folder containing the .vrs files</param>
/// ------------------------------------------------------------------------------------
public static void Initialize(string vrsFolder)
{
baseDir = vrsFolder;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Get the versification table for this versification
/// </summary>
/// <param name="vers"></param>
/// <returns></returns>
/// ------------------------------------------------------------------------------------
public static VersificationTable Get(ScrVers vers)
{
Debug.Assert(vers != ScrVers.Unknown);
if (versifications == null)
versifications = new VersificationTable[versificationFiles.GetUpperBound(0)];
// Read versification table if not already read
if (versifications[(int)vers] == null)
{
versifications[(int)vers] = new VersificationTable(vers);
ReadVersificationFile(FileName(vers), versifications[(int)vers]);
}
return versifications[(int)vers];
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Read versification file and "add" its entries.
/// At the moment we only do this once. Eventually we will call this twice.
/// Once for the standard versification, once for custom entries in versification.vrs
/// file for this project.
/// </summary>
/// <param name="fileName"></param>
/// <param name="versification"></param>
/// ------------------------------------------------------------------------------------
private static void ReadVersificationFile(string fileName, VersificationTable versification)
{
using (TextReader reader = new StreamReader(fileName))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
line = line.Trim();
if (line == "" || line[0] == '#')
continue;
if (line.Contains("="))
ParseMappingLine(fileName, versification, line);
else
ParseChapterVerseLine(fileName, versification, line);
}
}
}
// Parse lines mapping from this versification to standard versification
// GEN 1:10 = GEN 2:11
// GEN 1:10-13 = GEN 2:11-14
private static void ParseChapterVerseLine(string fileName, VersificationTable versification, string line)
{
string[] parts = line.Split(' ');
int bookNum = BCVRef.BookToNumber(parts[0]);
if (bookNum == -1)
return; // Deuterocanonical books not supported
if (bookNum == 0)
throw new Exception("Invalid [" + parts[0] + "] " + fileName);
while (versification.bookList.Count < bookNum)
versification.bookList.Add(new int[1] { 1 });
List<int> verses = new List<int>();
for (int i = 1; i <= parts.GetUpperBound(0); ++i)
{
string[] pieces = parts[i].Split(':');
int verseCount;
if (pieces.GetUpperBound(0) != 1 ||
!int.TryParse(pieces[1], out verseCount) || verseCount <= 0)
{
throw new Exception("Invalid [" + line + "] " + fileName);
}
verses.Add(verseCount);
}
versification.bookList[bookNum - 1] = verses.ToArray();
}
// Parse lines giving number of verses for each chapter like
// GEN 1:10 2:23 ...
private static void ParseMappingLine(string fileName, VersificationTable versification, string line)
{
try
{
string[] parts = line.Split('=');
string[] leftPieces = parts[0].Trim().Split('-');
string[] rightPieces = parts[1].Trim().Split('-');
BCVRef left = new BCVRef(leftPieces[0]);
int leftLimit = leftPieces.GetUpperBound(0) == 0 ? 0 : int.Parse(leftPieces[1]);
BCVRef right = new BCVRef(rightPieces[0]);
while (true)
{
versification.toStandard[left.ToString()] = right.ToString();
versification.fromStandard[right.ToString()] = left.ToString();
if (left.Verse >= leftLimit)
break;
left.Verse = left.Verse + 1;
right.Verse = right.Verse + 1;
}
}
catch
{
// ENHANCE: Make it so the TE version of Localizer can have its own resources for stuff
// like this.
throw new Exception("Invalid [" + line + "] " + fileName);
}
}
/// <summary>
/// Gets the name of this requested versification file.
/// </summary>
/// <param name="vers">Versification scheme</param>
public static string GetFileNameForVersification(ScrVers vers)
{
return versificationFiles[(int)vers];
}
// Get path of this versification file.
// Fall back to eng.vrs if not present.
private static string FileName(ScrVers vers)
{
if (baseDir == null)
throw new InvalidOperationException("VersificationTable.Initialize must be called first");
string fileName = Path.Combine(baseDir, GetFileNameForVersification(vers));
if (!File.Exists(fileName))
fileName = Path.Combine(baseDir, GetFileNameForVersification(ScrVers.English));
return fileName;
}
// Create empty versification table
private VersificationTable(ScrVers vers)
{
this.scrVers = vers;
bookList = new List<int[]>();
toStandard = new Dictionary<string, string>();
fromStandard = new Dictionary<string, string>();
}
public int LastBook()
{
return bookList.Count;
}
/// <summary>
/// Last chapter number in this book.
/// </summary>
/// <param name="bookNum"></param>
/// <returns></returns>
public int LastChapter(int bookNum)
{
if (bookNum <= 0)
return 0;
if (bookNum - 1 >= bookList.Count)
return 1;
int[] chapters = bookList[bookNum - 1];
return chapters.GetUpperBound(0) + 1;
}
/// <summary>
/// Last verse number in this book/chapter.
/// </summary>
/// <param name="bookNum"></param>
/// <param name="chapterNum"></param>
/// <returns></returns>
public int LastVerse(int bookNum, int chapterNum)
{
if (bookNum <= 0)
return 0;
if (bookNum - 1 >= bookList.Count)
return 1;
int[] chapters = bookList[bookNum - 1];
// Chapter "0" is the intro material. Pretend that it has 1 verse.
if (chapterNum - 1 > chapters.GetUpperBound(0) || chapterNum < 1)
return 1;
return chapters[chapterNum - 1];
}
/// <summary>
/// Change the passed VerseRef to be this versification.
/// </summary>
/// <param name="vref"></param>
public void ChangeVersification(IVerseReference vref)
{
if (vref.Versification == scrVers)
return;
// Map from existing to standard versification
string verse = vref.ToString();
string verse2;
Get(vref.Versification).toStandard.TryGetValue(verse, out verse2);
if (verse2 == null)
verse2 = verse;
// Map from standard versification to this versification
string verse3;
fromStandard.TryGetValue(verse2, out verse3);
if (verse3 == null)
verse3 = verse2;
// If verse has changed, parse new value
if (verse != verse3)
vref.Parse(verse3);
vref.Versification = scrVers;
}
}
}
| |
// These interfaces serve as an extension to the BCL's SymbolStore interfaces.
namespace Luma.SimpleEntity.Tools.Pdb.SymStore
{
using System;
using System.Diagnostics.SymbolStore;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
[
ComImport,
Guid("AA544d42-28CB-11d3-bd22-0000f80849bd"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)
]
internal interface ISymUnmanagedBinder
{
// These methods will often return error HRs in common cases.
// If there are no symbols for the given target, a failing hr is returned.
// This is pretty common.
//
// Using PreserveSig and manually handling error cases provides a big performance win.
// Far fewer exceptions will be thrown and caught.
// Exceptions should be reserved for truely "exceptional" cases.
[PreserveSig]
int GetReaderForFile(IntPtr importer,
[MarshalAs(UnmanagedType.LPWStr)] String filename,
[MarshalAs(UnmanagedType.LPWStr)] String SearchPath,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal);
[PreserveSig]
int GetReaderFromStream(IntPtr importer,
IStream stream,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal);
}
[
ComImport,
Guid("ACCEE350-89AF-4ccb-8B40-1C2C4C6F9434"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)
]
internal interface ISymUnmanagedBinder2 : ISymUnmanagedBinder
{
// ISymUnmanagedBinder methods (need to define the base interface methods also, per COM interop requirements)
[PreserveSig]
new int GetReaderForFile(IntPtr importer,
[MarshalAs(UnmanagedType.LPWStr)] String filename,
[MarshalAs(UnmanagedType.LPWStr)] String SearchPath,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal);
[PreserveSig]
new int GetReaderFromStream(IntPtr importer,
IStream stream,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal);
// ISymUnmanagedBinder2 methods
[PreserveSig]
int GetReaderForFile2(IntPtr importer,
[MarshalAs(UnmanagedType.LPWStr)] String fileName,
[MarshalAs(UnmanagedType.LPWStr)] String searchPath,
int searchPolicy,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader pRetVal);
}
[
ComImport,
Guid("28AD3D43-B601-4d26-8A1B-25F9165AF9D7"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)
]
internal interface ISymUnmanagedBinder3 : ISymUnmanagedBinder2
{
// ISymUnmanagedBinder methods (need to define the base interface methods also, per COM interop requirements)
[PreserveSig]
new int GetReaderForFile(IntPtr importer,
[MarshalAs(UnmanagedType.LPWStr)] String filename,
[MarshalAs(UnmanagedType.LPWStr)] String SearchPath,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal);
[PreserveSig]
new int GetReaderFromStream(IntPtr importer,
IStream stream,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal);
// ISymUnmanagedBinder2 methods (need to define the base interface methods also, per COM interop requirements)
[PreserveSig]
new int GetReaderForFile2(IntPtr importer,
[MarshalAs(UnmanagedType.LPWStr)] String fileName,
[MarshalAs(UnmanagedType.LPWStr)] String searchPath,
int searchPolicy,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader pRetVal);
// ISymUnmanagedBinder3 methods
[PreserveSig]
int GetReaderFromCallback(IntPtr importer,
[MarshalAs(UnmanagedType.LPWStr)] String fileName,
[MarshalAs(UnmanagedType.LPWStr)] String searchPath,
int searchPolicy,
[MarshalAs(UnmanagedType.IUnknown)] object callback,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader pRetVal);
}
//// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder"]/*' />
internal class SymbolBinder: ISymbolBinder1, ISymbolBinder2
{
ISymUnmanagedBinder m_binder;
protected static readonly Guid CLSID_CorSymBinder = new Guid("0A29FF9E-7F9C-4437-8B11-F424491E3931");
//// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.SymbolBinder"]/*' />
public SymbolBinder()
{
Type binderType = Type.GetTypeFromCLSID(CLSID_CorSymBinder);
object comBinder = (ISymUnmanagedBinder)Activator.CreateInstance(binderType);
m_binder = (ISymUnmanagedBinder)comBinder;
}
/// <summary>
/// Create a SymbolBinder given the underling COM object for ISymUnmanagedBinder
/// </summary>
/// <param name="comBinderObject"></param>
/// <remarks>Note that this could be protected, but C# doesn't have a way to express "internal AND
/// protected", just "internal OR protected"</remarks>
internal SymbolBinder(ISymUnmanagedBinder comBinderObject)
{
// We should not wrap null instances
if (comBinderObject == null)
throw new ArgumentNullException("comBinderObject");
m_binder = comBinderObject;
}
//// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReader"]/*' />
public ISymbolReader GetReader(IntPtr importer, String filename,
String searchPath)
{
ISymUnmanagedReader reader = null;
int hr = m_binder.GetReaderForFile(importer, filename, searchPath, out reader);
if (IsFailingResultNormal(hr))
{
return null;
}
Marshal.ThrowExceptionForHR(hr);
return new SymReader(reader);
}
//// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderForFile"]/*' />
public ISymbolReader GetReaderForFile(Object importer, String filename,
String searchPath)
{
ISymUnmanagedReader reader = null;
IntPtr uImporter = IntPtr.Zero;
try
{
uImporter = Marshal.GetIUnknownForObject(importer);
int hr = m_binder.GetReaderForFile(uImporter, filename, searchPath, out reader);
if (IsFailingResultNormal(hr))
{
return null;
}
Marshal.ThrowExceptionForHR(hr);
}
finally
{
if (uImporter != IntPtr.Zero)
Marshal.Release(uImporter);
}
return new SymReader(reader);
}
//// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderForFile1"]/*' />
public ISymbolReader GetReaderForFile(Object importer, String fileName,
String searchPath, SymSearchPolicies searchPolicy)
{
ISymUnmanagedReader symReader = null;
IntPtr uImporter = IntPtr.Zero;
try
{
uImporter = Marshal.GetIUnknownForObject(importer);
int hr = ((ISymUnmanagedBinder2)m_binder).GetReaderForFile2(uImporter, fileName, searchPath, (int)searchPolicy, out symReader);
if (IsFailingResultNormal(hr))
{
return null;
}
Marshal.ThrowExceptionForHR(hr);
}
finally
{
if (uImporter != IntPtr.Zero)
Marshal.Release(uImporter);
}
return new SymReader(symReader);
}
//// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderForFile2"]/*' />
public ISymbolReader GetReaderForFile(Object importer, String fileName,
String searchPath, SymSearchPolicies searchPolicy,
object callback)
{
ISymUnmanagedReader reader = null;
IntPtr uImporter = IntPtr.Zero;
try
{
uImporter = Marshal.GetIUnknownForObject(importer);
int hr = ((ISymUnmanagedBinder3)m_binder).GetReaderFromCallback(uImporter, fileName, searchPath, (int)searchPolicy, callback, out reader);
if (IsFailingResultNormal(hr))
{
return null;
}
Marshal.ThrowExceptionForHR(hr);
}
finally {
if (uImporter != IntPtr.Zero)
Marshal.Release(uImporter);
}
return new SymReader(reader);
}
//// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderFromStream"]/*' />
public ISymbolReader GetReaderFromStream(Object importer, IStream stream)
{
ISymUnmanagedReader reader = null;
IntPtr uImporter = IntPtr.Zero;
try
{
uImporter = Marshal.GetIUnknownForObject(importer);
int hr = ((ISymUnmanagedBinder2)m_binder).GetReaderFromStream(uImporter, stream, out reader);
if (IsFailingResultNormal(hr))
{
return null;
}
Marshal.ThrowExceptionForHR(hr);
}
finally
{
if (uImporter != IntPtr.Zero)
Marshal.Release(uImporter);
}
return new SymReader(reader);
}
/// <summary>
/// Get an ISymbolReader interface given a raw COM symbol reader object.
/// </summary>
/// <param name="reader">A COM object implementing ISymUnmanagedReader</param>
/// <returns>The ISybmolReader interface wrapping the provided COM object</returns>
/// <remarks>This method is on SymbolBinder because it's conceptually similar to the
/// other methods for creating a reader. It does not, however, actually need to use the underlying
/// Binder, so it could be on SymReader instead (but we'd have to make it a public class instead of
/// internal).</remarks>
public static ISymbolReader GetReaderFromCOM(Object reader)
{
return new SymReader((ISymUnmanagedReader)reader);
}
private static bool IsFailingResultNormal(int hr)
{
// If a pdb is not found, that's a pretty common thing.
if (hr == unchecked((int)0x806D0005)) // E_PDB_NOT_FOUND
{
return true;
}
// Other fairly common things may happen here, but we don't want to hide
// this from the programmer.
// You may get 0x806D0014 if the pdb is there, but just old (mismatched)
// Or if you ask for the symbol information on something that's not an assembly.
// If that may happen for your application, wrap calls to GetReaderForFile in
// try-catch(COMException) blocks and use the error code in the COMException to report error.
return false;
}
}
}
| |
/*
* 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 NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client.Tests;
using Apache.Geode.Client;
using System;
namespace Apache.Geode.Client.UnitTests
{
[TestFixture]
[Category("group3")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientDurableCqTests : ThinClientRegionSteps
{
#region Private Members
private UnitProcess m_client1 = null;
private UnitProcess m_client2 = null;
private string[] m_client1DurableCqNames = { "client1DurableCQ1", "client1DurableCQ2", "client1DurableCQ3", "client1DurableCQ4", "client1DurableCQ5", "client1DurableCQ6", "client1DurableCQ7", "client1DurableCQ8" };
private string[] m_client2DurableCqNames = { "client2DurableCQ1", "client2DurableCQ2", "client2DurableCQ3", "client2DurableCQ4", "client2DurableCQ5", "client2DurableCQ6", "client2DurableCQ7", "client2DurableCQ8" };
private static string[] QueryRegionNames = { "ListDurableCqs" };
private static int m_NumberOfCqs = 110;
#endregion
#region Test helper methods
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2 };
}
public void InitDurableClient(string locators, int redundancyLevel,
string durableClientId, int durableTimeout)
{
CacheHelper.InitConfigForDurable_Pool(locators, redundancyLevel, durableClientId, durableTimeout);
CacheHelper.CreateTCRegion_Pool(QueryRegionNames[0], true, true, (ICacheListener<object, object>)null, CacheHelper.Locators, "__TESTPOOL1_", true);
}
public void RegisterCqsClient1(bool isRecycle)
{
Util.Log("Registering Cqs for client1.");
CqAttributesFactory<object, object> cqAf = new CqAttributesFactory<object, object>();
CqAttributes<object, object> attributes = cqAf.Create();
QueryService<object, object> qs = Client.PoolManager.Find("__TESTPOOL1_").GetQueryService<object, object>();
if (!isRecycle)
{
qs.NewCq(m_client1DurableCqNames[0], "Select * From /" + QueryRegionNames[0] + " where id = 1", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[1], "Select * From /" + QueryRegionNames[0] + " where id = 10", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[2], "Select * From /" + QueryRegionNames[0], attributes, false).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[3], "Select * From /" + QueryRegionNames[0] + " where id = 3", attributes, false).ExecuteWithInitialResults();
}
else
{
qs.NewCq(m_client1DurableCqNames[4], "Select * From /" + QueryRegionNames[0] + " where id = 1", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[5], "Select * From /" + QueryRegionNames[0] + " where id = 10", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[6], "Select * From /" + QueryRegionNames[0], attributes, false).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[7], "Select * From /" + QueryRegionNames[0] + " where id = 3", attributes, false).ExecuteWithInitialResults();
}
}
public void RegisterCqsClient1MultipleChunks()
{
Util.Log("Registering Cqs for client1 for multiple chunks.");
CqAttributesFactory<object, object> cqAf = new CqAttributesFactory<object, object>();
CqAttributes<object, object> attributes = cqAf.Create();
QueryService<object, object> qs = Client.PoolManager.Find("__TESTPOOL1_").GetQueryService<object, object>();
for (int i = 0; i < m_NumberOfCqs; i++)
qs.NewCq("MyCq_" + i.ToString(), "Select * From /" + QueryRegionNames[0] + " where id = 1", attributes, true).ExecuteWithInitialResults();
}
public void RegisterCqsClient2(bool isRecycle)
{
Util.Log("Registering Cqs for client2.");
CqAttributesFactory<object, object> cqAf = new CqAttributesFactory<object, object>();
CqAttributes<object, object> attributes = cqAf.Create();
QueryService<object, object> qs = Client.PoolManager.Find("__TESTPOOL1_").GetQueryService<object, object>();
if (!isRecycle)
{
qs.NewCq(m_client2DurableCqNames[0], "Select * From /" + QueryRegionNames[0] + " where id = 1", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[1], "Select * From /" + QueryRegionNames[0] + " where id = 10", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[2], "Select * From /" + QueryRegionNames[0], attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[3], "Select * From /" + QueryRegionNames[0] + " where id = 3", attributes, true).ExecuteWithInitialResults();
}
else
{
qs.NewCq(m_client2DurableCqNames[4], "Select * From /" + QueryRegionNames[0] + " where id = 1", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[5], "Select * From /" + QueryRegionNames[0] + " where id = 10", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[6], "Select * From /" + QueryRegionNames[0], attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[7], "Select * From /" + QueryRegionNames[0] + " where id = 3", attributes, true).ExecuteWithInitialResults();
}
}
public void VerifyDurableCqListClient1MultipleChunks()
{
Util.Log("Verifying durable Cqs for client1.");
QueryService<object, object> qs = Client.PoolManager.Find("__TESTPOOL1_").GetQueryService<object, object>();
System.Collections.Generic.List<string> durableCqList = qs.GetAllDurableCqsFromServer();
Assert.AreNotEqual(null, durableCqList);
Assert.AreEqual(m_NumberOfCqs, durableCqList.Count, "Durable CQ count sholuld be %d", m_NumberOfCqs);
Util.Log("Completed verifying durable Cqs for client1.");
}
public void VerifyDurableCqListClient1(bool isRecycle)
{
Util.Log("Verifying durable Cqs for client1.");
QueryService<object, object> qs = Client.PoolManager.Find("__TESTPOOL1_").GetQueryService<object, object>();
System.Collections.Generic.List<string> durableCqList = qs.GetAllDurableCqsFromServer();
Assert.AreNotEqual(null, durableCqList);
if (!isRecycle)
{
Assert.AreEqual(2, durableCqList.Count, "Durable CQ count sholuld be 2");
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[0]));
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[1]));
}
else
{
Assert.AreEqual(4, durableCqList.Count, "Durable CQ count sholuld be 4");
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[0]));
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[1]));
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[4]));
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[5]));
}
Util.Log("Completed verifying durable Cqs for client1.");
}
public void VerifyDurableCqListClient2(bool isRecycle)
{
Util.Log("Verifying durable Cqs for client2.");
QueryService<object, object> qs = Client.PoolManager.Find("__TESTPOOL1_").GetQueryService<object, object>();
System.Collections.Generic.List<string> durableCqList = qs.GetAllDurableCqsFromServer();
Assert.AreNotEqual(null, durableCqList);
if (!isRecycle)
{
Assert.AreEqual(4, durableCqList.Count, "Durable CQ count sholuld be 4");
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[0]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[1]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[2]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[3]));
}
else
{
Assert.AreEqual(8, durableCqList.Count, "Durable CQ count sholuld be 8");
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[0]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[1]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[2]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[3]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[4]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[5]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[6]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[7]));
}
}
public void VerifyEmptyDurableCqListClient1()
{
Util.Log("Verifying empty durable Cqs for client1.");
QueryService<object, object> qs = Client.PoolManager.Find("__TESTPOOL1_").GetQueryService<object, object>();
System.Collections.Generic.List<string> durableCqList = qs.GetAllDurableCqsFromServer();
Assert.AreNotEqual(null, durableCqList);
Assert.AreEqual(0, durableCqList.Count, "Durable CQ list sholuld be empty");
}
private void RunTestGetDurableCqsFromServer()
{
try
{
CacheHelper.SetupJavaServers(true, "cacheserverDurableCqs.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cache server 1 started");
m_client1.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient1", 300);
m_client2.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient2", 300);
Util.Log("client initialization done.");
m_client1.Call(RegisterCqsClient1, false);
m_client2.Call(RegisterCqsClient2, false);
Util.Log("Registered DurableCQs.");
m_client1.Call(VerifyDurableCqListClient1, false);
m_client2.Call(VerifyDurableCqListClient2, false);
Util.Log("Verified DurableCQ List.");
}
finally
{
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
}
}
private void RunTestGetDurableCqsFromServerCyclicClients()
{
try
{
CacheHelper.SetupJavaServers(true, "cacheserverDurableCqs.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cache server 1 started");
m_client1.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient1", 300);
m_client2.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient2", 300);
Util.Log("client initialization done.");
m_client1.Call(RegisterCqsClient1, false);
m_client2.Call(RegisterCqsClient2, false);
Util.Log("Registered DurableCQs.");
m_client1.Call(VerifyDurableCqListClient1, false);
m_client1.Call(VerifyDurableCqListClient1, false);
Util.Log("Verified DurableCQ List.");
m_client1.Call(CacheHelper.CloseKeepAlive);
m_client2.Call(CacheHelper.CloseKeepAlive);
m_client1.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient1", 300);
m_client2.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient2", 300);
Util.Log("client re-initialization done.");
m_client1.Call(RegisterCqsClient1, true);
m_client2.Call(RegisterCqsClient2, true);
Util.Log("Registered DurableCQs.");
m_client1.Call(VerifyDurableCqListClient1, true);
m_client1.Call(VerifyDurableCqListClient1, true);
Util.Log("Verified DurableCQ List.");
}
finally
{
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
}
}
[TestFixtureSetUp]
public override void InitTests()
{
base.InitTests();
}
[TestFixtureTearDown]
public override void EndTests()
{
m_client1.Exit();
m_client2.Exit();
base.EndTests();
}
[SetUp]
public override void InitTest()
{
base.InitTest();
}
[TearDown]
public override void EndTest()
{
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
base.EndTest();
}
#endregion
#region Tests
[Test]
public void TestGetDurableCqsFromServerWithLocator()
{
RunTestGetDurableCqsFromServer();
}
[Test]
public void TestGetDurableCqsFromServerCyclicClientsWithLocator()
{
RunTestGetDurableCqsFromServerCyclicClients();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
#pragma warning disable 414
#pragma warning disable 67
#pragma warning disable 3009
#pragma warning disable 3016
#pragma warning disable 3001
#pragma warning disable 3015
#pragma warning disable 169
#pragma warning disable 649
[assembly: SampleMetadata.SimpleStringCa("assembly")]
public class SimpleTopLevelClass
{
public void MethodWithDefaultParamValue(int a1 = 32)
{
}
}
namespace SampleMetadata
{
public class Outer
{
public class Inner
{
public class ReallyInner
{
}
}
}
public class Outer2
{
public class Inner2
{
protected class ProtectedInner
{
}
internal class InternalInner
{
}
private class PrivateInner
{
}
}
private class PrivateInner2
{
public class ReallyInner2
{
}
}
}
internal class Hidden
{
public class PublicInsideHidden
{
}
}
public class SimpleGenericType<T>
{
}
[SimpleStringCa("type")]
public class GenericTypeWithThreeParameters<X, Y, Z>
{
public GenericTypeWithThreeParameters(int x)
{
}
[SimpleStringCa("ctor")]
private GenericTypeWithThreeParameters(String s)
{
}
[return: SimpleStringCa("return")]
public void SimpleMethod()
{
}
[SimpleStringCa("method")]
public M SimpleGenericMethod<M, N>(X arg1, N arg2)
{
throw null;
}
public X SimpleReadOnlyProperty { get { throw null; } }
[SimpleStringCa("property")]
public Y SimpleMutableProperty
{
get
{
throw null;
}
[SimpleStringCa("setter")]
set
{
throw null;
}
}
[IndexerName("SimpleIndexedProperty")]
public X this[int i1, Y i2] { get { throw null; } }
public int MyField1;
[SimpleStringCa("field")]
public static String MyField2;
private double MyField3 = 0.0;
[SimpleStringCa("event")]
public event Action SimpleEvent
{
add
{
throw null;
}
remove
{
throw null;
}
}
[SimpleStringCa("nestedtype")]
public class InnerType
{
}
public class InnerGenericType<W>
{
}
static GenericTypeWithThreeParameters()
{
}
}
public class Derived : SampleMetadata.Extra.Deep.BaseContainer.SubmergedBaseClass
{
}
public interface IFoo
{
}
public interface IBar
{
}
public interface IComplex : IFoo, IBar, IList, IEnumerable
{
}
public class CFoo : IFoo
{
}
public class GenericTypeWithConstraints<A, B, C, D, E, F, G, H, AA, BB, CC, DD, EE, FF, GG, HH>
where B : CFoo, IList
where C : IList
where D : struct
where E : class
where F : new()
where G : class, new()
where H : IList, new()
where AA : A
where BB : B
where CC : C
// where DD : D // cannot use a "struct"-constrainted generic parameter as a constraint.
where EE : E
where FF : F
where GG : G
where HH : H
{
}
public struct SimpleStruct
{
}
public struct SimpleGenericStruct<T>
{
}
public interface ISimpleGenericInterface<T>
{
}
public class MethodContainer<T>
{
public String Moo(int i, T g, String[] s, IEnumerable<String> e, ref double d, out Object o)
{
throw null;
}
[IndexerName("SimpleIndexedSetterOnlyProperty")]
public int this[String i1, T i2] { set { throw null; } }
}
public enum SimpleEnum
{
Red = 1,
Blue = 2,
Green = 3,
Green_a = 3,
Green_b = 3,
}
public enum ByteEnum : byte
{
Min = 0,
One = 1,
Two = 2,
Max = 0xff,
}
public enum SByteEnum : sbyte
{
Min = -128,
One = 1,
Two = 2,
Max = 127,
}
public enum UInt16Enum : ushort
{
Min = 0,
One = 1,
Two = 2,
Max = 0xffff,
}
public enum Int16Enum : short
{
Min = unchecked((short)0x8000),
One = 1,
Two = 2,
Max = 0x7fff,
}
public enum UInt32Enum : uint
{
Min = 0,
One = 1,
Two = 2,
Max = 0xffffffff,
}
public enum Int32Enum : int
{
Min = unchecked((int)0x80000000),
One = 1,
Two = 2,
Max = 0x7fffffff,
}
public enum UInt64Enum : ulong
{
Min = 0,
One = 1,
Two = 2,
Max = 0xffffffffffffffff,
}
public enum Int64Enum : long
{
Min = unchecked((long)0x8000000000000000L),
One = 1,
Two = 2,
Max = 0x7fffffffffffffff,
}
public class SimpleCaAttribute : Attribute
{
public SimpleCaAttribute()
{
}
}
public class SimpleStringCaAttribute : Attribute
{
public SimpleStringCaAttribute(String s)
{
}
}
public class SimpleCaWithBigCtorAttribute : Attribute
{
public SimpleCaWithBigCtorAttribute(bool b, char c, float f, double d, sbyte sb, short sh, int i, long l, byte by, ushort us, uint ui, ulong ul, String s, Type t)
{
}
}
public class SimpleArrayCaAttribute : Attribute
{
public SimpleArrayCaAttribute(bool[] b) { }
public SimpleArrayCaAttribute(char[] b) { }
public SimpleArrayCaAttribute(float[] b) { }
public SimpleArrayCaAttribute(double[] b) { }
public SimpleArrayCaAttribute(sbyte[] b) { }
public SimpleArrayCaAttribute(short[] b) { }
public SimpleArrayCaAttribute(int[] b) { }
public SimpleArrayCaAttribute(long[] b) { }
public SimpleArrayCaAttribute(byte[] b) { }
public SimpleArrayCaAttribute(ushort[] b) { }
public SimpleArrayCaAttribute(uint[] b) { }
public SimpleArrayCaAttribute(ulong[] b) { }
public SimpleArrayCaAttribute(String[] b) { }
public SimpleArrayCaAttribute(Type[] b) { }
}
public class SimpleObjectArrayCaAttribute : Attribute
{
public SimpleObjectArrayCaAttribute(object[] o) { }
}
public class SimpleEnumCaAttribute : Attribute
{
public SimpleEnumCaAttribute(SimpleEnum e) { }
public SimpleEnumCaAttribute(SimpleEnum[] e) { }
}
public class AnnoyingSpecialCaseAttribute : Attribute
{
public AnnoyingSpecialCaseAttribute(Object o)
{
}
public Object Oops;
}
public class SimpleCaWithNamedParametersAttribute : Attribute
{
public SimpleCaWithNamedParametersAttribute(int i, String s)
{
}
public double DParameter;
public Type TParameter { get; set; }
}
[SimpleCaWithBigCtor(true, 'c', (float)1.5f, 1.5, (sbyte)(-2), (short)(-2), (int)(-2), (long)(-2), (byte)0xfe, (ushort)0xfedc, (uint)0xfedcba98, (ulong)0xfedcba9876543210, "Hello", typeof(IEnumerable<String>))]
public class CaHolder
{
[AnnoyingSpecialCase(SimpleEnum.Blue, Oops = SimpleEnum.Red)]
public class ObjectCa { }
[SimpleObjectArrayCa(new object[] { SimpleEnum.Red, 123 })]
public class ObjectArrayCa { }
[SimpleEnumCa(SimpleEnum.Green)]
public class EnumCa { }
[SimpleEnumCa(new SimpleEnum[] { SimpleEnum.Green, SimpleEnum.Red })]
public class EnumArray { }
[SimpleCaWithNamedParameters(42, "Yo", DParameter = 2.3, TParameter = typeof(IList<String>))]
public class Named { }
[SimpleArrayCa(new bool[] { true, false, true, true, false, false, false, true })]
public class BoolArray { }
[SimpleArrayCa(new char[] { 'a', 'b', 'c', 'd', 'e' })]
public class CharArray { }
[SimpleArrayCa(new byte[] { 1, 2, 0xfe, 0xff })]
public class ByteArray { }
[SimpleArrayCa(new sbyte[] { 1, 2, -2, -1 })]
public class SByteArray { }
[SimpleArrayCa(new ushort[] { 1, 2, 0xfedc })]
public class UShortArray { }
[SimpleArrayCa(new short[] { 1, 2, -2, -1 })]
public class ShortArray { }
[SimpleArrayCa(new uint[] { 1, 2, 0xfedcba98 })]
public class UIntArray { }
[SimpleArrayCa(new int[] { 1, 2, -2, -1 })]
public class IntArray { }
[SimpleArrayCa(new ulong[] { 1, 2, 0xfedcba9876543210 })]
public class ULongArray { }
[SimpleArrayCa(new long[] { 1, 2, -2, -1 })]
public class LongArray { }
[SimpleArrayCa(new float[] { 1.2f, 3.5f })]
public class FloatArray { }
[SimpleArrayCa(new double[] { 1.2, 3.5 })]
public class DoubleArray { }
[SimpleArrayCa(new String[] { "Hello", "There" })]
public class StringArray { }
[SimpleArrayCa(new Type[] { typeof(Object), typeof(String), null })]
public class TypeArray { }
}
public class DefaultValueHolder
{
public static void LotsaDefaults(
bool b = true,
char c = 'a',
sbyte sb = -2,
byte by = 0xfe,
short sh = -2,
ushort ush = 0xfedc,
int i = -2,
uint ui = 0xfedcba98,
long l = -2,
ulong ul = 0xfedcba9876543210,
float f = 1.5f,
double d = 1.5,
String s = "Hello",
String sn = null,
Object o = null,
SimpleEnum e = SimpleEnum.Blue
)
{
}
}
public class SimpleIntCustomAttributeAttribute : Attribute
{
public SimpleIntCustomAttributeAttribute(int a1)
{
}
}
[SimpleIntCustomAttribute(32)]
public class SimpleTypeWithCustomAttribute
{
[SimpleIntCustomAttribute(64)]
public void SimpleMethodWithCustomAttribute()
{
}
}
public interface IMethodImplTest
{
void MethodImplFunc();
}
public class MethodImplTest : IMethodImplTest
{
void IMethodImplTest.MethodImplFunc()
{
}
}
public class GenericOutside<S>
{
public class Inside
{
public class ReallyInside<I>
{
public S TypeS_Field;
public I TypeI_Field;
public class Really2Inside
{
public class Really3Inside<D>
{
public class Really4Inside<O>
{
public GenericTypeWithThreeParameters<S, I, D> TypeSID_Field;
public GenericTypeWithThreeParameters<S, I, O> TypeSIO_Field;
}
}
}
}
}
}
public class NonGenericOutside
{
public class GenericInside<T>
{
}
}
public static class SimpleStaticClass
{
public class NestedInsideSimpleStatic
{
}
public static void Foo(int x)
{
}
}
public static class SimpleGenericStaticClass<T>
{
public class NestedInsideSimpleStatic
{
}
public static void Foo(T x)
{
}
}
}
namespace SampleMetadata.Extra.Deep
{
public class BaseContainer
{
[SimpleStringCa("base")]
public class SubmergedBaseClass
{
}
}
}
namespace SampleMetadata
{
// Create two types with the exact same shape. Ensure that MdTranform and Reflection can
// distinguish the members.
public class DoppleGanger1
{
public DoppleGanger1()
{
}
public void Moo()
{
}
public int Field;
public int Prop { get; set; }
public event Action Event
{
add
{
throw null;
}
remove
{
throw null;
}
}
public class NestedType
{
}
}
public class DoppleGanger2
{
public DoppleGanger2()
{
}
public void Moo()
{
}
public int Field;
public int Prop { get; set; }
public event Action Event
{
add
{
throw null;
}
remove
{
throw null;
}
}
public class NestedType
{
}
}
}
namespace SampleMetadata
{
// Create two types with "identical" methods.
public class ProtoType
{
[SimpleStringCa("1")]
public void Meth()
{
}
public void Foo([SimpleStringCa("p1")] int twin, Object differentTypes)
{
}
}
public class Similar
{
[SimpleStringCa("2")]
public void Meth()
{
}
public void Foo([SimpleStringCa("p2")] int twin, String differentTypes)
{
}
}
}
namespace SampleMetadata
{
public class MethodFamilyIsInstance
{
public void MethodFamily()
{
}
}
public class MethodFamilyIsStatic
{
public static void MethodFamily()
{
}
}
public class MethodFamilyIsPrivate
{
private void MethodFamily()
{
}
}
public class MethodFamilyIsGeneric
{
public void MethodFamily<M1>()
where M1 : IEquatable<M1>
{
}
}
public class MethodFamilyIsAlsoGeneric
{
public void MethodFamily<M2>()
where M2 : IEquatable<M2>
{
}
}
public class MethodFamilyIsUnary
{
public void MethodFamily(int m)
{
}
}
public class MethodFamilyReturnsSomething
{
public String MethodFamily()
{
return null;
}
}
public class MethodFamilyHasCtor1
{
[Circular(1)]
public void MethodFamily()
{
}
}
public class MethodFamilyHasCtor2
{
[Circular(2)]
public void MethodFamily()
{
}
}
}
namespace SampleMetadata
{
[Circular(1)]
public class CircularAttribute : Attribute
{
[Circular(2)]
public CircularAttribute([Circular(3)] int x)
{
}
}
}
namespace SampleMetadata.NS1
{
public class Twin
{
}
}
namespace SampleMetadata.NS2
{
public class Twin
{
}
}
namespace SampleMetadata
{
public class FieldInvokeSampleBase
{
public String InheritedField;
}
public class FieldInvokeSample : FieldInvokeSampleBase
{
public String InstanceField;
public static String StaticField;
public const int LiteralInt32Field = 42;
public const SimpleEnum LiteralEnumField = SimpleEnum.Green;
public const String LiteralStringField = "Hello";
public const Object LiteralNullField = null;
}
public class PropertyInvokeSample
{
public PropertyInvokeSample(String name)
{
this.Name = name;
}
public String InstanceProperty
{
get;
set;
}
public static String StaticProperty
{
get;
set;
}
public String ReadOnlyInstanceProperty
{
get { return "rip:"; }
}
public static String ReadOnlyStaticProperty
{
get { return "rsp"; }
}
[IndexerName("IndexedProperty")]
public String this[int i1, int i2]
{
get
{
return _indexed;
}
set
{
_indexed = value;
}
}
private String _indexed;
public String Name;
}
public class MethodInvokeSample
{
public MethodInvokeSample(String name)
{
this.Name = name;
}
public void InstanceMethod(int x, String s)
{
}
public void InstanceMethodWithSingleParameter(String s)
{
}
public static void StaticMethod(int x, String s)
{
}
public String InstanceFunction(int x, String s)
{
throw null;
}
public static String StaticFunction(int x, String s)
{
throw null;
}
public static String LastStaticCall { get; set; }
public String LastCall { get; set; }
public String Name;
}
}
namespace SampleMetadataEx
{
public enum Color
{
Red = 1,
Green = 2,
Blue = 3,
}
//=========================================================================================
//=========================================================================================
public class DataTypeTestAttribute : Attribute
{
public DataTypeTestAttribute(int i, String s, Type t, Color c, int[] iArray, String[] sArray, Type[] tArray, Color[] cArray)
{
this.I = i;
this.S = s;
this.T = t;
this.C = c;
this.IArray = iArray;
this.SArray = sArray;
this.TArray = tArray;
this.CArray = cArray;
}
public int I { get; private set; }
public String S { get; private set; }
public Type T { get; private set; }
public Color C { get; private set; }
public int[] IArray { get; private set; }
public String[] SArray { get; private set; }
public Type[] TArray { get; private set; }
public Color[] CArray { get; private set; }
}
//=========================================================================================
// Named arguments.
//=========================================================================================
public class NamedArgumentsAttribute : Attribute
{
public NamedArgumentsAttribute()
{
}
public int F1;
public Color F2;
public int P1 { get; set; }
public Color P2 { get; set; }
}
//=========================================================================================
// The annoying special case where the formal parameter type is Object.
//=========================================================================================
public class ObjectTypeTestAttribute : Attribute
{
public ObjectTypeTestAttribute(Object o)
{
this.O = o;
}
public Object O { get; private set; }
public Object F;
public Object P { get; set; }
}
public class BaseAttribute : Attribute
{
public BaseAttribute(String s)
{
S = s;
}
public BaseAttribute(String s, int i)
{
}
public int F;
public int P { get; set; }
public String S { get; private set; }
public sealed override String ToString()
{
throw null;
}
}
public class MidAttribute : BaseAttribute
{
public MidAttribute(String s)
: base(s)
{
}
public MidAttribute(String s, int i)
: base(s, i)
{
}
public new int F;
public new int P { get; set; }
}
public class DerivedAttribute : MidAttribute
{
public DerivedAttribute(String s)
: base(s)
{
}
public new int F;
public new int P { get; set; }
}
public class NonInheritableAttribute : BaseAttribute
{
public NonInheritableAttribute(String s)
: base(s)
{
}
}
public class BaseAmAttribute : Attribute
{
public BaseAmAttribute(String s)
{
S = s;
}
public BaseAmAttribute(String s, int i)
{
}
public String S { get; private set; }
public sealed override String ToString()
{
throw null;
}
}
public class MidAmAttribute : BaseAmAttribute
{
public MidAmAttribute(String s)
: base(s)
{
}
}
public class DerivedAmAttribute : MidAmAttribute
{
public DerivedAmAttribute(String s)
: base(s)
{
}
}
}
namespace SampleMetadataEx
{
public class CaHolder
{
[DataTypeTest(
42,
"FortyTwo",
typeof(IList<String>),
Color.Green,
new int[] { 1, 2, 3 },
new String[] { "One", "Two", "Three" },
new Type[] { typeof(int), typeof(String) },
new Color[] { Color.Red, Color.Blue }
)]
public int DataTypeTest = 1;
[NamedArguments(F1 = 42, F2 = Color.Blue, P1 = 77, P2 = Color.Green)]
public int NamedArgumentsTest = 1;
[ObjectTypeTest(Color.Red, F = Color.Blue, P = Color.Green)]
public int ObjectTest = 1;
[Base("B", F = 1, P = 2)]
public int BaseTest = 1;
[Mid("M", F = 5, P = 6)]
public int MidTest = 1;
[Derived("D", F = 8, P = 9)]
public int DerivedTest = 1;
}
[BaseAttribute("[Base]SearchType.Field")]
[MidAttribute("[Mid]SearchType.Field")]
[DerivedAttribute("[Derived]SearchType.Field")]
public class SearchType1
{
public int Field;
}
[BaseAttribute("[Base]B")]
[MidAttribute("[Mid]B", 42)] // This is hidden by down-level MidAttributes, even though the down-level MidAttributes are using a different .ctor
[DerivedAttribute("[Derived]B")]
[BaseAmAttribute("[BaseAm]B")]
[MidAmAttribute("[MidAm]B")]
[DerivedAmAttribute("[DerivedAm]B")]
public abstract class B
{
[BaseAm("[BaseAm]B.M1()")]
public virtual void M1([BaseAm("[BaseAm]B.M1.x")] int x) { }
[BaseAm("[BaseAm]B.M2()")]
public void M2([BaseAm("[BaseAm]B.M2.x")] int x) { }
[BaseAm("[BaseAm]B.P1")]
public virtual int P1 { get; set; }
[BaseAm("[BaseAm]B.P2")]
public int P2 { get; set; }
[BaseAm("[BaseAm]B.E1")]
public virtual event Action E1 { add { } remove { } }
[BaseAm("[BaseAm]B.E2")]
public event Action E2 { add { } remove { } }
}
[NonInheritable("[Noninheritable]M")]
[MidAttribute("[Mid]M")]
[DerivedAttribute("[Derived]M")]
[MidAmAttribute("[MidAm]M")]
[DerivedAmAttribute("[DerivedAm]M")]
public abstract class M : B
{
public override void M1(int x) { }
public override int P1 { get; set; }
public override event Action E1 { add { } remove { } }
}
[DerivedAttribute("[Derived]D")]
[DerivedAmAttribute("[DerivedAm]D")]
public abstract class D : M, ID
{
public void Foo() { }
public new virtual void M1(int x) { }
public new void M2(int x) { }
public new virtual int P1 { get; set; }
public new int P2 { get; set; }
public new virtual event Action E1 { add { } remove { } }
public new event Action E2 { add { } remove { } }
}
// These attributes won't be inherited as the CA inheritance only walks base classes, not interfaces.
[BaseAttribute("[Base]ID")]
[MidAttribute("[Mid]ID")]
[DerivedAttribute("[Derived]ID")]
[BaseAmAttribute("[BaseAm]ID")]
[MidAmAttribute("[MidAm]ID")]
[DerivedAmAttribute("[DerivedAm]ID")]
public interface ID
{
[BaseAmAttribute("[BaseAm]ID.Foo()")]
void Foo();
}
}
namespace SampleMetadataRex
{
public class DelegateBinding
{
public static void M1()
{
}
public static void M2()
{
}
}
public class MethodLookup
{
public void Moo(int x) { }
public void Moo(String s) { }
public void Moo(String s, int x) { }
}
public interface IFoo
{
void Foo();
void Hidden();
int FooProp { get; set; }
event Action FooEvent;
}
public interface IBar : IFoo
{
void Bar();
new void Hidden();
}
public abstract class CBar : IBar
{
public void Bar()
{
}
public void Hidden()
{
}
public void Foo()
{
}
public int FooProp
{
get
{
throw null;
}
set
{
throw null;
}
}
public event Action FooEvent
{
add { }
remove { }
}
}
public abstract class Base
{
// Instance fields
public int B_InstFieldPublic;
protected int B_InstFieldFamily;
private int B_InstFieldPrivate;
internal int B_InstFieldAssembly;
protected internal int B_InstFieldFamOrAssembly;
// Hidden fields
public int B_HiddenFieldPublic;
protected int B_HiddenFieldFamily;
private int B_HiddenFieldPrivate;
internal int B_HiddenFieldAssembly;
protected internal int B_HiddenFieldFamOrAssembly;
// Static fields
public static int B_StaticFieldPublic;
protected static int B_StaticFieldFamily;
private static int B_StaticFieldPrivate;
internal static int B_StaticFieldAssembly;
protected static internal int B_StaticFieldFamOrAssembly;
// Instance methods
public void B_InstMethPublic() { }
protected void B_InstMethFamily() { }
private void B_InstMethPrivate() { }
internal void B_InstMethAssembly() { }
protected internal void B_InstMethFamOrAssembly() { }
// Hidden methods
public void B_HiddenMethPublic() { }
protected void B_HiddenMethFamily() { }
private void B_HiddenMethPrivate() { }
internal void B_HiddenMethAssembly() { }
protected internal void B_HiddenMethFamOrAssembly() { }
// Static methods
public static void B_StaticMethPublic() { }
protected static void B_StaticMethFamily() { }
private static void B_StaticMethPrivate() { }
internal static void B_StaticMethAssembly() { }
protected static internal void B_StaticMethFamOrAssembly() { }
// Virtual methods
public virtual void B_VirtualMethPublic() { }
protected virtual void B_VirtualMethFamily() { }
internal virtual void B_VirtualMethAssembly() { }
protected virtual internal void B_VirtualMethFamOrAssembly() { }
// Instance properties
public int B_InstPropPublic { get { return 5; } }
protected int B_InstPropFamily { get { return 5; } }
private int B_InstPropPrivate { get { return 5; } }
internal int B_InstPropAssembly { get { return 5; } }
protected internal int B_InstPropFamOrAssembly { get { return 5; } }
// Hidden properties
public int B_HiddenPropPublic { get { return 5; } }
protected int B_HiddenPropFamily { get { return 5; } }
private int B_HiddenPropPrivate { get { return 5; } }
internal int B_HiddenPropAssembly { get { return 5; } }
protected internal int B_HiddenPropFamOrAssembly { get { return 5; } }
// Static properties
public static int B_StaticPropPublic { get { return 5; } }
protected static int B_StaticPropFamily { get { return 5; } }
private static int B_StaticPropPrivate { get { return 5; } }
internal static int B_StaticPropAssembly { get { return 5; } }
protected static internal int B_StaticPropFamOrAssembly { get { return 5; } }
// Virtual properties
public virtual int B_VirtualPropPublic { get { return 5; } }
protected virtual int B_VirtualPropFamily { get { return 5; } }
internal virtual int B_VirtualPropAssembly { get { return 5; } }
protected virtual internal int B_VirtualPropFamOrAssembly { get { return 5; } }
// Instance events
public event Action B_InstEventPublic { add { } remove { } }
protected event Action B_InstEventFamily { add { } remove { } }
private event Action B_InstEventPrivate { add { } remove { } }
internal event Action B_InstEventAssembly { add { } remove { } }
protected internal event Action B_InstEventFamOrAssembly { add { } remove { } }
// Hidden events
public event Action B_HiddenEventPublic { add { } remove { } }
protected event Action B_HiddenEventFamily { add { } remove { } }
private event Action B_HiddenEventPrivate { add { } remove { } }
internal event Action B_HiddenEventAssembly { add { } remove { } }
protected internal event Action B_HiddenEventFamOrAssembly { add { } remove { } }
// Static events
public static event Action B_StaticEventPublic { add { } remove { } }
protected static event Action B_StaticEventFamily { add { } remove { } }
private static event Action B_StaticEventPrivate { add { } remove { } }
internal static event Action B_StaticEventAssembly { add { } remove { } }
protected static internal event Action B_StaticEventFamOrAssembly { add { } remove { } }
// Virtual events
public virtual event Action B_VirtualEventPublic { add { } remove { } }
protected virtual event Action B_VirtualEventFamily { add { } remove { } }
internal virtual event Action B_VirtualEventAssembly { add { } remove { } }
protected virtual internal event Action B_VirtualEventFamOrAssembly { add { } remove { } }
}
public abstract class Mid : Base
{
// Instance fields
public int M_InstFieldPublic;
protected int M_InstFieldFamily;
private int M_InstFieldPrivate;
internal int M_InstFieldAssembly;
protected internal int M_InstFieldFamOrAssembly;
// Hidden fields
public new int B_HiddenFieldPublic;
protected new int B_HiddenFieldFamily;
private /*new*/ int B_HiddenFieldPrivate;
internal new int B_HiddenFieldAssembly;
protected internal new int B_HiddenFieldFamOrAssembly;
// Static fields
public static int M_StaticFieldPublic;
protected static int M_StaticFieldFamily;
private static int M_StaticFieldPrivate;
internal static int M_StaticFieldAssembly;
protected static internal int M_StaticFieldFamOrAssembly;
// Instance methods
public void M_InstMethPublic() { }
protected void M_InstMethFamily() { }
private void M_InstMethPrivate() { }
internal void M_InstMethAssembly() { }
protected internal void M_InstMethFamOrAssembly() { }
// Hidden methods
public new void B_HiddenMethPublic() { }
protected new void B_HiddenMethFamily() { }
private void B_HiddenMethPrivate() { }
internal new void B_HiddenMethAssembly() { }
protected new internal void B_HiddenMethFamOrAssembly() { }
// Static methods
public static void M_StaticMethPublic() { }
protected static void M_StaticMethFamily() { }
private static void M_StaticMethPrivate() { }
internal static void M_StaticMethAssembly() { }
protected static internal void M_StaticMethFamOrAssembly() { }
// Overriding Virtual methods
public override void B_VirtualMethPublic() { }
protected override void B_VirtualMethFamily() { }
internal override void B_VirtualMethAssembly() { }
protected override internal void B_VirtualMethFamOrAssembly() { }
// Instance properties
public int M_InstPropPublic { get { return 5; } }
protected int M_InstPropFamily { get { return 5; } }
private int M_InstPropPrivate { get { return 5; } }
internal int M_InstPropAssembly { get { return 5; } }
protected internal int M_InstPropFamOrAssembly { get { return 5; } }
// Hidden properties
public new int B_HiddenPropPublic { get { return 5; } }
protected new int B_HiddenPropFamily { get { return 5; } }
private int B_HiddenPropPrivate { get { return 5; } }
internal new int B_HiddenPropAssembly { get { return 5; } }
protected new internal int B_HiddenPropFamOrAssembly { get { return 5; } }
// Static properties
public static int M_StaticPropPublic { get { return 5; } }
protected static int M_StaticPropFamily { get { return 5; } }
private static int M_StaticPropPrivate { get { return 5; } }
internal static int M_StaticPropAssembly { get { return 5; } }
protected static internal int M_StaticPropFamOrAssembly { get { return 5; } }
// Overriding Virtual properties
public override int B_VirtualPropPublic { get { return 5; } }
protected override int B_VirtualPropFamily { get { return 5; } }
internal override int B_VirtualPropAssembly { get { return 5; } }
protected override internal int B_VirtualPropFamOrAssembly { get { return 5; } }
// Instance events
public event Action M_InstEventPublic { add { } remove { } }
protected event Action M_InstEventFamily { add { } remove { } }
private event Action M_InstEventPrivate { add { } remove { } }
internal event Action M_InstEventAssembly { add { } remove { } }
protected internal event Action M_InstEventFamOrAssembly { add { } remove { } }
// Hidden events
public new event Action B_HiddenEventPublic { add { } remove { } }
protected new event Action B_HiddenEventFamily { add { } remove { } }
private event Action B_HiddenEventPrivate { add { } remove { } }
internal new event Action B_HiddenEventAssembly { add { } remove { } }
protected new internal event Action B_HiddenEventFamOrAssembly { add { } remove { } }
// Static events
public static event Action M_StaticEventPublic { add { } remove { } }
protected static event Action M_StaticEventFamily { add { } remove { } }
private static event Action M_StaticEventPrivate { add { } remove { } }
internal static event Action M_StaticEventAssembly { add { } remove { } }
protected static internal event Action M_StaticEventFamOrAssembly { add { } remove { } }
// Overriding Virtual events
public override event Action B_VirtualEventPublic { add { } remove { } }
protected override event Action B_VirtualEventFamily { add { } remove { } }
internal override event Action B_VirtualEventAssembly { add { } remove { } }
protected override internal event Action B_VirtualEventFamOrAssembly { add { } remove { } }
}
public abstract class Derived : Mid
{
// New Virtual methods
public new virtual void B_VirtualMethPublic() { }
protected new virtual void B_VirtualMethFamily() { }
internal new virtual void B_VirtualMethAssembly() { }
protected new virtual internal void B_VirtualMethFamOrAssembly() { }
// New Virtual properties
public new virtual int B_VirtualPropPublic { get { return 5; } }
protected new virtual int B_VirtualPropFamily { get { return 5; } }
internal new virtual int B_VirtualPropAssembly { get { return 5; } }
protected new virtual internal int B_VirtualPropFamOrAssembly { get { return 5; } }
// New Virtual events
public new virtual event Action B_VirtualEventPublic { add { } remove { } }
protected new virtual event Action B_VirtualEventFamily { add { } remove { } }
internal new virtual event Action B_VirtualEventAssembly { add { } remove { } }
protected new virtual internal event Action B_VirtualEventFamOrAssembly { add { } remove { } }
}
public abstract class S1
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
public event Action Event1 { add { } remove { } }
public event Action Event2 { add { } remove { } }
protected abstract void M1();
protected virtual void M3() { }
protected virtual void M4() { }
}
public abstract class S2 : S1
{
private new int Prop1 { get; set; }
private new event Action Event1 { add { } remove { } }
protected virtual void M2() { }
protected new virtual void M4() { }
}
public abstract class S3 : S2
{
public static new int Prop2 { get; set; }
public static new event Action Event2 { add { } remove { } }
protected override void M1() { }
protected abstract override void M2();
protected override void M4() { }
}
public abstract class S4 : S3
{
protected override void M2() { }
protected override void M3() { }
protected new virtual void M4() { }
}
public interface INov1
{
void Foo();
}
public interface INov2 : INov1
{
}
public class Nov : INov2
{
public static void S() { }
public void I() { }
public void Foo() { }
}
public class GetRuntimeMethodBase
{
public void Hidden1(int x) { }
public void DefinedInBaseOnly(int x) { }
public void InExact(Object o) { }
public void Close1(String s) { }
public void VarArgs(int x, params Object[] varargs) { }
public void Primitives(int i) { }
}
public class GetRuntimeMethodDerived : GetRuntimeMethodBase
{
public new void Hidden1(int x) { }
public void Close1(Object s) { }
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* 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.
*/
#pragma warning disable 0162
namespace TrueSync.Physics2D
{
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
/// <summary>
/// Friction joint. This is used for top-down friction.
/// It provides 2D translational friction and angular friction.
/// </summary>
public class FrictionJoint : Joint2D
{
// Solver shared
private TSVector2 _linearImpulse;
private FP _angularImpulse;
// Solver temp
private int _indexA;
private int _indexB;
private TSVector2 _rA;
private TSVector2 _rB;
private TSVector2 _localCenterA;
private TSVector2 _localCenterB;
private FP _invMassA;
private FP _invMassB;
private FP _invIA;
private FP _invIB;
private FP _angularMass;
private Mat22 _linearMass;
internal FrictionJoint()
{
JointType = JointType.Friction;
}
/// <summary>
/// Constructor for FrictionJoint.
/// </summary>
/// <param name="bodyA"></param>
/// <param name="bodyB"></param>
/// <param name="anchor"></param>
/// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param>
public FrictionJoint(Body bodyA, Body bodyB, TSVector2 anchor, bool useWorldCoordinates = false)
: base(bodyA, bodyB)
{
JointType = JointType.Friction;
if (useWorldCoordinates)
{
LocalAnchorA = BodyA.GetLocalPoint(anchor);
LocalAnchorB = BodyB.GetLocalPoint(anchor);
}
else
{
LocalAnchorA = anchor;
LocalAnchorB = anchor;
}
}
/// <summary>
/// The local anchor point on BodyA
/// </summary>
public TSVector2 LocalAnchorA { get; set; }
/// <summary>
/// The local anchor point on BodyB
/// </summary>
public TSVector2 LocalAnchorB { get; set; }
public override TSVector2 WorldAnchorA
{
get { return BodyA.GetWorldPoint(LocalAnchorA); }
set { LocalAnchorA = BodyA.GetLocalPoint(value); }
}
public override TSVector2 WorldAnchorB
{
get { return BodyB.GetWorldPoint(LocalAnchorB); }
set { LocalAnchorB = BodyB.GetLocalPoint(value); }
}
/// <summary>
/// The maximum friction force in N.
/// </summary>
public FP MaxForce { get; set; }
/// <summary>
/// The maximum friction torque in N-m.
/// </summary>
public FP MaxTorque { get; set; }
public override TSVector2 GetReactionForce(FP invDt)
{
return invDt * _linearImpulse;
}
public override FP GetReactionTorque(FP invDt)
{
return invDt * _angularImpulse;
}
internal override void InitVelocityConstraints(ref SolverData data)
{
_indexA = BodyA.IslandIndex;
_indexB = BodyB.IslandIndex;
_localCenterA = BodyA._sweep.LocalCenter;
_localCenterB = BodyB._sweep.LocalCenter;
_invMassA = BodyA._invMass;
_invMassB = BodyB._invMass;
_invIA = BodyA._invI;
_invIB = BodyB._invI;
FP aA = data.positions[_indexA].a;
TSVector2 vA = data.velocities[_indexA].v;
FP wA = data.velocities[_indexA].w;
FP aB = data.positions[_indexB].a;
TSVector2 vB = data.velocities[_indexB].v;
FP wB = data.velocities[_indexB].w;
Rot qA = new Rot(aA), qB = new Rot(aB);
// Compute the effective mass matrix.
_rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
_rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
FP mA = _invMassA, mB = _invMassB;
FP iA = _invIA, iB = _invIB;
Mat22 K = new Mat22();
K.ex.x = mA + mB + iA * _rA.y * _rA.y + iB * _rB.y * _rB.y;
K.ex.y = -iA * _rA.x * _rA.y - iB * _rB.x * _rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * _rA.x * _rA.x + iB * _rB.x * _rB.x;
_linearMass = K.Inverse;
_angularMass = iA + iB;
if (_angularMass > 0.0f)
{
_angularMass = 1.0f / _angularMass;
}
if (Settings.EnableWarmstarting)
{
// Scale impulses to support a variable time step.
_linearImpulse *= data.step.dtRatio;
_angularImpulse *= data.step.dtRatio;
TSVector2 P = new TSVector2(_linearImpulse.x, _linearImpulse.y);
vA -= mA * P;
wA -= iA * (MathUtils.Cross(_rA, P) + _angularImpulse);
vB += mB * P;
wB += iB * (MathUtils.Cross(_rB, P) + _angularImpulse);
}
else
{
_linearImpulse = TSVector2.zero;
_angularImpulse = 0.0f;
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
internal override void SolveVelocityConstraints(ref SolverData data)
{
TSVector2 vA = data.velocities[_indexA].v;
FP wA = data.velocities[_indexA].w;
TSVector2 vB = data.velocities[_indexB].v;
FP wB = data.velocities[_indexB].w;
FP mA = _invMassA, mB = _invMassB;
FP iA = _invIA, iB = _invIB;
FP h = data.step.dt;
// Solve angular friction
{
FP Cdot = wB - wA;
FP impulse = -_angularMass * Cdot;
FP oldImpulse = _angularImpulse;
FP maxImpulse = h * MaxTorque;
_angularImpulse = MathUtils.Clamp(_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = _angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
TSVector2 Cdot = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA);
TSVector2 impulse = -MathUtils.Mul(ref _linearMass, Cdot);
TSVector2 oldImpulse = _linearImpulse;
_linearImpulse += impulse;
FP maxImpulse = h * MaxForce;
if (_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
_linearImpulse.Normalize();
_linearImpulse *= maxImpulse;
}
impulse = _linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * MathUtils.Cross(_rA, impulse);
vB += mB * impulse;
wB += iB * MathUtils.Cross(_rB, impulse);
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
internal override bool SolvePositionConstraints(ref SolverData data)
{
return true;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Accord.Math;
using Accord.Statistics;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Data;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Indicators;
using QuantConnect.Orders.Fees;
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Algorithm.CSharp.Alphas
{
/// <summary>
/// Energy prices, especially Oil and Natural Gas, are in general fairly correlated,
/// meaning they typically move in the same direction as an overall trend.This Alpha
/// uses this idea and implements an Alpha Model that takes Natural Gas ETF price
/// movements as a leading indicator for Crude Oil ETF price movements.We take the
/// Natural Gas/Crude Oil ETF pair with the highest historical price correlation and
/// then create insights for Crude Oil depending on whether or not the Natural Gas ETF price change
/// is above/below a certain threshold that we set (arbitrarily).
///
/// This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
/// sourced so the community and client funds can see an example of an alpha.
///</summary>
public class GasAndCrudeOilEnergyCorrelationAlpha : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2018, 1, 1);
SetCash(100000);
// Set zero transaction fees
SetSecurityInitializer(security => security.FeeModel = new ConstantFeeModel(0));
Func<string, Symbol> ToSymbol = x => QuantConnect.Symbol.Create(x, SecurityType.Equity, Market.USA);
var naturalGas = new[] { "UNG", "BOIL", "FCG" }.Select(ToSymbol).ToArray();
var crudeOil = new[] { "USO", "UCO", "DBO" }.Select(ToSymbol).ToArray();
// Manually curated universe
UniverseSettings.Resolution = Resolution.Minute;
SetUniverseSelection(new ManualUniverseSelectionModel(naturalGas.Concat(crudeOil)));
// Use PairsAlphaModel to establish insights
SetAlpha(new PairsAlphaModel(naturalGas, crudeOil, 90, Resolution.Minute));
// Equally weigh securities in portfolio, based on insights
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
// Set Custom Execution Model
SetExecution(new CustomExecutionModel());
// Set Null Risk Management Model
SetRiskManagement(new NullRiskManagementModel());
}
/// <summary>
/// This Alpha model assumes that the ETF for natural gas is a good leading-indicator
/// of the price of the crude oil ETF.The model will take in arguments for a threshold
/// at which the model triggers an insight, the length of the look-back period for evaluating
/// rate-of-change of UNG prices, and the duration of the insight
/// </summary>
private class PairsAlphaModel : AlphaModel
{
private readonly Symbol[] _leading;
private readonly Symbol[] _following;
private readonly int _historyDays;
private readonly int _lookback;
private readonly decimal _differenceTrigger = 0.75m;
private readonly Resolution _resolution;
private readonly TimeSpan _predictionInterval;
private readonly Dictionary<Symbol, SymbolData> _symbolDataBySymbol;
private Tuple<SymbolData, SymbolData> _pair;
private DateTime _nextUpdate;
public PairsAlphaModel(
Symbol[] naturalGas,
Symbol[] crudeOil,
int historyDays = 90,
Resolution resolution = Resolution.Hour,
int lookback = 5,
decimal differenceTrigger = 0.75m)
{
_leading = naturalGas;
_following = crudeOil;
_historyDays = historyDays;
_resolution = resolution;
_lookback = lookback;
_differenceTrigger = differenceTrigger;
_symbolDataBySymbol = new Dictionary<Symbol, SymbolData>();
_predictionInterval = resolution.ToTimeSpan().Multiply(lookback);
}
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
{
if (_nextUpdate == DateTime.MinValue || algorithm.Time > _nextUpdate)
{
CorrelationPairsSelection();
_nextUpdate = algorithm.Time.AddDays(30);
}
var magnitude = (double)Math.Round(_pair.Item1.Return / 100, 6);
if (_pair.Item1.Return > _differenceTrigger)
{
yield return Insight.Price(_pair.Item2.Symbol, _predictionInterval, InsightDirection.Up, magnitude);
}
if (_pair.Item1.Return < -_differenceTrigger)
{
yield return Insight.Price(_pair.Item2.Symbol, _predictionInterval, InsightDirection.Down, magnitude);
}
}
public void CorrelationPairsSelection()
{
var maxCorrelation = -1.0;
var matrix = new double[_historyDays, _following.Length + 1];
// Get returns for each oil ETF
for (var j = 0; j < _following.Length; j++)
{
SymbolData symbolData2;
if (_symbolDataBySymbol.TryGetValue(_following[j], out symbolData2))
{
var dailyReturn2 = symbolData2.DailyReturnArray;
for (var i = 0; i < _historyDays; i++)
{
matrix[i, j + 1] = symbolData2.DailyReturnArray[i];
}
}
}
// Get returns for each natural gas ETF
for (var j = 0; j < _leading.Length; j++)
{
SymbolData symbolData1;
if (_symbolDataBySymbol.TryGetValue(_leading[j], out symbolData1))
{
for (var i = 0; i < _historyDays; i++)
{
matrix[i, 0] = symbolData1.DailyReturnArray[i];
}
var column = matrix.Correlation().GetColumn(0);
var correlation = column.RemoveAt(0).Max();
// Calculate the pair with highest historical correlation
if (correlation > maxCorrelation)
{
var maxIndex = column.IndexOf(correlation) - 1;
if (maxIndex < 0) continue;
var symbolData2 = _symbolDataBySymbol[_following[maxIndex]];
_pair = Tuple.Create(symbolData1, symbolData2);
maxCorrelation = correlation;
}
}
}
}
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
{
foreach (var removed in changes.RemovedSecurities)
{
if (_symbolDataBySymbol.ContainsKey(removed.Symbol))
{
_symbolDataBySymbol[removed.Symbol].RemoveConsolidators(algorithm);
_symbolDataBySymbol.Remove(removed.Symbol);
}
}
// Initialize data for added securities
var symbols = changes.AddedSecurities.Select(x => x.Symbol);
var dailyHistory = algorithm.History(symbols, _historyDays + 1, Resolution.Daily);
if (symbols.Count() > 0 && dailyHistory.Count() == 0)
{
algorithm.Debug($"{algorithm.Time} :: No daily data");
}
dailyHistory.PushThrough(bar =>
{
SymbolData symbolData;
if (!_symbolDataBySymbol.TryGetValue(bar.Symbol, out symbolData))
{
symbolData = new SymbolData(algorithm, bar.Symbol, _historyDays, _lookback, _resolution);
_symbolDataBySymbol.Add(bar.Symbol, symbolData);
}
// Update daily rate of change indicator
symbolData.UpdateDailyRateOfChange(bar);
});
algorithm.History(symbols, _lookback, _resolution).PushThrough(bar =>
{
// Update rate of change indicator with given resolution
if (_symbolDataBySymbol.ContainsKey(bar.Symbol))
{
_symbolDataBySymbol[bar.Symbol].UpdateRateOfChange(bar);
}
});
}
/// <summary>
/// Contains data specific to a symbol required by this model
/// </summary>
private class SymbolData
{
private readonly RateOfChangePercent _dailyReturn;
private readonly IDataConsolidator _dailyConsolidator;
private readonly RollingWindow<IndicatorDataPoint> _dailyReturnHistory;
private readonly IDataConsolidator _consolidator;
public Symbol Symbol { get; }
public RateOfChangePercent Return { get; }
public double[] DailyReturnArray => _dailyReturnHistory
.OrderBy(x => x.EndTime)
.Select(x => (double)x.Value).ToArray();
public SymbolData(QCAlgorithm algorithm, Symbol symbol, int dailyLookback, int lookback, Resolution resolution)
{
Symbol = symbol;
_dailyReturn = new RateOfChangePercent($"{symbol}.DailyROCP(1)", 1);
_dailyConsolidator = algorithm.ResolveConsolidator(symbol, Resolution.Daily);
_dailyReturnHistory = new RollingWindow<IndicatorDataPoint>(dailyLookback);
_dailyReturn.Updated += (s, e) => _dailyReturnHistory.Add(e);
algorithm.RegisterIndicator(symbol, _dailyReturn, _dailyConsolidator);
Return = new RateOfChangePercent($"{symbol}.ROCP({lookback})", lookback);
_consolidator = algorithm.ResolveConsolidator(symbol, resolution);
algorithm.RegisterIndicator(symbol, Return, _consolidator);
}
public void RemoveConsolidators(QCAlgorithm algorithm)
{
algorithm.SubscriptionManager.RemoveConsolidator(Symbol, _consolidator);
algorithm.SubscriptionManager.RemoveConsolidator(Symbol, _dailyConsolidator);
}
public void UpdateRateOfChange(BaseData data)
{
Return.Update(data.EndTime, data.Value);
}
internal void UpdateDailyRateOfChange(BaseData data)
{
_dailyReturn.Update(data.EndTime, data.Value);
}
public override string ToString() => Return.ToDetailedString();
}
}
/// <summary>
/// Provides an implementation of IExecutionModel that immediately submits market orders to achieve the desired portfolio targets
/// </summary>
private class CustomExecutionModel : ExecutionModel
{
private readonly PortfolioTargetCollection _targetsCollection = new PortfolioTargetCollection();
private Symbol _previousSymbol;
/// <summary>
/// Immediately submits orders for the specified portfolio targets.
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="targets">The portfolio targets to be ordered</param>
public override void Execute(QCAlgorithm algorithm, IPortfolioTarget[] targets)
{
_targetsCollection.AddRange(targets);
foreach (var target in _targetsCollection.OrderByMarginImpact(algorithm))
{
var openQuantity = algorithm.Transactions.GetOpenOrders(target.Symbol)
.Sum(x => x.Quantity);
var existing = algorithm.Securities[target.Symbol].Holdings.Quantity + openQuantity;
var quantity = target.Quantity - existing;
// Liquidate positions in Crude Oil ETF that is no longer part of the highest-correlation pair
if (_previousSymbol != null && target.Symbol != _previousSymbol)
{
algorithm.Liquidate(_previousSymbol);
}
if (quantity != 0)
{
algorithm.MarketOrder(target.Symbol, quantity);
_previousSymbol = target.Symbol;
}
}
_targetsCollection.ClearFulfilled(algorithm);
}
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
namespace DotSpatial.Symbology
{
/// <summary>
/// Categorizable legend item.
/// </summary>
public abstract class Scheme : LegendItem
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Scheme"/> class.
/// </summary>
protected Scheme()
{
LegendSymbolMode = SymbolMode.None;
LegendType = LegendType.Scheme;
Statistics = new Statistics();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the editor settings that control how this scheme operates.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public EditorSettings EditorSettings { get; set; }
/// <summary>
/// Gets or sets the statistics. This is cached until a GetValues call is made, at which time the statistics will
/// be re-calculated from the values.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Statistics Statistics { get; protected set; }
/// <summary>
/// Gets or sets the current list of values calculated in the case of numeric breaks.
/// This includes only members that are not excluded by the exclude expression,
/// and have a valid numeric value.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public List<double> Values { get; protected set; }
/// <summary>
/// Gets or sets the list of breaks for this scheme.
/// </summary>
protected List<Break> Breaks { get; set; }
#endregion
#region Methods
/// <summary>
/// Adds a new scheme, assuming that the new scheme is the correct type.
/// </summary>
/// <param name="category">The category to add</param>
public abstract void AddCategory(ICategory category);
/// <summary>
/// Applies the snapping rule directly to the categories, based on the most recently
/// collected set of values, and the current VectorEditorSettings.
/// </summary>
/// <param name="category">Category the snapping is applied to.</param>
public void ApplySnapping(ICategory category)
{
category.ApplySnapping(EditorSettings.IntervalSnapMethod, EditorSettings.IntervalRoundingDigits, Values);
}
/// <summary>
/// Clears the categories.
/// </summary>
public abstract void ClearCategories();
/// <summary>
/// Creates the category using a random fill color
/// </summary>
/// <param name="fillColor">The base color to use for creating the category</param>
/// <param name="size">For points this is the larger dimension, for lines this is the largest width</param>
/// <returns>A new IFeatureCategory that matches the type of this scheme</returns>
public virtual ICategory CreateNewCategory(Color fillColor, double size)
{
// This method should be overridden in child classes
return null;
}
/// <summary>
/// Uses the settings on this scheme to create a random category.
/// </summary>
/// <returns>A new ICategory</returns>
public abstract ICategory CreateRandomCategory();
/// <summary>
/// Reduces the index value of the specified category by 1 by
/// exchaning it with the category before it. If there is no
/// category before it, then this does nothing.
/// </summary>
/// <param name="category">The category to decrease the index of</param>
/// <returns>True, if run successfully.</returns>
public abstract bool DecreaseCategoryIndex(ICategory category);
/// <summary>
/// Draws the regular symbolizer for the specified cateogry to the specified graphics
/// surface in the specified bounding rectangle.
/// </summary>
/// <param name="index">The integer index of the feature to draw.</param>
/// <param name="g">The Graphics object to draw to</param>
/// <param name="bounds">The rectangular bounds to draw in</param>
public abstract void DrawCategory(int index, Graphics g, Rectangle bounds);
/// <summary>
/// Re-orders the specified member by attempting to exchange it with the next higher
/// index category. If there is no higher index, this does nothing.
/// </summary>
/// <param name="category">The category to increase the index of</param>
/// <returns>True, if run successfully.</returns>
public abstract bool IncreaseCategoryIndex(ICategory category);
/// <summary>
/// Inserts the category at the specified index
/// </summary>
/// <param name="index">The integer index where the category should be inserted</param>
/// <param name="category">The category to insert</param>
public abstract void InsertCategory(int index, ICategory category);
/// <summary>
/// Removes the specified category
/// </summary>
/// <param name="category">The category to insert</param>
public abstract void RemoveCategory(ICategory category);
/// <summary>
/// Resumes the category events
/// </summary>
public abstract void ResumeEvents();
/// <summary>
/// Suspends the category events
/// </summary>
public abstract void SuspendEvents();
/// <summary>
/// Sets the names for the break categories.
/// </summary>
/// <param name="breaks">Breaks to use for naming.</param>
protected static void SetBreakNames(IList<Break> breaks)
{
for (var i = 0; i < breaks.Count; i++)
{
var brk = breaks[i];
if (breaks.Count == 1)
{
brk.Name = "All Values";
}
else if (i == 0)
{
brk.Name = "<= " + brk.Maximum;
}
else if (i == breaks.Count - 1)
{
brk.Name = "> " + breaks[i - 1].Maximum;
}
else
{
brk.Name = breaks[i - 1].Maximum + " - " + brk.Maximum;
}
}
}
/// <summary>
/// Applies the snapping type to the given breaks
/// </summary>
protected void ApplyBreakSnapping()
{
if (Values == null || Values.Count == 0) return;
switch (EditorSettings.IntervalSnapMethod)
{
case IntervalSnapMethod.None: break;
case IntervalSnapMethod.SignificantFigures:
foreach (var item in Breaks)
{
if (item.Maximum == null) continue;
var val = (double)item.Maximum;
item.Maximum = Utils.SigFig(val, EditorSettings.IntervalRoundingDigits);
}
break;
case IntervalSnapMethod.Rounding:
foreach (var item in Breaks)
{
if (item.Maximum == null) continue;
item.Maximum = Math.Round((double)item.Maximum, EditorSettings.IntervalRoundingDigits);
}
break;
case IntervalSnapMethod.DataValue:
foreach (var item in Breaks)
{
if (item.Maximum == null) continue;
item.Maximum = Utils.GetNearestValue((double)item.Maximum, Values);
}
break;
}
}
/// <summary>
/// Generates the break categories for this scheme
/// </summary>
protected void CreateBreakCategories()
{
var count = EditorSettings.NumBreaks;
switch (EditorSettings.IntervalMethod)
{
case IntervalMethod.EqualFrequency:
Breaks = GetQuantileBreaks(count);
break;
case IntervalMethod.NaturalBreaks:
Breaks = GetNaturalBreaks(count);
break;
default:
Breaks = GetEqualBreaks(count);
break;
}
ApplyBreakSnapping();
SetBreakNames(Breaks);
var colorRamp = GetColorSet(count);
var sizeRamp = GetSizeSet(count);
ClearCategories();
var colorIndex = 0;
Break prevBreak = null;
foreach (var brk in Breaks)
{
// get the color for the category
var randomColor = colorRamp[colorIndex];
var randomSize = sizeRamp[colorIndex];
var cat = CreateNewCategory(randomColor, randomSize);
if (cat != null)
{
// cat.SelectionSymbolizer = _selectionSymbolizer.Copy();
cat.LegendText = brk.Name;
if (prevBreak != null) cat.Minimum = prevBreak.Maximum;
cat.Maximum = brk.Maximum;
cat.Range.MaxIsInclusive = true;
cat.ApplyMinMax(EditorSettings);
AddCategory(cat);
}
prevBreak = brk;
colorIndex++;
}
}
/// <summary>
/// Creates a random color, but accepts a given random class instead of creating a new one.
/// </summary>
/// <param name="rnd">The random generator.</param>
/// <returns>The created random color.</returns>
protected Color CreateRandomColor(Random rnd)
{
var startColor = EditorSettings.StartColor;
var endColor = EditorSettings.EndColor;
if (EditorSettings.HueSatLight)
{
double hLow = startColor.GetHue();
var dH = endColor.GetHue() - hLow;
double sLow = startColor.GetSaturation();
var ds = endColor.GetSaturation() - sLow;
double lLow = startColor.GetBrightness();
var dl = endColor.GetBrightness() - lLow;
var aLow = startColor.A / 255.0;
var da = (endColor.A - aLow) / 255.0;
return SymbologyGlobal.ColorFromHsl((rnd.NextDouble() * dH) + hLow, (rnd.NextDouble() * ds) + sLow, (rnd.NextDouble() * dl) + lLow).ToTransparent((float)((rnd.NextDouble() * da) + aLow));
}
int rLow = Math.Min(startColor.R, endColor.R);
int rHigh = Math.Max(startColor.R, endColor.R);
int gLow = Math.Min(startColor.G, endColor.G);
int gHigh = Math.Max(startColor.G, endColor.G);
int bLow = Math.Min(startColor.B, endColor.B);
int bHigh = Math.Max(startColor.B, endColor.B);
int iaLow = Math.Min(startColor.A, endColor.A);
int aHigh = Math.Max(startColor.A, endColor.A);
return Color.FromArgb(rnd.Next(iaLow, aHigh), rnd.Next(rLow, rHigh), rnd.Next(gLow, gHigh), rnd.Next(bLow, bHigh));
}
/// <summary>
/// Creates a list of generated colors according to the convention specified in the EditorSettings.
/// </summary>
/// <param name="count">The integer count of the number of colors to create.</param>
/// <returns>The list of colors created.</returns>
protected List<Color> GetColorSet(int count)
{
List<Color> colorRamp;
if (EditorSettings.UseColorRange)
{
if (!EditorSettings.RampColors)
{
colorRamp = CreateRandomColors(count);
}
else if (!EditorSettings.HueSatLight)
{
colorRamp = CreateRampColors(count, EditorSettings.StartColor, EditorSettings.EndColor);
}
else
{
var cStart = EditorSettings.StartColor;
var cEnd = EditorSettings.EndColor;
colorRamp = CreateRampColors(count, cStart.GetSaturation(), cStart.GetBrightness(), (int)cStart.GetHue(), cEnd.GetSaturation(), cEnd.GetBrightness(), (int)cEnd.GetHue(), EditorSettings.HueShift, cStart.A, cEnd.A);
}
}
else
{
colorRamp = GetDefaultColors(count);
}
return colorRamp;
}
/// <summary>
/// Creates the colors in the case where the color range controls are not being used.
/// This can be overriddend for handling special cases like point and line symbolizers
/// that should be using the template colors.
/// </summary>
/// <param name="count">The integer count to use</param>
/// <returns>The default colors.</returns>
protected virtual List<Color> GetDefaultColors(int count)
{
return EditorSettings.RampColors ? CreateUnboundedRampColors(count) : CreateUnboundedRandomColors(count);
}
/// <summary>
/// Uses the currently calculated Values in order to calculate a list of breaks
/// that have equal separations.
/// </summary>
/// <param name="count">Number of breaks that should be added.</param>
/// <returns>Calculated list of breaks.</returns>
protected List<Break> GetEqualBreaks(int count)
{
var result = new List<Break>();
var min = Values[0];
var dx = (Values[Values.Count - 1] - min) / count;
for (var i = 0; i < count; i++)
{
var brk = new Break();
// max
if (i == count - 1)
{
brk.Maximum = null;
}
else
{
brk.Maximum = min + ((i + 1) * dx);
}
result.Add(brk);
}
return result;
}
/// <summary>
/// Generates natural breaks.
/// </summary>
/// <param name="count">Count of breaks.</param>
/// <returns>List with breaks.</returns>
protected List<Break> GetNaturalBreaks(int count)
{
var breaks = new JenksBreaksCalcuation(Values, count);
breaks.Optimize();
var results = breaks.GetResults();
var output = new List<Break>(count);
output.AddRange(
results.Select(
result => new Break
{
Maximum = Values[result]
}));
// Set latest Maximum to null
output.Last().Maximum = null;
return output;
}
/// <summary>
/// Attempts to create the specified number of breaks with equal numbers of members in each.
/// </summary>
/// <param name="count">The integer count.</param>
/// <returns>A list of breaks.</returns>
protected List<Break> GetQuantileBreaks(int count)
{
var result = new List<Break>();
var binSize = (int)Math.Ceiling(Values.Count / (double)count);
for (var iBreak = 1; iBreak <= count; iBreak++)
{
if (binSize * iBreak < Values.Count)
{
var brk = new Break { Maximum = Values[binSize * iBreak] };
result.Add(brk);
}
else
{
// if num breaks is larger than number of members, this can happen
var brk = new Break { Maximum = null };
result.Add(brk);
break;
}
}
return result;
}
/// <summary>
/// Gets the default size set.
/// </summary>
/// <param name="count">Number of sizes needed.</param>
/// <returns>The default size set.</returns>
protected virtual List<double> GetSizeSet(int count)
{
var result = new List<double>();
for (var i = 0; i < count; i++)
{
result.Add(20);
}
return result;
}
private static List<Color> CreateRampColors(int numColors, Color startColor, Color endColor)
{
var result = new List<Color>(numColors);
var dR = (endColor.R - (double)startColor.R) / numColors;
var dG = (endColor.G - (double)startColor.G) / numColors;
var dB = (endColor.B - (double)startColor.B) / numColors;
var dA = (endColor.A - (double)startColor.A) / numColors;
for (var i = 0; i < numColors; i++)
{
result.Add(Color.FromArgb((int)(startColor.A + (dA * i)), (int)(startColor.R + (dR * i)), (int)(startColor.G + (dG * i)), (int)(startColor.B + (dB * i))));
}
return result;
}
private static List<Color> CreateRampColors(int numColors, float minSat, float minLight, int minHue, float maxSat, float maxLight, int maxHue, int hueShift, int minAlpha, int maxAlpha)
{
var result = new List<Color>(numColors);
var ds = (maxSat - (double)minSat) / numColors;
var dh = (maxHue - (double)minHue) / numColors;
var dl = (maxLight - (double)minLight) / numColors;
var dA = (maxAlpha - (double)minAlpha) / numColors;
for (var i = 0; i < numColors; i++)
{
var h = (minHue + (dh * i)) + (hueShift % 360);
var s = minSat + (ds * i);
var l = minLight + (dl * i);
var a = (float)(minAlpha + (dA * i)) / 255f;
result.Add(SymbologyGlobal.ColorFromHsl(h, s, l).ToTransparent(a));
}
return result;
}
/// <summary>
/// The default behavior for creating ramp colors is to create colors in the mid-range for
/// both lightness and saturation, but to have the full range of hue
/// </summary>
/// <param name="numColors">Number of colors needed.</param>
/// <returns>The list with the created colors.</returns>
private static List<Color> CreateUnboundedRampColors(int numColors)
{
return CreateRampColors(numColors, .25f, .25f, 0, .75f, .75f, 360, 0, 255, 255);
}
private static List<Color> CreateUnboundedRandomColors(int numColors)
{
var rnd = new Random(DateTime.Now.Millisecond);
var result = new List<Color>(numColors);
for (var i = 0; i < numColors; i++)
{
result.Add(rnd.NextColor());
}
return result;
}
private List<Color> CreateRandomColors(int numColors)
{
var result = new List<Color>(numColors);
var rnd = new Random(DateTime.Now.Millisecond);
for (var i = 0; i < numColors; i++)
{
result.Add(CreateRandomColor(rnd));
}
return result;
}
#endregion
#region Classes
/// <summary>
/// Breaks for value ranges
/// </summary>
protected class Break
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Break"/> class.
/// </summary>
public Break()
{
Name = string.Empty;
Maximum = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Break"/> class.
/// </summary>
/// <param name="name">The string name for the break</param>
public Break(string name)
{
Name = name;
Maximum = 0;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a double value for the maximum value for the break.
/// </summary>
public double? Maximum { get; set; }
/// <summary>
/// Gets or sets the string name.
/// </summary>
public string Name { get; set; }
#endregion
}
#endregion
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Tank.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace SimpleAnimation
{
/// <summary>
/// Helper class for drawing a tank model with animated wheels and turret.
/// </summary>
public class Tank
{
#region Fields
// The XNA framework Model object that we are going to display.
Model tankModel;
// Shortcut references to the bones that we are going to animate.
// We could just look these up inside the Draw method, but it is more
// efficient to do the lookups while loading and cache the results.
ModelBone leftBackWheelBone;
ModelBone rightBackWheelBone;
ModelBone leftFrontWheelBone;
ModelBone rightFrontWheelBone;
ModelBone leftSteerBone;
ModelBone rightSteerBone;
ModelBone turretBone;
ModelBone cannonBone;
ModelBone hatchBone;
// Store the original transform matrix for each animating bone.
Matrix leftBackWheelTransform;
Matrix rightBackWheelTransform;
Matrix leftFrontWheelTransform;
Matrix rightFrontWheelTransform;
Matrix leftSteerTransform;
Matrix rightSteerTransform;
Matrix turretTransform;
Matrix cannonTransform;
Matrix hatchTransform;
// Array holding all the bone transform matrices for the entire model.
// We could just allocate this locally inside the Draw method, but it
// is more efficient to reuse a single array, as this avoids creating
// unnecessary garbage.
Matrix[] boneTransforms;
// Current animation positions.
float wheelRotationValue;
float steerRotationValue;
float turretRotationValue;
float cannonRotationValue;
float hatchRotationValue;
#endregion
#region Properties
/// <summary>
/// Gets or sets the wheel rotation amount.
/// </summary>
public float WheelRotation
{
get { return wheelRotationValue; }
set { wheelRotationValue = value; }
}
/// <summary>
/// Gets or sets the steering rotation amount.
/// </summary>
public float SteerRotation
{
get { return steerRotationValue; }
set { steerRotationValue = value; }
}
/// <summary>
/// Gets or sets the turret rotation amount.
/// </summary>
public float TurretRotation
{
get { return turretRotationValue; }
set { turretRotationValue = value; }
}
/// <summary>
/// Gets or sets the cannon rotation amount.
/// </summary>
public float CannonRotation
{
get { return cannonRotationValue; }
set { cannonRotationValue = value; }
}
/// <summary>
/// Gets or sets the entry hatch rotation amount.
/// </summary>
public float HatchRotation
{
get { return hatchRotationValue; }
set { hatchRotationValue = value; }
}
#endregion
/// <summary>
/// Loads the tank model.
/// </summary>
public void Load(ContentManager content)
{
// Load the tank model from the ContentManager.
tankModel = content.Load<Model>("tank");
// Look up shortcut references to the bones we are going to animate.
leftBackWheelBone = tankModel.Bones["l_back_wheel_geo"];
rightBackWheelBone = tankModel.Bones["r_back_wheel_geo"];
leftFrontWheelBone = tankModel.Bones["l_front_wheel_geo"];
rightFrontWheelBone = tankModel.Bones["r_front_wheel_geo"];
leftSteerBone = tankModel.Bones["l_steer_geo"];
rightSteerBone = tankModel.Bones["r_steer_geo"];
turretBone = tankModel.Bones["turret_geo"];
cannonBone = tankModel.Bones["canon_geo"];
hatchBone = tankModel.Bones["hatch_geo"];
// Store the original transform matrix for each animating bone.
leftBackWheelTransform = leftBackWheelBone.Transform;
rightBackWheelTransform = rightBackWheelBone.Transform;
leftFrontWheelTransform = leftFrontWheelBone.Transform;
rightFrontWheelTransform = rightFrontWheelBone.Transform;
leftSteerTransform = leftSteerBone.Transform;
rightSteerTransform = rightSteerBone.Transform;
turretTransform = turretBone.Transform;
cannonTransform = cannonBone.Transform;
hatchTransform = hatchBone.Transform;
// Allocate the transform matrix array.
boneTransforms = new Matrix[tankModel.Bones.Count];
}
/// <summary>
/// Draws the tank model, using the current animation settings.
/// </summary>
public void Draw(Matrix world, Matrix view, Matrix projection)
{
// Set the world matrix as the root transform of the model.
tankModel.Root.Transform = world;
// Calculate matrices based on the current animation position.
Matrix wheelRotation = Matrix.CreateRotationX(wheelRotationValue);
Matrix steerRotation = Matrix.CreateRotationY(steerRotationValue);
Matrix turretRotation = Matrix.CreateRotationY(turretRotationValue);
Matrix cannonRotation = Matrix.CreateRotationX(cannonRotationValue);
Matrix hatchRotation = Matrix.CreateRotationX(hatchRotationValue);
// Apply matrices to the relevant bones.
leftBackWheelBone.Transform = wheelRotation * leftBackWheelTransform;
rightBackWheelBone.Transform = wheelRotation * rightBackWheelTransform;
leftFrontWheelBone.Transform = wheelRotation * leftFrontWheelTransform;
rightFrontWheelBone.Transform = wheelRotation * rightFrontWheelTransform;
leftSteerBone.Transform = steerRotation * leftSteerTransform;
rightSteerBone.Transform = steerRotation * rightSteerTransform;
turretBone.Transform = turretRotation * turretTransform;
cannonBone.Transform = cannonRotation * cannonTransform;
hatchBone.Transform = hatchRotation * hatchTransform;
// Look up combined bone matrices for the entire model.
tankModel.CopyAbsoluteBoneTransformsTo(boneTransforms);
// Draw the model.
foreach (ModelMesh mesh in tankModel.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = boneTransforms[mesh.ParentBone.Index];
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
}
mesh.Draw();
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Diagnostics.Contracts;
using System;
using System.Text;
using System.Collections.Generic;
namespace System.IO
{
public class File
{
public static void Move(string sourceFileName, string destFileName)
{
Contract.Requires(sourceFileName != null);
Contract.Requires(destFileName != null);
Contract.Requires(sourceFileName.Length != 0);
Contract.Requires(destFileName.Length != 0);
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"The destination file already exists. -or- sourceFileName was not found.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path in sourceFileName or destFileName is invalid, (for example, it is on an unmapped drive).");
}
public static FileStream OpenWrite(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Ensures(Contract.Result<FileStream>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
return default(FileStream);
}
public static FileStream OpenRead(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Ensures(Contract.Result<FileStream>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
return default(FileStream);
}
public static void SetAttributes(string path, FileAttributes fileAttributes)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
}
#if !SILVERLIGHT
public static FileAttributes GetAttributes(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"This file is being used by another process.");
return default(FileAttributes);
}
#endif
#if !SILVERLIGHT
public static DateTime GetLastWriteTimeUtc(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(DateTime);
}
#endif
public static DateTime GetLastWriteTime(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(DateTime);
}
#if !SILVERLIGHT
public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
}
public static void SetLastWriteTime(string path, DateTime lastWriteTime)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
}
public static DateTime GetLastAccessTimeUtc(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
return default(DateTime);
}
#endif
public static DateTime GetLastAccessTime(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
return default(DateTime);
}
#if !SILVERLIGHT
public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
}
public static void SetLastAccessTime(string path, DateTime lastAccessTime)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
}
public static DateTime GetCreationTimeUtc(string path)
{
return default(DateTime);
}
#endif
public static DateTime GetCreationTime(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(DateTime);
}
#if !SILVERLIGHT
public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurred while performing the operation. ");
}
public static void SetCreationTime(string path, DateTime creationTime)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurred while performing the operation. ");
}
#endif
public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurred while performing the operation. ");
Contract.Ensures(Contract.Result<FileStream>() != null);
return default(FileStream);
}
public static FileStream Open(string path, FileMode mode, FileAccess access)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurred while performing the operation. ");
Contract.Ensures(Contract.Result<FileStream>() != null);
return default(FileStream);
}
public static FileStream Open(string path, FileMode mode)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurred while performing the operation. ");
Contract.Ensures(Contract.Result<FileStream>() != null);
return default(FileStream);
}
[Pure]
public static bool Exists(string path)
{
Contract.Ensures(!Contract.Result<bool>() || path != null);
Contract.Ensures(!Contract.Result<bool>() || path.Length > 0); // trivial, but useful for clients
return default(bool);
}
public static void Delete(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"The specified file is in use.");
}
public static FileStream Create(string path, int bufferSize)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Ensures(Contract.Result<FileStream>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurred while creating the file.");
return default(FileStream);
}
public static FileStream Create(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Ensures(Contract.Result<FileStream>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The path specified in sourceFileName or destFileName is invalid (for example, it is on an unmapped drive).
");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurred while creating the file.");
return default(FileStream);
}
public static void Copy(string sourceFileName, string destFileName, bool overwrite)
{
Contract.Requires(!String.IsNullOrEmpty(sourceFileName));
Contract.Requires(!String.IsNullOrEmpty(destFileName));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"destFileName exists and overwrite is false. -or- An I/O error has occurred.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
}
public static void Copy(string sourceFileName, string destFileName)
{
Contract.Requires(!String.IsNullOrEmpty(sourceFileName));
Contract.Requires(!String.IsNullOrEmpty(destFileName));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"destFileName exists and overwrite is false. -or- An I/O error has occurred.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
}
public static StreamWriter AppendText(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Ensures(Contract.Result<StreamWriter>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
return default(StreamWriter);
}
public static StreamWriter CreateText(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Ensures(Contract.Result<StreamWriter>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
return default(StreamWriter);
}
public static StreamReader OpenText(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Ensures(Contract.Result<StreamReader>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
return default(StreamReader);
}
#if !SILVERLIGHT
public static byte[] ReadAllBytes(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Requires(path.Length > 0);
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error has occurred.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
return default(byte[]);
}
public static string ReadAllText(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Requires(path.Length > 0);
Contract.Ensures(Contract.Result<string>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error has occurred.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
return default(string);
}
public static string ReadAllText(string path, Encoding encoding)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Requires(path.Length > 0);
Contract.Ensures(Contract.Result<string>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error has occurred.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
return default(string);
}
#endif
#if !SILVERLIGHT
public static string[] ReadAllLines(string fileName) {
Contract.Requires(!String.IsNullOrEmpty(fileName));
Contract.Ensures(Contract.Result<string[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<string[]>(), line => line != null));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error has occurred.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
return default(string[]);
}
public static string[] ReadAllLines(string fileName, System.Text.Encoding encoding) {
Contract.Requires(!String.IsNullOrEmpty(fileName));
Contract.Ensures(Contract.Result<string[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<string[]>(), line => line != null));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid, (for example, it is on an unmapped drive).");
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error has occurred.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The file specified in path was not found.");
return default(string[]);
}
#elif SILVERLIGHT_4_0 || SILVERLIGHT_5_0 || NETFRAMEWORK_4_0
public static IEnumerable<string> ReadLines(string fileName) {
Contract.Requires(fileName != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), line => line != null));
return default(string[]);
}
public static IEnumerable<string> ReadLines(string fileName, System.Text.Encoding encoding) {
Contract.Requires(fileName != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), line => line != null));
return default(string[]);
}
#endif
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.Animation.StringKeyFrameCollection.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Animation
{
public partial class StringKeyFrameCollection : System.Windows.Freezable, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable
{
#region Methods and constructors
public int Add(StringKeyFrame keyFrame)
{
return default(int);
}
public void Clear()
{
}
public System.Windows.Media.Animation.StringKeyFrameCollection Clone()
{
return default(System.Windows.Media.Animation.StringKeyFrameCollection);
}
protected override void CloneCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void CloneCurrentValueCore(System.Windows.Freezable sourceFreezable)
{
}
public bool Contains(StringKeyFrame keyFrame)
{
return default(bool);
}
public void CopyTo(StringKeyFrame[] array, int index)
{
}
protected override System.Windows.Freezable CreateInstanceCore()
{
return default(System.Windows.Freezable);
}
protected override bool FreezeCore(bool isChecking)
{
return default(bool);
}
protected override void GetAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
public System.Collections.IEnumerator GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
public int IndexOf(StringKeyFrame keyFrame)
{
return default(int);
}
public void Insert(int index, StringKeyFrame keyFrame)
{
}
public void Remove(StringKeyFrame keyFrame)
{
}
public void RemoveAt(int index)
{
}
public StringKeyFrameCollection()
{
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
}
int System.Collections.IList.Add(Object keyFrame)
{
return default(int);
}
bool System.Collections.IList.Contains(Object keyFrame)
{
return default(bool);
}
int System.Collections.IList.IndexOf(Object keyFrame)
{
return default(int);
}
void System.Collections.IList.Insert(int index, Object keyFrame)
{
}
void System.Collections.IList.Remove(Object keyFrame)
{
}
#endregion
#region Properties and indexers
public int Count
{
get
{
return default(int);
}
}
public static System.Windows.Media.Animation.StringKeyFrameCollection Empty
{
get
{
return default(System.Windows.Media.Animation.StringKeyFrameCollection);
}
}
public bool IsFixedSize
{
get
{
return default(bool);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public bool IsSynchronized
{
get
{
return default(bool);
}
}
public StringKeyFrame this [int index]
{
get
{
return default(StringKeyFrame);
}
set
{
}
}
public Object SyncRoot
{
get
{
return default(Object);
}
}
Object System.Collections.IList.this [int index]
{
get
{
return default(Object);
}
set
{
}
}
#endregion
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET
// Copyright (C) Rick Brewster, Chris Crosetto, Dennis Dietrich, Tom Jackson,
// Michael Kelsey, Brandon Ortiz, Craig Taylor, Chris Trevino,
// and Luke Walker
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved.
// See src/setup/License.rtf for complete licensing and attribution information.
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Copied for Paint.NET PCX Plugin
// Copyright (C) Joshua Bell
/////////////////////////////////////////////////////////////////////////////////
// Based on: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/colorquant.asp
//Bizhawk says: adapted from https://github.com/inexorabletash/PcxFileType/blob/master/Quantize
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace BizHawk.Client.EmuHawk
{
/// <summary>
/// Summary description for Class1.
/// </summary>
internal unsafe abstract class Quantizer
{
/// <summary>
/// Flag used to indicate whether a single pass or two passes are needed for quantization.
/// </summary>
private bool _singlePass;
protected bool highquality;
public bool HighQuality
{
get
{
return highquality;
}
set
{
highquality = value;
}
}
protected int ditherLevel;
public int DitherLevel
{
get
{
return this.ditherLevel;
}
set
{
this.ditherLevel = value;
}
}
/// <summary>
/// Construct the quantizer
/// </summary>
/// <param name="singlePass">If true, the quantization only needs to loop through the source pixels once</param>
/// <remarks>
/// If you construct this class with a true value for singlePass, then the code will, when quantizing your image,
/// only call the 'QuantizeImage' function. If two passes are required, the code will call 'InitialQuantizeImage'
/// and then 'QuantizeImage'.
/// </remarks>
public Quantizer(bool singlePass)
{
_singlePass = singlePass;
}
/// <summary>
/// Quantize an image and return the resulting output bitmap
/// </summary>
/// <param name="source">The image to quantize</param>
/// <returns>A quantized version of the image</returns>
public Bitmap Quantize(Image source)
{
// Get the size of the source image
int height = source.Height;
int width = source.Width;
// And construct a rectangle from these dimensions
Rectangle bounds = new Rectangle(0, 0, width, height);
// First off take a 32bpp copy of the image
Bitmap copy;
if (source is Bitmap && source.PixelFormat == PixelFormat.Format32bppArgb)
{
copy = (Bitmap)source;
}
else
{
copy = new Bitmap(width, height, PixelFormat.Format32bppArgb);
// Now lock the bitmap into memory
using (Graphics g = Graphics.FromImage(copy))
{
g.PageUnit = GraphicsUnit.Pixel;
// Draw the source image onto the copy bitmap,
// which will effect a widening as appropriate.
g.DrawImage(source, 0, 0, bounds.Width, bounds.Height);
}
}
// And construct an 8bpp version
Bitmap output = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
// Define a pointer to the bitmap data
BitmapData sourceData = null;
try
{
// Get the source image bits and lock into memory
sourceData = copy.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Call the FirstPass function if not a single pass algorithm.
// For something like an octree quantizer, this will run through
// all image pixels, build a data structure, and create a palette.
if (!_singlePass)
{
FirstPass(sourceData, width, height);
}
// Then set the color palette on the output bitmap. I'm passing in the current palette
// as there's no way to construct a new, empty palette.
output.Palette = this.GetPalette(output.Palette);
// Then call the second pass which actually does the conversion
SecondPass(sourceData, output, width, height, bounds);
}
finally
{
// Ensure that the bits are unlocked
copy.UnlockBits(sourceData);
}
if (copy != source)
{
copy.Dispose();
}
// Last but not least, return the output bitmap
return output;
}
/// <summary>
/// Execute the first pass through the pixels in the image
/// </summary>
/// <param name="sourceData">The source data</param>
/// <param name="width">The width in pixels of the image</param>
/// <param name="height">The height in pixels of the image</param>
protected virtual void FirstPass(BitmapData sourceData, int width, int height)
{
// Define the source data pointers. The source row is a byte to
// keep addition of the stride value easier (as this is in bytes)
byte* pSourceRow = (byte*)sourceData.Scan0.ToPointer();
int* pSourcePixel;
// Loop through each row
for (int row = 0; row < height; row++)
{
// Set the source pixel to the first pixel in this row
pSourcePixel = (Int32*)pSourceRow;
// And loop through each column
for (int col = 0; col < width; col++, pSourcePixel++)
{
InitialQuantizePixel(*pSourcePixel);
}
// Add the stride to the source row
pSourceRow += sourceData.Stride;
}
}
int ClampToByte(int val)
{
if (val < 0) return 0;
else if (val > 255) return 255;
else return val;
}
/// <summary>
/// Execute a second pass through the bitmap
/// </summary>
/// <param name="sourceData">The source bitmap, locked into memory</param>
/// <param name="output">The output bitmap</param>
/// <param name="width">The width in pixels of the image</param>
/// <param name="height">The height in pixels of the image</param>
/// <param name="bounds">The bounding rectangle</param>
protected virtual void SecondPass(BitmapData sourceData, Bitmap output, int width, int height, Rectangle bounds)
{
BitmapData outputData = null;
Color[] pallete = output.Palette.Entries;
int weight = ditherLevel;
try
{
// Lock the output bitmap into memory
outputData = output.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
// Define the source data pointers. The source row is a byte to
// keep addition of the stride value easier (as this is in bytes)
byte* pSourceRow = (byte *)sourceData.Scan0.ToPointer();
Int32* pSourcePixel = (Int32 *)pSourceRow;
// Now define the destination data pointers
byte* pDestinationRow = (byte *)outputData.Scan0.ToPointer();
byte* pDestinationPixel = pDestinationRow;
int[] errorThisRowR = new int[width + 1];
int[] errorThisRowG = new int[width + 1];
int[] errorThisRowB = new int[width + 1];
for (int row = 0; row < height; row++)
{
int[] errorNextRowR = new int[width + 1];
int[] errorNextRowG = new int[width + 1];
int[] errorNextRowB = new int[width + 1];
int ptrInc;
if ((row & 1) == 0)
{
pSourcePixel = (Int32*)pSourceRow;
pDestinationPixel = pDestinationRow;
ptrInc = +1;
}
else
{
pSourcePixel = (Int32*)pSourceRow + width - 1;
pDestinationPixel = pDestinationRow + width - 1;
ptrInc = -1;
}
// Loop through each pixel on this scan line
for (int col = 0; col < width; ++col)
{
// Quantize the pixel
int srcPixel = *pSourcePixel;
int srcR = srcPixel & 0xFF; //not
int srcG = (srcPixel>>8) & 0xFF; //a
int srcB = (srcPixel>>16) & 0xFF; //mistake
int srcA = (srcPixel >> 24) & 0xFF;
int targetB = ClampToByte(srcB - ((errorThisRowB[col] * weight) / 8));
int targetG = ClampToByte(srcG - ((errorThisRowG[col] * weight) / 8));
int targetR = ClampToByte(srcR - ((errorThisRowR[col] * weight) / 8));
int targetA = srcA;
int target = (targetA<<24)|(targetB<<16)|(targetG<<8)|targetR;
byte pixelValue = QuantizePixel(target);
*pDestinationPixel = pixelValue;
int actual = pallete[pixelValue].ToArgb();
int actualR = actual & 0xFF;
int actualG = (actual >> 8) & 0xFF;
int actualB = (actual >> 16) & 0xFF;
int errorR = actualR - targetR;
int errorG = actualG - targetG;
int errorB = actualB - targetB;
// Floyd-Steinberg Error Diffusion:
// a) 7/16 error goes to x+1
// b) 5/16 error goes to y+1
// c) 3/16 error goes to x-1,y+1
// d) 1/16 error goes to x+1,y+1
const int a = 7;
const int b = 5;
const int c = 3;
int errorRa = (errorR * a) / 16;
int errorRb = (errorR * b) / 16;
int errorRc = (errorR * c) / 16;
int errorRd = errorR - errorRa - errorRb - errorRc;
int errorGa = (errorG * a) / 16;
int errorGb = (errorG * b) / 16;
int errorGc = (errorG * c) / 16;
int errorGd = errorG - errorGa - errorGb - errorGc;
int errorBa = (errorB * a) / 16;
int errorBb = (errorB * b) / 16;
int errorBc = (errorB * c) / 16;
int errorBd = errorB - errorBa - errorBb - errorBc;
errorThisRowR[col + 1] += errorRa;
errorThisRowG[col + 1] += errorGa;
errorThisRowB[col + 1] += errorBa;
errorNextRowR[width - col] += errorRb;
errorNextRowG[width - col] += errorGb;
errorNextRowB[width - col] += errorBb;
if (col != 0)
{
errorNextRowR[width - (col - 1)] += errorRc;
errorNextRowG[width - (col - 1)] += errorGc;
errorNextRowB[width - (col - 1)] += errorBc;
}
errorNextRowR[width - (col + 1)] += errorRd;
errorNextRowG[width - (col + 1)] += errorGd;
errorNextRowB[width - (col + 1)] += errorBd;
unchecked
{
pSourcePixel += ptrInc;
pDestinationPixel += ptrInc;
}
}
// Add the stride to the source row
pSourceRow += sourceData.Stride;
// And to the destination row
pDestinationRow += outputData.Stride;
errorThisRowB = errorNextRowB;
errorThisRowG = errorNextRowG;
errorThisRowR = errorNextRowR;
}
}
finally
{
// Ensure that I unlock the output bits
output.UnlockBits(outputData);
}
}
/// <summary>
/// Override this to process the pixel in the first pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <remarks>
/// This function need only be overridden if your quantize algorithm needs two passes,
/// such as an Octree quantizer.
/// </remarks>
protected virtual void InitialQuantizePixel(int pixel)
{
}
/// <summary>
/// Override this to process the pixel in the second pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <returns>The quantized value</returns>
protected abstract byte QuantizePixel(int pixel);
/// <summary>
/// Retrieve the palette for the quantized image
/// </summary>
/// <param name="original">Any old palette, this is overrwritten</param>
/// <returns>The new color palette</returns>
protected abstract ColorPalette GetPalette(ColorPalette original);
}
}
| |
namespace Star
{
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Star.Util;
using Star.Util.Log;
using Star.Util.Debug;
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
private Color backgroundColour = Color.Black;
private const int initialRocks = 3;
private Texture2D rockTexture;
private Texture2D starTexture;
private Texture2D hearthTexture;
private Texture2D background;
private Sprite hearth;
private Sprite star;
private List<Sprite> rocks = new List<Sprite>();
private SpriteFont scoreFont;
private int score;
private readonly Random rand = new Random();
private CornerStack cornerStack;
private readonly ILogger logger = ILoggerFactory.getLogger(typeof(Game1));
private AudioEngine audioEngine;
private WaveBank waveBank;
private SoundBank soundBank;
private Cue soundLoop;
private int lastTickCount;
public Game1()
{
this.graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
TargetElapsedTime = System.TimeSpan.FromMilliseconds(100);
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
this.audioEngine = new AudioEngine("Content\\Audio\\MyGameAudio.xgs");
this.waveBank = new WaveBank(this.audioEngine, "Content\\Audio\\Wave Bank.xwb");
this.soundBank = new SoundBank(this.audioEngine, "Content\\Audio\\Sound Bank.xsb");
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
this.soundLoop = this.soundBank.GetCue("125bpm-Minimal--HHats-Snare");
// Create a new SpriteBatch, which can be used to draw textures.
this.spriteBatch = new SpriteBatch(GraphicsDevice);
this.graphics.PreferredBackBufferWidth = 500;
this.graphics.PreferredBackBufferHeight = 500;
this.graphics.ApplyChanges();
this.cornerStack = new CornerStack(new Rectangle(0, 0, this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight));
this.background = Content.Load<Texture2D>("gcenter");
this.starTexture = Content.Load<Texture2D>("star");
this.hearthTexture = Content.Load<Texture2D>("hearth");
this.rockTexture = Content.Load<Texture2D>("rock");
this.scoreFont = Content.Load<SpriteFont>("starfont");
Init();
}
private void SetNextRandomPosition(Sprite aSprite)
{
do
{
aSprite.Position = new Vector2(this.rand.Next((int) this.graphics.PreferredBackBufferWidth - (int) aSprite.Size.X), this.rand.Next(this.graphics.PreferredBackBufferHeight - (int) aSprite.Size.Y));
} while (this.star.CollidesWith(aSprite));
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
this.rockTexture.Dispose();
this.starTexture.Dispose();
this.hearthTexture.Dispose();
this.soundBank.Dispose();
this.waveBank.Dispose();
this.audioEngine.Dispose();
this.background.Dispose();
this.spriteBatch.Dispose();
this.scoreFont = null;
}
private void Init()
{
logger.Debug("Initializing game...");
this.lastTickCount = System.Environment.TickCount;
Queue<Vector2> corners = this.cornerStack.GetRandomCornerStack();
this.star = new Sprite(this.starTexture, Vector2.Zero, new Vector2(35f, 35f), new Vector2(this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight));
this.star.Position = corners.Dequeue();
logger.Debug("...setting star to corner: {0}", star.Position);
this.star.Velocity = Vector2.Zero;
this.hearth = new Sprite(this.hearthTexture, new Vector2(this.graphics.PreferredBackBufferWidth / 2, this.graphics.PreferredBackBufferHeight / 2), new Vector2(23f, 22f), new Vector2(this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight));
this.rocks.Clear();
for (int i = 0; i < initialRocks; i++)
{
Sprite newRock = createRock(corners.Dequeue());
logger.Debug("...setting rock to corner: {0}", newRock.Position);
this.rocks.Add(newRock);
}
this.score = 0;
logger.Debug("...finished initializing.");
if (this.soundLoop.IsPaused)
{
this.soundLoop.Resume();
}
else
{
this.soundLoop.Play();
}
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if ((GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
|| Keyboard.GetState().IsKeyDown(Keys.Escape))
{
this.Exit();
}
if ((GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed)
|| Keyboard.GetState().IsKeyDown(Keys.Space))
{
foreach (Sprite rock in this.rocks)
{
rock.Velocity *= -1;
rock.RandomMovement();
}
}
this.star.Move();
foreach (Sprite rock in this.rocks)
{
rock.RandomMovement();
if (rock.CollidesWith(this.hearth))
{
logger.Debug("Rock {0} collides with hearth", rock.GetHashCode());
rock.Velocity *= -1;
}
if (rock.CollidesWith(this.star))
{
logger.Debug("Rock {0} collides with star", rock.GetHashCode());
this.soundLoop.Pause();
StartVibrating();
System.Threading.Thread.Sleep(1000);
StopVibrating();
Init();
return;
}
foreach (Sprite otherrock in this.rocks)
{
if (rock != otherrock && rock.CollidesWith(otherrock))
{
this.soundBank.PlayCue("FOLEY TECHNOLOGY SPRING DVD PLAYER SPRING VIBRATE LONG 01");
logger.Debug("Rock {0} collides with rock {1}", rock.GetHashCode(), otherrock.GetHashCode());
rock.Velocity *= -1;
otherrock.Velocity *= -1;
otherrock.RandomMovement();
rock.RandomMovement();
}
}
}
if (this.star.CollidesWith(this.hearth))
{
logger.Debug("Star collides with hearth...");
this.soundBank.PlayCue("digital_feedback");
StartVibrating();
this.score++;
if (0 == this.score % 5)
{
this.soundBank.PlayCue("hyperspace_activate");
Sprite newRock = createRock(this.cornerStack.GetCorner(CornerStack.POSITION.LOWER_RIGHT));
this.rocks.Add(newRock);
logger.Debug("...must add new rock at {0}", newRock.Position);
}
SetNextRandomPosition(this.hearth);
}
else
{
StopVibrating();
}
if (System.Environment.TickCount - this.lastTickCount > 10000)
{
this.soundBank.PlayCue("hyperspace_activate");
Sprite newRock = createRock(this.cornerStack.GetCorner(CornerStack.POSITION.LOWER_RIGHT));
this.rocks.Add(newRock);
logger.Debug("...must add new rock at {0}", newRock.Position);
this.lastTickCount = System.Environment.TickCount;
}
base.Update(gameTime);
}
private Sprite createRock(Vector2 position)
{
Assert.FailIfNull(position, "position");
return new Sprite(this.rockTexture,
position,
new Vector2(30f, 30f),
new Vector2(this.graphics.PreferredBackBufferWidth, this.graphics.PreferredBackBufferHeight));
}
private void StopVibrating()
{
this.backgroundColour = Color.Black;
if (GamePad.GetState(PlayerIndex.One).IsConnected)
{
GamePad.SetVibration(PlayerIndex.One, 0f, 0f);
}
}
private void StartVibrating()
{
this.backgroundColour = Color.Red;
if (GamePad.GetState(PlayerIndex.One).IsConnected)
{
GamePad.SetVibration(PlayerIndex.One, 0.5f, 0.5f);
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(this.backgroundColour);
this.spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
this.spriteBatch.Draw(this.background, Vector2.Zero, Color.White);
this.spriteBatch.DrawString(this.scoreFont, "Herzchen: " + this.score, new Vector2(15, 15), Color.Black);
this.spriteBatch.DrawString(this.scoreFont, "Herzchen: " + this.score, new Vector2(16, 16), Color.White);
this.spriteBatch.Draw(this.star.Texture, this.star.Position, Color.White);
this.spriteBatch.Draw(this.hearth.Texture, this.hearth.Position, Color.White);
foreach (Sprite rock in this.rocks)
{
this.spriteBatch.Draw(this.rockTexture, rock.Position, Color.White);
}
this.spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
using qx.ui.core;
namespace qx.ui.container
{
/// <summary>
/// <para>The Resizer is a resizable container widget.</para>
/// <para>It allows to be resized (not moved), normally in
/// the right and/or bottom directions. It is an alternative to splitters.</para>
/// <para>Example</para>
/// <para>Here is a little example of how to use the widget.</para>
/// <code>
/// var resizer = new qx.ui.container.Resizer().set({
/// width: 200,
/// height: 100
/// });
/// resizer.setLayout(new qx.ui.layout.Canvas());
/// var text = new qx.ui.form.TextArea("Resize me\nI'm resizable");
/// resizer.add(text, {edge: 0});
/// this.getRoot().add(resizer);
/// </code>
/// <para>This example creates a resizer, configures it with a canvas layout and
/// adds a text area to it.</para>
/// <para>External Documentation</para>
///
/// Documentation of this widget in the qooxdoo manual.
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.container.Resizer", OmitOptionalParameters = true, Export = false)]
public partial class Resizer : qx.ui.container.Composite
{
#region Properties
/// <summary>
/// <para>The appearance ID. This ID is used to identify the appearance theme
/// entry to use for this widget. This controls the styling of the element.</para>
/// </summary>
[JsProperty(Name = "appearance", NativeField = true)]
public string Appearance { get; set; }
/// <summary>
/// <para>Property group to configure the resize behaviour for all edges at once</para>
/// </summary>
[JsProperty(Name = "resizable", NativeField = true)]
public object Resizable { get; set; }
/// <summary>
/// <para>Whether the bottom edge is resizable</para>
/// </summary>
[JsProperty(Name = "resizableBottom", NativeField = true)]
public bool ResizableBottom { get; set; }
/// <summary>
/// <para>Whether the left edge is resizable</para>
/// </summary>
[JsProperty(Name = "resizableLeft", NativeField = true)]
public bool ResizableLeft { get; set; }
/// <summary>
/// <para>Whether the right edge is resizable</para>
/// </summary>
[JsProperty(Name = "resizableRight", NativeField = true)]
public bool ResizableRight { get; set; }
/// <summary>
/// <para>Whether the top edge is resizable</para>
/// </summary>
[JsProperty(Name = "resizableTop", NativeField = true)]
public bool ResizableTop { get; set; }
/// <summary>
/// <para>The tolerance to activate resizing</para>
/// </summary>
[JsProperty(Name = "resizeSensitivity", NativeField = true)]
public double ResizeSensitivity { get; set; }
/// <summary>
/// <para>Whether a frame replacement should be used during the resize sequence</para>
/// </summary>
[JsProperty(Name = "useResizeFrame", NativeField = true)]
public bool UseResizeFrame { get; set; }
#endregion Properties
#region Methods
public Resizer() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property resizableBottom.</para>
/// </summary>
[JsMethod(Name = "getResizableBottom")]
public bool GetResizableBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property resizableLeft.</para>
/// </summary>
[JsMethod(Name = "getResizableLeft")]
public bool GetResizableLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property resizableRight.</para>
/// </summary>
[JsMethod(Name = "getResizableRight")]
public bool GetResizableRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property resizableTop.</para>
/// </summary>
[JsMethod(Name = "getResizableTop")]
public bool GetResizableTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property resizeSensitivity.</para>
/// </summary>
[JsMethod(Name = "getResizeSensitivity")]
public double GetResizeSensitivity() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property useResizeFrame.</para>
/// </summary>
[JsMethod(Name = "getUseResizeFrame")]
public bool GetUseResizeFrame() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property resizableBottom
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property resizableBottom.</param>
[JsMethod(Name = "initResizableBottom")]
public void InitResizableBottom(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property resizableLeft
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property resizableLeft.</param>
[JsMethod(Name = "initResizableLeft")]
public void InitResizableLeft(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property resizableRight
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property resizableRight.</param>
[JsMethod(Name = "initResizableRight")]
public void InitResizableRight(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property resizableTop
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property resizableTop.</param>
[JsMethod(Name = "initResizableTop")]
public void InitResizableTop(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property resizeSensitivity
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property resizeSensitivity.</param>
[JsMethod(Name = "initResizeSensitivity")]
public void InitResizeSensitivity(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property useResizeFrame
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property useResizeFrame.</param>
[JsMethod(Name = "initUseResizeFrame")]
public void InitUseResizeFrame(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property resizableBottom equals true.</para>
/// </summary>
[JsMethod(Name = "isResizableBottom")]
public void IsResizableBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property resizableLeft equals true.</para>
/// </summary>
[JsMethod(Name = "isResizableLeft")]
public void IsResizableLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property resizableRight equals true.</para>
/// </summary>
[JsMethod(Name = "isResizableRight")]
public void IsResizableRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property resizableTop equals true.</para>
/// </summary>
[JsMethod(Name = "isResizableTop")]
public void IsResizableTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property useResizeFrame equals true.</para>
/// </summary>
[JsMethod(Name = "isUseResizeFrame")]
public void IsUseResizeFrame() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizable.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizable")]
public void ResetResizable() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizableBottom.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizableBottom")]
public void ResetResizableBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizableLeft.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizableLeft")]
public void ResetResizableLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizableRight.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizableRight")]
public void ResetResizableRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizableTop.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizableTop")]
public void ResetResizableTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property resizeSensitivity.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetResizeSensitivity")]
public void ResetResizeSensitivity() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property useResizeFrame.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetUseResizeFrame")]
public void ResetUseResizeFrame() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the values of the property group resizable.</para>
/// <para>This setter supports a shorthand mode compatible with the way margins and paddins are set in CSS.</para>
/// </summary>
/// <param name="resizableTop">Sets the value of the property #resizableTop.</param>
/// <param name="resizableRight">Sets the value of the property #resizableRight.</param>
/// <param name="resizableBottom">Sets the value of the property #resizableBottom.</param>
/// <param name="resizableLeft">Sets the value of the property #resizableLeft.</param>
[JsMethod(Name = "setResizable")]
public void SetResizable(object resizableTop, object resizableRight, object resizableBottom, object resizableLeft) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property resizableBottom.</para>
/// </summary>
/// <param name="value">New value for property resizableBottom.</param>
[JsMethod(Name = "setResizableBottom")]
public void SetResizableBottom(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property resizableLeft.</para>
/// </summary>
/// <param name="value">New value for property resizableLeft.</param>
[JsMethod(Name = "setResizableLeft")]
public void SetResizableLeft(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property resizableRight.</para>
/// </summary>
/// <param name="value">New value for property resizableRight.</param>
[JsMethod(Name = "setResizableRight")]
public void SetResizableRight(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property resizableTop.</para>
/// </summary>
/// <param name="value">New value for property resizableTop.</param>
[JsMethod(Name = "setResizableTop")]
public void SetResizableTop(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property resizeSensitivity.</para>
/// </summary>
/// <param name="value">New value for property resizeSensitivity.</param>
[JsMethod(Name = "setResizeSensitivity")]
public void SetResizeSensitivity(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property useResizeFrame.</para>
/// </summary>
/// <param name="value">New value for property useResizeFrame.</param>
[JsMethod(Name = "setUseResizeFrame")]
public void SetUseResizeFrame(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property resizableBottom.</para>
/// </summary>
[JsMethod(Name = "toggleResizableBottom")]
public void ToggleResizableBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property resizableLeft.</para>
/// </summary>
[JsMethod(Name = "toggleResizableLeft")]
public void ToggleResizableLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property resizableRight.</para>
/// </summary>
[JsMethod(Name = "toggleResizableRight")]
public void ToggleResizableRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property resizableTop.</para>
/// </summary>
[JsMethod(Name = "toggleResizableTop")]
public void ToggleResizableTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property useResizeFrame.</para>
/// </summary>
[JsMethod(Name = "toggleUseResizeFrame")]
public void ToggleUseResizeFrame() { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
//-----------------------------------------------------------------------------
// Filename: RawSocket.cs
//
// Description: Allows the sending of hand crafted IP packets.
//
// History:
// 01 Feb 2008 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2006 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// 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 SIP Sorcery PTY LTD.
// 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 System;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.Sys
{
/// <summary>
/// 0 1 2 3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// |Version| IHL |Type of Service| Total Length |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | Identification |Flags| Fragment Offset |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | Time to Live | Protocol | Header Checksum |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | Source Address |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | Destination Address |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | Options | Padding |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// </summary>
public class IPv4Header
{
public const int MIN_HEADER_LEN = 5; // Minimum length if header in 32 bit words.
public const int IP_VERSION = 4;
public int Version = IP_VERSION;
public int HeaderLength = MIN_HEADER_LEN; // Length of header in 32 bit words.
public int TypeOfService;
public int Length = MIN_HEADER_LEN; // Total length of the IP packet in octets.
public int Id;
public int TTL = 255;
public ProtocolType Protocol; // 1 = ICMP, 6 = TCP, 17 = UDP.
public IPAddress SourceAddress;
public IPAddress DestinationAddress;
// Fragmentation flags. Bit 0=0, Bit 1=DF, Bit 2=MF
public int DF = 1; // 0 = May fragment, 1 = Don't fragment.
public int MF = 0; // 0 = Last fragment, 1 = More fragments.
public int FragmentOffset; // Indiciates where in the datagram the fragment belongs.
public IPv4Header(ProtocolType protocol, int id, IPAddress sourceAddress, IPAddress dstAddress)
{
Protocol = protocol;
Id = id;
SourceAddress = sourceAddress;
DestinationAddress = dstAddress;
}
public byte[] GetBytes()
{
byte[] header = new byte[HeaderLength * 4];
header[0] = (byte)((Version << 4) + HeaderLength);
header[1] = (byte)TypeOfService;
header[2] = (byte)(Length >> 8);
header[3] = (byte)Length;
header[4] = (byte)(Id >> 8);
header[5] = (byte)Id;
header[6] = (byte)(DF * 64 + MF * 32 + (FragmentOffset >> 8));
header[7] = (byte)FragmentOffset;
header[8] = (byte)TTL;
header[9] = (byte)Protocol;
Buffer.BlockCopy(SourceAddress.GetAddressBytes(), 0, header, 12, 4);
Buffer.BlockCopy(DestinationAddress.GetAddressBytes(), 0, header, 16, 4);
UInt16 checksum = GetChecksum(header);
header[10] = (byte)(checksum >> 8);
header[11] = (byte)checksum;
return header;
}
public UInt16 GetChecksum(byte[] buffer)
{
int checksum = 0;
for(int index=0; index<buffer.Length-2; index=index+2)
{
checksum += (buffer[index] << 4) + buffer[index + 1];
}
//checksum = (checksum >> 16) + (checksum & 0xffff);
//cksum += (checksum >> 16);
return (UInt16) ~checksum;
}
}
/// <summary>
/// 0 7 8 15 16 23 24 31
/// +--------+--------+--------+--------+
/// | Source | Destination |
/// | Port | Port |
/// +--------+--------+--------+--------+
/// | | |
/// | Length | Checksum |
/// +--------+--------+--------+--------+
/// |
/// | data octets ...
/// +---------------- ...
///
/// </summary>
public class UDPPacket
{
public int SourcePort;
public int DestinationPort;
public byte[] Payload;
public UDPPacket(int sourcePort, int destinationPort, byte[] payload)
{
SourcePort = sourcePort;
DestinationPort = destinationPort;
Payload = payload;
}
public byte[] GetBytes()
{
byte[] packet = new byte[8 + Payload.Length];
packet[0] = (byte)(SourcePort >> 8);
packet[1] = (byte)SourcePort;
packet[2] = (byte)(DestinationPort >> 8);
packet[3] = (byte)DestinationPort;
packet[4] = (byte)(packet.Length >> 8);
packet[5] = (byte)packet.Length;
Buffer.BlockCopy(Payload, 0, packet, 8, Payload.Length);
return packet;
}
}
public class IPv4Packet
{
public IPv4Header Header;
public byte[] Payload;
public IPv4Packet(IPv4Header header, byte[] payload)
{
Header = header;
Payload = payload;
Header.Length = Header.HeaderLength * 2 + Payload.Length / 2;
}
public byte[] GetBytes()
{
byte[] packet = new byte[Header.Length * 2];
Buffer.BlockCopy(Header.GetBytes(), 0, packet, 0, Header.HeaderLength * 4);
Buffer.BlockCopy(Payload, 0, packet, Header.HeaderLength * 4, Payload.Length);
return packet;
}
}
public class RawSocket
{
public void SendSpoofedPacket(byte[] payload, IPEndPoint sourceSocket, IPEndPoint destinationSocket)
{
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class IPSocketUnitTest
{
[TestFixtureSetUp]
public void Init()
{
}
[TestFixtureTearDown]
public void Dispose()
{
}
[Test]
public void SampleTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
Assert.IsTrue(true, "True was false.");
}
[Test]
public void IPHeaderConstructionUnitTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
IPv4Header header = new IPv4Header(ProtocolType.Udp, 4567, IPAddress.Parse("194.213.29.54"), IPAddress.Parse("194.213.29.54"));
byte[] headerData = header.GetBytes();
int count = 0;
foreach (byte headerByte in headerData)
{
Console.Write("0x{0,-2:x} ", headerByte);
count++;
if (count % 4 == 0)
{
Console.Write("\n");
}
}
Console.WriteLine();
Assert.IsTrue(true, "True was false.");
}
[Test]
[Ignore("Will only work on WinXP or where raw socket privileges have been explicitly granted.")]
public void PreconstructedIPPacketSendUnitTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
byte[] ipPacket = new byte[] {
// IP Header.
0x45, 0x30, 0x0, 0x4,
0xe4, 0x29, 0x0, 0x0,
0x80, 0x0, 0x62, 0x3d,
0x0a, 0x0, 0x0, 0x64,
0xc2, 0xd5, 0x1d, 0x36,
// Data.
0x0, 0x0, 0x0, 0x0
};
Socket rawSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
rawSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
try
{
rawSocket.SendTo(ipPacket, new IPEndPoint(IPAddress.Parse("194.213.29.54"), 5060));
}
catch (SocketException sockExcp)
{
Console.WriteLine("Socket exception error code= " + sockExcp.ErrorCode + ". " + sockExcp.Message);
throw sockExcp;
}
rawSocket.Shutdown(SocketShutdown.Both);
rawSocket.Close();
Assert.IsTrue(true, "True was false.");
}
[Test]
[Ignore("Will only work on WinXP or where raw socket privileges have been explicitly granted.")]
public void IPEmptyPacketSendUnitTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
UDPPacket udpPacket = new UDPPacket(4001, 4001, new byte[] { 0x1, 0x2, 0x3, 0x4 });
IPv4Header header = new IPv4Header(ProtocolType.Udp, 7890, IPAddress.Parse("194.213.29.54"), IPAddress.Parse("194.213.29.54"));
byte[] headerData = header.GetBytes();
foreach (byte headerByte in headerData)
{
Console.Write("0x{0:x} ", headerByte);
}
Console.WriteLine();
Socket rawSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
//rawSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
rawSocket.SendTo(headerData, new IPEndPoint(IPAddress.Parse("194.213.29.54"), 5060));
rawSocket.Shutdown(SocketShutdown.Both);
rawSocket.Close();
Assert.IsTrue(true, "True was false.");
}
}
#endif
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking {
[ToolboxItem(false)]
public partial class DockPane : UserControl, IDockDragSource {
public enum AppearanceStyle {
ToolWindow,
Document
}
private enum HitTestArea {
Caption,
TabStrip,
Content,
None
}
private struct HitTestResult {
public HitTestArea HitArea;
public int Index;
public HitTestResult(HitTestArea hitTestArea, int index) {
HitArea = hitTestArea;
Index = index;
}
}
private DockPaneCaptionBase m_captionControl;
private DockPaneCaptionBase CaptionControl {
get { return m_captionControl; }
}
private DockPaneStripBase m_tabStripControl;
internal DockPaneStripBase TabStripControl {
get { return m_tabStripControl; }
}
internal protected DockPane(IDockContent content, DockState visibleState, bool show) {
InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show) {
if (floatWindow == null)
throw new ArgumentNullException("floatWindow");
InternalConstruct(content, DockState.Float, false, Rectangle.Empty, floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show);
}
internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show) {
if (previousPane == null)
throw (new ArgumentNullException("previousPane"));
InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, proportion, show);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show) {
InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show);
}
private void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show) {
if (dockState == DockState.Hidden || dockState == DockState.Unknown)
throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState);
if (content == null)
throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent);
if (content.DockHandler.DockPanel == null)
throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel);
SuspendLayout();
SetStyle(ControlStyles.Selectable, false);
m_isFloat = (dockState == DockState.Float);
m_contents = new DockContentCollection();
m_displayingContents = new DockContentCollection(this);
m_dockPanel = content.DockHandler.DockPanel;
m_dockPanel.AddPane(this);
m_splitter = new SplitterControl(this);
m_nestedDockingStatus = new NestedDockingStatus(this);
m_captionControl = DockPanel.DockPaneCaptionFactory.CreateDockPaneCaption(this);
m_tabStripControl = DockPanel.DockPaneStripFactory.CreateDockPaneStrip(this);
Controls.AddRange(new Control[] { m_captionControl, m_tabStripControl });
DockPanel.SuspendLayout(true);
if (flagBounds)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds);
else if (prevPane != null)
DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion);
SetDockState(dockState);
if (show)
content.DockHandler.Pane = this;
else if (this.IsFloat)
content.DockHandler.FloatPane = this;
else
content.DockHandler.PanelPane = this;
ResumeLayout();
DockPanel.ResumeLayout(true, true);
}
protected override void Dispose(bool disposing) {
if (disposing) {
m_dockState = DockState.Unknown;
if (NestedPanesContainer != null)
NestedPanesContainer.NestedPanes.Remove(this);
if (DockPanel != null) {
DockPanel.RemovePane(this);
m_dockPanel = null;
}
Splitter.Dispose();
if (m_autoHidePane != null)
m_autoHidePane.Dispose();
}
try {
base.Dispose(disposing);
}
catch (Exception) {
}
}
private IDockContent m_activeContent = null;
public virtual IDockContent ActiveContent {
get { return m_activeContent; }
set {
if (ActiveContent == value)
return;
if (value != null) {
if (!DisplayingContents.Contains(value))
throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue));
}
else {
if (DisplayingContents.Count != 0)
throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue));
}
IDockContent oldValue = m_activeContent;
if (DockPanel.ActiveAutoHideContent == oldValue)
DockPanel.ActiveAutoHideContent = null;
m_activeContent = value;
if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) {
if (m_activeContent != null)
m_activeContent.DockHandler.Form.BringToFront();
}
else {
if (m_activeContent != null)
m_activeContent.DockHandler.SetVisible();
if (oldValue != null && DisplayingContents.Contains(oldValue))
oldValue.DockHandler.SetVisible();
if (IsActivated && m_activeContent != null)
m_activeContent.DockHandler.Activate();
}
if (FloatWindow != null)
FloatWindow.SetText();
if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi &&
DockState == DockState.Document)
RefreshChanges(false); // delayed layout to reduce screen flicker
else
RefreshChanges();
if (m_activeContent != null)
TabStripControl.EnsureTabVisible(m_activeContent);
}
}
private bool m_allowDockDragAndDrop = true;
public virtual bool AllowDockDragAndDrop {
get { return m_allowDockDragAndDrop; }
set { m_allowDockDragAndDrop = value; }
}
private IDisposable m_autoHidePane = null;
internal IDisposable AutoHidePane {
get { return m_autoHidePane; }
set { m_autoHidePane = value; }
}
private object m_autoHideTabs = null;
internal object AutoHideTabs {
get { return m_autoHideTabs; }
set { m_autoHideTabs = value; }
}
private object TabPageContextMenu {
get {
IDockContent content = ActiveContent;
if (content == null)
return null;
if (content.DockHandler.TabPageContextMenuStrip != null)
return content.DockHandler.TabPageContextMenuStrip;
else if (content.DockHandler.TabPageContextMenu != null)
return content.DockHandler.TabPageContextMenu;
else
return null;
}
}
internal bool HasTabPageContextMenu {
get { return TabPageContextMenu != null; }
}
internal void ShowTabPageContextMenu(Control control, Point position) {
object menu = TabPageContextMenu;
if (menu == null)
return;
ContextMenuStrip contextMenuStrip = menu as ContextMenuStrip;
if (contextMenuStrip != null) {
contextMenuStrip.Show(control, position);
return;
}
ContextMenu contextMenu = menu as ContextMenu;
if (contextMenu != null)
contextMenu.Show(this, position);
}
private Rectangle CaptionRectangle {
get {
if (!HasCaption)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int x, y, width;
x = rectWindow.X;
y = rectWindow.Y;
width = rectWindow.Width;
int height = CaptionControl.MeasureHeight();
return new Rectangle(x, y, width, height);
}
}
internal Rectangle ContentRectangle {
get {
Rectangle rectWindow = DisplayingRectangle;
Rectangle rectCaption = CaptionRectangle;
Rectangle rectTabStrip = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height);
if (DockState == DockState.Document && DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Top)
y += rectTabStrip.Height;
int width = rectWindow.Width;
int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height;
return new Rectangle(x, y, width, height);
}
}
internal Rectangle TabStripRectangle {
get {
if (Appearance == AppearanceStyle.ToolWindow)
return TabStripRectangle_ToolWindow;
else
return TabStripRectangle_Document;
}
}
private Rectangle TabStripRectangle_ToolWindow {
get {
if (DisplayingContents.Count <= 1 || IsAutoHide)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int width = rectWindow.Width;
int height = TabStripControl.MeasureHeight();
int x = rectWindow.X;
int y = rectWindow.Bottom - height;
Rectangle rectCaption = CaptionRectangle;
if (rectCaption.Contains(x, y))
y = rectCaption.Y + rectCaption.Height;
return new Rectangle(x, y, width, height);
}
}
private Rectangle TabStripRectangle_Document {
get {
if (DisplayingContents.Count == 0)
return Rectangle.Empty;
if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi)
return Rectangle.Empty;
Rectangle rectWindow = DisplayingRectangle;
int x = rectWindow.X;
int width = rectWindow.Width;
int height = TabStripControl.MeasureHeight();
int y = 0;
if (DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
y = rectWindow.Height - height;
else
y = rectWindow.Y;
return new Rectangle(x, y, width, height);
}
}
public virtual string CaptionText {
get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; }
}
private DockContentCollection m_contents;
public DockContentCollection Contents {
get { return m_contents; }
}
private DockContentCollection m_displayingContents;
public DockContentCollection DisplayingContents {
get { return m_displayingContents; }
}
private DockPanel m_dockPanel;
public DockPanel DockPanel {
get { return m_dockPanel; }
}
private bool HasCaption {
get {
if (DockState == DockState.Document ||
DockState == DockState.Hidden ||
DockState == DockState.Unknown ||
(DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1))
return false;
else
return true;
}
}
private bool m_isActivated = false;
public bool IsActivated {
get { return m_isActivated; }
}
internal void SetIsActivated(bool value) {
if (m_isActivated == value)
return;
m_isActivated = value;
if (DockState != DockState.Document)
RefreshChanges(false);
OnIsActivatedChanged(EventArgs.Empty);
}
private bool m_isActiveDocumentPane = false;
public bool IsActiveDocumentPane {
get { return m_isActiveDocumentPane; }
}
internal void SetIsActiveDocumentPane(bool value) {
if (m_isActiveDocumentPane == value)
return;
m_isActiveDocumentPane = value;
if (DockState == DockState.Document)
RefreshChanges();
OnIsActiveDocumentPaneChanged(EventArgs.Empty);
}
public bool IsDockStateValid(DockState dockState) {
foreach (IDockContent content in Contents)
if (!content.DockHandler.IsDockStateValid(dockState))
return false;
return true;
}
public bool IsAutoHide {
get { return DockHelper.IsDockStateAutoHide(DockState); }
}
public AppearanceStyle Appearance {
get { return (DockState == DockState.Document) ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; }
}
internal Rectangle DisplayingRectangle {
get { return ClientRectangle; }
}
public void Activate() {
if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent)
DockPanel.ActiveAutoHideContent = ActiveContent;
else if (!IsActivated && ActiveContent != null)
ActiveContent.DockHandler.Activate();
}
internal void AddContent(IDockContent content) {
if (Contents.Contains(content))
return;
Contents.Add(content);
}
internal void Close() {
Dispose();
}
public void CloseActiveContent() {
CloseContent(ActiveContent);
}
internal void CloseContent(IDockContent content) {
DockPanel dockPanel = DockPanel;
if (content == null)
return;
if (!content.DockHandler.CloseButton)
return;
dockPanel.SuspendLayout(true);
try {
if (content.DockHandler.HideOnClose) {
content.DockHandler.Hide();
NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this);
}
else
content.DockHandler.Close();
}
finally {
dockPanel.ResumeLayout(true, true);
}
}
private HitTestResult GetHitTest(Point ptMouse) {
Point ptMouseClient = PointToClient(ptMouse);
Rectangle rectCaption = CaptionRectangle;
if (rectCaption.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.Caption, -1);
Rectangle rectContent = ContentRectangle;
if (rectContent.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.Content, -1);
Rectangle rectTabStrip = TabStripRectangle;
if (rectTabStrip.Contains(ptMouseClient))
return new HitTestResult(HitTestArea.TabStrip, TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse)));
return new HitTestResult(HitTestArea.None, -1);
}
private bool m_isHidden = true;
public bool IsHidden {
get { return m_isHidden; }
}
private void SetIsHidden(bool value) {
if (m_isHidden == value)
return;
m_isHidden = value;
if (DockHelper.IsDockStateAutoHide(DockState)) {
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
else if (NestedPanesContainer != null)
((Control)NestedPanesContainer).PerformLayout();
}
protected override void OnLayout(LayoutEventArgs levent) {
SetIsHidden(DisplayingContents.Count == 0);
if (!IsHidden) {
CaptionControl.Bounds = CaptionRectangle;
TabStripControl.Bounds = TabStripRectangle;
SetContentBounds();
foreach (IDockContent content in Contents) {
if (DisplayingContents.Contains(content))
if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible)
content.DockHandler.FlagClipWindow = false;
}
}
base.OnLayout(levent);
}
internal void SetContentBounds() {
Rectangle rectContent = ContentRectangle;
if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi)
rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent));
Rectangle rectInactive = new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height);
foreach (IDockContent content in Contents)
if (content.DockHandler.Pane == this) {
if (content == ActiveContent)
content.DockHandler.Form.Bounds = rectContent;
else
content.DockHandler.Form.Bounds = rectInactive;
}
}
internal void RefreshChanges() {
RefreshChanges(true);
}
private void RefreshChanges(bool performLayout) {
if (IsDisposed)
return;
CaptionControl.RefreshChanges();
TabStripControl.RefreshChanges();
if (DockState == DockState.Float && FloatWindow != null)
FloatWindow.RefreshChanges();
if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null) {
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
if (performLayout)
PerformLayout();
}
internal void RemoveContent(IDockContent content) {
if (!Contents.Contains(content))
return;
Contents.Remove(content);
}
public void SetContentIndex(IDockContent content, int index) {
int oldIndex = Contents.IndexOf(content);
if (oldIndex == -1)
throw (new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent));
if (index < 0 || index > Contents.Count - 1)
if (index != -1)
throw (new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex));
if (oldIndex == index)
return;
if (oldIndex == Contents.Count - 1 && index == -1)
return;
Contents.Remove(content);
if (index == -1)
Contents.Add(content);
else if (oldIndex < index)
Contents.AddAt(content, index - 1);
else
Contents.AddAt(content, index);
RefreshChanges();
}
private void SetParent() {
if (DockState == DockState.Unknown || DockState == DockState.Hidden) {
SetParent(null);
Splitter.Parent = null;
}
else if (DockState == DockState.Float) {
SetParent(FloatWindow);
Splitter.Parent = FloatWindow;
}
else if (DockHelper.IsDockStateAutoHide(DockState)) {
SetParent(DockPanel.AutoHideControl);
Splitter.Parent = null;
}
else {
SetParent(DockPanel.DockWindows[DockState]);
Splitter.Parent = Parent;
}
}
private void SetParent(Control value) {
if (Parent == value)
return;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Workaround of .Net Framework bug:
// Change the parent of a control with focus may result in the first
// MDI child form get activated.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Parent = value;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Workaround of .Net Framework bug:
// Change the parent of a control with focus may result in the first
// MDI child form get activated.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (contentFocused != null)
contentFocused.DockHandler.Activate();
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
public new void Show() {
Activate();
}
internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline) {
if (!dragSource.CanDockTo(this))
return;
Point ptMouse = Control.MousePosition;
HitTestResult hitTestResult = GetHitTest(ptMouse);
if (hitTestResult.HitArea == HitTestArea.Caption)
dockOutline.Show(this, -1);
else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1)
dockOutline.Show(this, hitTestResult.Index);
}
internal void ValidateActiveContent() {
if (ActiveContent == null) {
if (DisplayingContents.Count != 0)
ActiveContent = DisplayingContents[0];
return;
}
if (DisplayingContents.IndexOf(ActiveContent) >= 0)
return;
IDockContent prevVisible = null;
for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--)
if (Contents[i].DockHandler.DockState == DockState) {
prevVisible = Contents[i];
break;
}
IDockContent nextVisible = null;
for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++)
if (Contents[i].DockHandler.DockState == DockState) {
nextVisible = Contents[i];
break;
}
if (prevVisible != null)
ActiveContent = prevVisible;
else if (nextVisible != null)
ActiveContent = nextVisible;
else
ActiveContent = null;
}
private static readonly object DockStateChangedEvent = new object();
public event EventHandler DockStateChanged {
add { Events.AddHandler(DockStateChangedEvent, value); }
remove { Events.RemoveHandler(DockStateChangedEvent, value); }
}
protected virtual void OnDockStateChanged(EventArgs e) {
EventHandler handler = (EventHandler)Events[DockStateChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object IsActivatedChangedEvent = new object();
public event EventHandler IsActivatedChanged {
add { Events.AddHandler(IsActivatedChangedEvent, value); }
remove { Events.RemoveHandler(IsActivatedChangedEvent, value); }
}
protected virtual void OnIsActivatedChanged(EventArgs e) {
EventHandler handler = (EventHandler)Events[IsActivatedChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object IsActiveDocumentPaneChangedEvent = new object();
public event EventHandler IsActiveDocumentPaneChanged {
add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); }
remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); }
}
protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e) {
EventHandler handler = (EventHandler)Events[IsActiveDocumentPaneChangedEvent];
if (handler != null)
handler(this, e);
}
public DockWindow DockWindow {
get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as DockWindow; }
set {
DockWindow oldValue = DockWindow;
if (oldValue == value)
return;
DockTo(value);
}
}
public FloatWindow FloatWindow {
get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as FloatWindow; }
set {
FloatWindow oldValue = FloatWindow;
if (oldValue == value)
return;
DockTo(value);
}
}
private NestedDockingStatus m_nestedDockingStatus;
public NestedDockingStatus NestedDockingStatus {
get { return m_nestedDockingStatus; }
}
private bool m_isFloat;
public bool IsFloat {
get { return m_isFloat; }
}
public INestedPanesContainer NestedPanesContainer {
get {
if (NestedDockingStatus.NestedPanes == null)
return null;
else
return NestedDockingStatus.NestedPanes.Container;
}
}
private DockState m_dockState = DockState.Unknown;
public DockState DockState {
get { return m_dockState; }
set {
SetDockState(value);
}
}
public DockPane SetDockState(DockState value) {
if (value == DockState.Unknown || value == DockState.Hidden)
throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState);
if ((value == DockState.Float) == this.IsFloat) {
InternalSetDockState(value);
return this;
}
if (DisplayingContents.Count == 0)
return null;
IDockContent firstContent = null;
for (int i = 0; i < DisplayingContents.Count; i++) {
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(value)) {
firstContent = content;
break;
}
}
if (firstContent == null)
return null;
firstContent.DockHandler.DockState = value;
DockPane pane = firstContent.DockHandler.Pane;
DockPanel.SuspendLayout(true);
for (int i = 0; i < DisplayingContents.Count; i++) {
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(value))
content.DockHandler.Pane = pane;
}
DockPanel.ResumeLayout(true, true);
return pane;
}
private void InternalSetDockState(DockState value) {
if (m_dockState == value)
return;
DockState oldDockState = m_dockState;
INestedPanesContainer oldContainer = NestedPanesContainer;
m_dockState = value;
SuspendRefreshStateChange();
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
if (!IsFloat)
DockWindow = DockPanel.DockWindows[DockState];
else if (FloatWindow == null)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this);
if (contentFocused != null)
DockPanel.ContentFocusManager.Activate(contentFocused);
ResumeRefreshStateChange(oldContainer, oldDockState);
}
private int m_countRefreshStateChange = 0;
private void SuspendRefreshStateChange() {
m_countRefreshStateChange++;
DockPanel.SuspendLayout(true);
}
private void ResumeRefreshStateChange() {
m_countRefreshStateChange--;
System.Diagnostics.Debug.Assert(m_countRefreshStateChange >= 0);
DockPanel.ResumeLayout(true, true);
}
private bool IsRefreshStateChangeSuspended {
get { return m_countRefreshStateChange != 0; }
}
private void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) {
ResumeRefreshStateChange();
RefreshStateChange(oldContainer, oldDockState);
}
private void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) {
lock (this) {
if (IsRefreshStateChangeSuspended)
return;
SuspendRefreshStateChange();
}
DockPanel.SuspendLayout(true);
IDockContent contentFocused = GetFocusedContent();
if (contentFocused != null)
DockPanel.SaveFocus();
SetParent();
if (ActiveContent != null)
ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, ActiveContent.DockHandler.Pane);
foreach (IDockContent content in Contents) {
if (content.DockHandler.Pane == this)
content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane);
}
if (oldContainer != null) {
Control oldContainerControl = (Control)oldContainer;
if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed)
oldContainerControl.PerformLayout();
}
if (DockHelper.IsDockStateAutoHide(oldDockState))
DockPanel.RefreshActiveAutoHideContent();
if (NestedPanesContainer.DockState == DockState)
((Control)NestedPanesContainer).PerformLayout();
if (DockHelper.IsDockStateAutoHide(DockState))
DockPanel.RefreshActiveAutoHideContent();
if (DockHelper.IsDockStateAutoHide(oldDockState) ||
DockHelper.IsDockStateAutoHide(DockState)) {
DockPanel.RefreshAutoHideStrip();
DockPanel.PerformLayout();
}
ResumeRefreshStateChange();
if (contentFocused != null)
contentFocused.DockHandler.Activate();
DockPanel.ResumeLayout(true, true);
if (oldDockState != DockState)
OnDockStateChanged(EventArgs.Empty);
}
private IDockContent GetFocusedContent() {
IDockContent contentFocused = null;
foreach (IDockContent content in Contents) {
if (content.DockHandler.Form.ContainsFocus) {
contentFocused = content;
break;
}
}
return contentFocused;
}
public DockPane DockTo(INestedPanesContainer container) {
if (container == null)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer);
DockAlignment alignment;
if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight)
alignment = DockAlignment.Bottom;
else
alignment = DockAlignment.Right;
return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5);
}
public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, double proportion) {
if (container == null)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer);
if (container.IsFloat == this.IsFloat) {
InternalAddToDockList(container, previousPane, alignment, proportion);
return this;
}
IDockContent firstContent = GetFirstContent(container.DockState);
if (firstContent == null)
return null;
DockPane pane;
DockPanel.DummyContent.DockPanel = DockPanel;
if (container.IsFloat)
pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow)container, true);
else
pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true);
pane.DockTo(container, previousPane, alignment, proportion);
SetVisibleContentsToPane(pane);
DockPanel.DummyContent.DockPanel = null;
return pane;
}
private void SetVisibleContentsToPane(DockPane pane) {
SetVisibleContentsToPane(pane, ActiveContent);
}
private void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent) {
for (int i = 0; i < DisplayingContents.Count; i++) {
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(pane.DockState)) {
content.DockHandler.Pane = pane;
i--;
}
}
if (activeContent.DockHandler.Pane == pane)
pane.ActiveContent = activeContent;
}
private void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, double proportion) {
if ((container.DockState == DockState.Float) != IsFloat)
throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer);
int count = container.NestedPanes.Count;
if (container.NestedPanes.Contains(this))
count--;
if (prevPane == null && count > 0)
throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane);
if (prevPane != null && !container.NestedPanes.Contains(prevPane))
throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane);
if (prevPane == this)
throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane);
INestedPanesContainer oldContainer = NestedPanesContainer;
DockState oldDockState = DockState;
container.NestedPanes.Add(this);
NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion);
if (DockHelper.IsDockWindowState(DockState))
m_dockState = container.DockState;
RefreshStateChange(oldContainer, oldDockState);
}
public void SetNestedDockingProportion(double proportion) {
NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, NestedDockingStatus.Alignment, proportion);
if (NestedPanesContainer != null)
((Control)NestedPanesContainer).PerformLayout();
}
public DockPane Float() {
DockPanel.SuspendLayout(true);
IDockContent activeContent = ActiveContent;
DockPane floatPane = GetFloatPaneFromContents();
if (floatPane == null) {
IDockContent firstContent = GetFirstContent(DockState.Float);
if (firstContent == null) {
DockPanel.ResumeLayout(true, true);
return null;
}
floatPane = DockPanel.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true);
}
SetVisibleContentsToPane(floatPane, activeContent);
DockPanel.ResumeLayout(true, true);
return floatPane;
}
private DockPane GetFloatPaneFromContents() {
DockPane floatPane = null;
for (int i = 0; i < DisplayingContents.Count; i++) {
IDockContent content = DisplayingContents[i];
if (!content.DockHandler.IsDockStateValid(DockState.Float))
continue;
if (floatPane != null && content.DockHandler.FloatPane != floatPane)
return null;
else
floatPane = content.DockHandler.FloatPane;
}
return floatPane;
}
private IDockContent GetFirstContent(DockState dockState) {
for (int i = 0; i < DisplayingContents.Count; i++) {
IDockContent content = DisplayingContents[i];
if (content.DockHandler.IsDockStateValid(dockState))
return content;
}
return null;
}
public void RestoreToPanel() {
DockPanel.SuspendLayout(true);
IDockContent activeContent = DockPanel.ActiveContent;
for (int i = DisplayingContents.Count - 1; i >= 0; i--) {
IDockContent content = DisplayingContents[i];
if (content.DockHandler.CheckDockState(false) != DockState.Unknown)
content.DockHandler.IsFloat = false;
}
DockPanel.ResumeLayout(true, true);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m) {
if (m.Msg == (int)Win32.Msgs.WM_MOUSEACTIVATE)
Activate();
base.WndProc(ref m);
}
#region IDockDragSource Members
#region IDragSource Members
Control IDragSource.DragControl {
get { return this; }
}
#endregion
bool IDockDragSource.IsDockStateValid(DockState dockState) {
return IsDockStateValid(dockState);
}
bool IDockDragSource.CanDockTo(DockPane pane) {
if (!IsDockStateValid(pane.DockState))
return false;
if (pane == this)
return false;
return true;
}
Rectangle IDockDragSource.BeginDrag(Point ptMouse) {
Point location = PointToScreen(new Point(0, 0));
Size size;
DockPane floatPane = ActiveContent.DockHandler.FloatPane;
if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1)
size = DockPanel.DefaultFloatWindowSize;
else
size = floatPane.FloatWindow.Size;
if (ptMouse.X > location.X + size.Width)
location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize;
return new Rectangle(location, size);
}
public void FloatAt(Rectangle floatWindowBounds) {
if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1)
FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds);
else
FloatWindow.Bounds = floatWindowBounds;
DockState = DockState.Float;
NestedDockingStatus.NestedPanes.Remove(this);
}
public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) {
if (dockStyle == DockStyle.Fill) {
IDockContent activeContent = ActiveContent;
for (int i = Contents.Count - 1; i >= 0; i--) {
IDockContent c = Contents[i];
if (c.DockHandler.DockState == DockState) {
c.DockHandler.Pane = pane;
if (contentIndex != -1)
pane.SetContentIndex(c, contentIndex);
}
}
pane.ActiveContent = activeContent;
}
else {
if (dockStyle == DockStyle.Left)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5);
else if (dockStyle == DockStyle.Right)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5);
else if (dockStyle == DockStyle.Top)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5);
else if (dockStyle == DockStyle.Bottom)
DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5);
DockState = pane.DockState;
}
}
public void DockTo(DockPanel panel, DockStyle dockStyle) {
if (panel != DockPanel)
throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel");
if (dockStyle == DockStyle.Top)
DockState = DockState.DockTop;
else if (dockStyle == DockStyle.Bottom)
DockState = DockState.DockBottom;
else if (dockStyle == DockStyle.Left)
DockState = DockState.DockLeft;
else if (dockStyle == DockStyle.Right)
DockState = DockState.DockRight;
else if (dockStyle == DockStyle.Fill)
DockState = DockState.Document;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using MdToken = System.Reflection.MetadataToken;
namespace System.Reflection
{
[Serializable]
internal unsafe sealed class RuntimeParameterInfo : ParameterInfo, ISerializable
{
#region Static Members
internal unsafe static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig)
{
Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
ParameterInfo dummy;
return GetParameters(method, member, sig, out dummy, false);
}
internal unsafe static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig)
{
Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
ParameterInfo returnParameter;
GetParameters(method, member, sig, out returnParameter, true);
return returnParameter;
}
internal unsafe static ParameterInfo[] GetParameters(
IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter)
{
returnParameter = null;
int sigArgCount = sig.Arguments.Length;
ParameterInfo[] args = fetchReturnParameter ? null : new ParameterInfo[sigArgCount];
int tkMethodDef = RuntimeMethodHandle.GetMethodDef(methodHandle);
int cParamDefs = 0;
// Not all methods have tokens. Arrays, pointers and byRef types do not have tokens as they
// are generated on the fly by the runtime.
if (!MdToken.IsNullToken(tkMethodDef))
{
MetadataImport scope = RuntimeTypeHandle.GetMetadataImport(RuntimeMethodHandle.GetDeclaringType(methodHandle));
MetadataEnumResult tkParamDefs;
scope.EnumParams(tkMethodDef, out tkParamDefs);
cParamDefs = tkParamDefs.Length;
// Not all parameters have tokens. Parameters may have no token
// if they have no name and no attributes.
if (cParamDefs > sigArgCount + 1 /* return type */)
throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch);
for (int i = 0; i < cParamDefs; i++)
{
#region Populate ParameterInfos
ParameterAttributes attr;
int position, tkParamDef = tkParamDefs[i];
scope.GetParamDefProps(tkParamDef, out position, out attr);
position--;
if (fetchReturnParameter == true && position == -1)
{
// more than one return parameter?
if (returnParameter != null)
throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch);
returnParameter = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member);
}
else if (fetchReturnParameter == false && position >= 0)
{
// position beyong sigArgCount?
if (position >= sigArgCount)
throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch);
args[position] = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member);
}
#endregion
}
}
// Fill in empty ParameterInfos for those without tokens
if (fetchReturnParameter)
{
if (returnParameter == null)
{
returnParameter = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, -1, (ParameterAttributes)0, member);
}
}
else
{
if (cParamDefs < args.Length + 1)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] != null)
continue;
args[i] = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, i, (ParameterAttributes)0, member);
}
}
}
return args;
}
#endregion
#region Private Statics
private static readonly Type s_DecimalConstantAttributeType = typeof(DecimalConstantAttribute);
private static readonly Type s_CustomConstantAttributeType = typeof(CustomConstantAttribute);
#endregion
#region Private Data Members
// These are new in Whidbey, so we cannot serialize them directly or we break backwards compatibility.
[NonSerialized]
private int m_tkParamDef;
[NonSerialized]
private MetadataImport m_scope;
[NonSerialized]
private Signature m_signature;
[NonSerialized]
private volatile bool m_nameIsCached = false;
[NonSerialized]
private readonly bool m_noMetadata = false;
[NonSerialized]
private bool m_noDefaultValue = false;
[NonSerialized]
private MethodBase m_originalMember = null;
#endregion
#region Internal Properties
internal MethodBase DefiningMethod
{
get
{
MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase;
Debug.Assert(result != null);
return result;
}
}
#endregion
#region Internal Methods
internal void SetName(string name)
{
NameImpl = name;
}
internal void SetAttributes(ParameterAttributes attributes)
{
AttrsImpl = attributes;
}
#endregion
#region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints.
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// We could be serializing for consumption by a pre-Whidbey
// endpoint. Therefore we set up all the serialized fields to look
// just like a v1.0/v1.1 instance.
// Need to set the type to ParameterInfo so that pre-Whidbey and Whidbey code
// can deserialize this. This is also why we cannot simply use [OnSerializing].
info.SetType(typeof(ParameterInfo));
// Use the properties intead of the fields in case the fields haven't been et
// _importer, bExtraConstChecked, and m_cachedData don't need to be set
// Now set the legacy fields that the current implementation doesn't
// use any more. Note that _importer is a raw pointer that should
// never have been serialized in V1. We set it to zero here; if the
// deserializer uses it (by calling GetCustomAttributes() on this
// instance) they'll AV, but at least it will be a well defined
// exception and not a random AV.
info.AddValue("AttrsImpl", Attributes);
info.AddValue("ClassImpl", ParameterType);
info.AddValue("DefaultValueImpl", DefaultValue);
info.AddValue("MemberImpl", Member);
info.AddValue("NameImpl", Name);
info.AddValue("PositionImpl", Position);
info.AddValue("_token", m_tkParamDef);
}
#endregion
#region Constructor
// used by RuntimePropertyInfo
internal RuntimeParameterInfo(RuntimeParameterInfo accessor, RuntimePropertyInfo property)
: this(accessor, (MemberInfo)property)
{
m_signature = property.Signature;
}
private RuntimeParameterInfo(RuntimeParameterInfo accessor, MemberInfo member)
{
// Change ownership
MemberImpl = member;
// The original owner should always be a method, because this method is only used to
// change the owner from a method to a property.
m_originalMember = accessor.MemberImpl as MethodBase;
Debug.Assert(m_originalMember != null);
// Populate all the caches -- we inherit this behavior from RTM
NameImpl = accessor.Name;
m_nameIsCached = true;
ClassImpl = accessor.ParameterType;
PositionImpl = accessor.Position;
AttrsImpl = accessor.Attributes;
// Strictly speeking, property's don't contain paramter tokens
// However we need this to make ca's work... oh well...
m_tkParamDef = MdToken.IsNullToken(accessor.MetadataToken) ? (int)MetadataTokenType.ParamDef : accessor.MetadataToken;
m_scope = accessor.m_scope;
}
private RuntimeParameterInfo(
Signature signature, MetadataImport scope, int tkParamDef,
int position, ParameterAttributes attributes, MemberInfo member)
{
Contract.Requires(member != null);
Debug.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport));
Debug.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef));
PositionImpl = position;
MemberImpl = member;
m_signature = signature;
m_tkParamDef = MdToken.IsNullToken(tkParamDef) ? (int)MetadataTokenType.ParamDef : tkParamDef;
m_scope = scope;
AttrsImpl = attributes;
ClassImpl = null;
NameImpl = null;
}
// ctor for no metadata MethodInfo in the DynamicMethod and RuntimeMethodInfo cases
internal RuntimeParameterInfo(MethodInfo owner, String name, Type parameterType, int position)
{
MemberImpl = owner;
NameImpl = name;
m_nameIsCached = true;
m_noMetadata = true;
ClassImpl = parameterType;
PositionImpl = position;
AttrsImpl = ParameterAttributes.None;
m_tkParamDef = (int)MetadataTokenType.ParamDef;
m_scope = MetadataImport.EmptyImport;
}
#endregion
#region Public Methods
public override Type ParameterType
{
get
{
// only instance of ParameterInfo has ClassImpl, all its subclasses don't
if (ClassImpl == null)
{
RuntimeType parameterType;
if (PositionImpl == -1)
parameterType = m_signature.ReturnType;
else
parameterType = m_signature.Arguments[PositionImpl];
Debug.Assert(parameterType != null);
// different thread could only write ClassImpl to the same value, so a race condition is not a problem here
ClassImpl = parameterType;
}
return ClassImpl;
}
}
public override String Name
{
get
{
if (!m_nameIsCached)
{
if (!MdToken.IsNullToken(m_tkParamDef))
{
string name;
name = m_scope.GetName(m_tkParamDef).ToString();
NameImpl = name;
}
// other threads could only write it to true, so a race condition is OK
// this field is volatile, so the write ordering is guaranteed
m_nameIsCached = true;
}
// name may be null
return NameImpl;
}
}
public override bool HasDefaultValue
{
get
{
if (m_noMetadata || m_noDefaultValue)
return false;
object defaultValue = GetDefaultValueInternal(false);
return (defaultValue != DBNull.Value);
}
}
public override Object DefaultValue { get { return GetDefaultValue(false); } }
public override Object RawDefaultValue { get { return GetDefaultValue(true); } }
private Object GetDefaultValue(bool raw)
{
// OLD COMMENT (Is this even true?)
// Cannot cache because default value could be non-agile user defined enumeration.
// OLD COMMENT ends
if (m_noMetadata)
return null;
// for dynamic method we pretend to have cached the value so we do not go to metadata
object defaultValue = GetDefaultValueInternal(raw);
if (defaultValue == DBNull.Value)
{
#region Handle case if no default value was found
if (IsOptional)
{
// If the argument is marked as optional then the default value is Missing.Value.
defaultValue = Type.Missing;
}
#endregion
}
return defaultValue;
}
// returns DBNull.Value if the parameter doesn't have a default value
private Object GetDefaultValueInternal(bool raw)
{
Debug.Assert(!m_noMetadata);
if (m_noDefaultValue)
return DBNull.Value;
object defaultValue = null;
// Why check the parameter type only for DateTime and only for the ctor arguments?
// No check on the parameter type is done for named args and for Decimal.
// We should move this after MdToken.IsNullToken(m_tkParamDef) and combine it
// with the other custom attribute logic. But will that be a breaking change?
// For a DateTime parameter on which both an md constant and a ca constant are set,
// which one should win?
if (ParameterType == typeof(DateTime))
{
if (raw)
{
CustomAttributeTypedArgument value =
CustomAttributeData.Filter(
CustomAttributeData.GetCustomAttributes(this), typeof(DateTimeConstantAttribute), 0);
if (value.ArgumentType != null)
return new DateTime((long)value.Value);
}
else
{
object[] dt = GetCustomAttributes(typeof(DateTimeConstantAttribute), false);
if (dt != null && dt.Length != 0)
return ((DateTimeConstantAttribute)dt[0]).Value;
}
}
#region Look for a default value in metadata
if (!MdToken.IsNullToken(m_tkParamDef))
{
// This will return DBNull.Value if no constant value is defined on m_tkParamDef in the metadata.
defaultValue = MdConstant.GetValue(m_scope, m_tkParamDef, ParameterType.GetTypeHandleInternal(), raw);
}
#endregion
if (defaultValue == DBNull.Value)
{
#region Look for a default value in the custom attributes
if (raw)
{
foreach (CustomAttributeData attr in CustomAttributeData.GetCustomAttributes(this))
{
Type attrType = attr.Constructor.DeclaringType;
if (attrType == typeof(DateTimeConstantAttribute))
{
defaultValue = DateTimeConstantAttribute.GetRawDateTimeConstant(attr);
}
else if (attrType == typeof(DecimalConstantAttribute))
{
defaultValue = DecimalConstantAttribute.GetRawDecimalConstant(attr);
}
else if (attrType.IsSubclassOf(s_CustomConstantAttributeType))
{
defaultValue = CustomConstantAttribute.GetRawConstant(attr);
}
}
}
else
{
Object[] CustomAttrs = GetCustomAttributes(s_CustomConstantAttributeType, false);
if (CustomAttrs.Length != 0)
{
defaultValue = ((CustomConstantAttribute)CustomAttrs[0]).Value;
}
else
{
CustomAttrs = GetCustomAttributes(s_DecimalConstantAttributeType, false);
if (CustomAttrs.Length != 0)
{
defaultValue = ((DecimalConstantAttribute)CustomAttrs[0]).Value;
}
}
}
#endregion
}
if (defaultValue == DBNull.Value)
m_noDefaultValue = true;
return defaultValue;
}
internal RuntimeModule GetRuntimeModule()
{
RuntimeMethodInfo method = Member as RuntimeMethodInfo;
RuntimeConstructorInfo constructor = Member as RuntimeConstructorInfo;
RuntimePropertyInfo property = Member as RuntimePropertyInfo;
if (method != null)
return method.GetRuntimeModule();
else if (constructor != null)
return constructor.GetRuntimeModule();
else if (property != null)
return property.GetRuntimeModule();
else
return null;
}
public override int MetadataToken
{
get
{
return m_tkParamDef;
}
}
public override Type[] GetRequiredCustomModifiers()
{
return m_signature.GetCustomModifiers(PositionImpl + 1, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return m_signature.GetCustomModifiers(PositionImpl + 1, false);
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
if (MdToken.IsNullToken(m_tkParamDef))
return Array.Empty<Object>();
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
if (MdToken.IsNullToken(m_tkParamDef))
return Array.Empty<Object>();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
if (MdToken.IsNullToken(m_tkParamDef))
return false;
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
}
}
| |
#region Copyright (C) 2005 Rob Blackwell & Active Web Solutions.
//
// L Sharp .NET, a powerful lisp-based scripting language for .NET.
// Copyright (C) 2005 Rob Blackwell & Active Web Solutions.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free
// Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
#endregion
using System;
using System.ComponentModel;
using System.Collections;
#if SYSTEM_DATA
using System.Data;
#endif
namespace LSharp
{
/// <summary>
/// A Cons is a compound object having two components, called the car
/// and the cdr, each of which can be any object. Lists are created
/// by setting the cdr to another cons. Trees are created by setting the car to
/// another cons.
/// </summary>
[TypeConverter("IronScheme.Editor.Controls.Design.LSharpConverter, xacc")]
[Editor("IronScheme.Editor.Controls.Design.LSharpUIEditor, xacc", typeof(System.Drawing.Design.UITypeEditor))]
public class Cons : ICollection, ICloneable
{
private Object car;
private Object cdr;
#if DEBUG
public string DebugInfo
{
get {return Printer.WriteToString(this);}
}
#endif
/// <summary>
/// Constructs a new List with one element, the car
/// </summary>
/// <param name="car"></param>
public Cons(Object car)
{
this.car = car;
this.cdr = null;
}
/// <summary>
/// Constructs a new List with cat at the head and cdr at the tail.
/// </summary>
/// <param name="car"></param>
/// <param name="cdr"></param>
public Cons(Object car, params object[] cdr)
{
this.car = car;
if (cdr != null)
{
if (cdr.Length == 1)
{
this.cdr = cdr[0];
}
else if (cdr.Length > 1)
{
object[] cdar = new object[cdr.Length - 1];
Array.Copy(cdr, 1, cdar, 0, cdar.Length);
this.cdr = new Cons(cdr[0], cdar);
}
}
}
/// <summary>
/// Returns an enumerator for enumerating all elements of the List
/// started by this cons.
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return (new ListEnumerator(this));
}
int ICollection.Count
{
get {return Length();}
}
bool ICollection.IsSynchronized
{
get {return false;}
}
object ICollection.SyncRoot
{
get {return this;}
}
void ICollection.CopyTo(Array arr, int index)
{
int i =0;
object o = this;
while (o != null)
{
if (i >= index)
{
arr.SetValue(((Cons)o).Car(), i);
}
i += 1;
o = ((Cons)o).Cdr();
}
}
/// <summary>
/// Returns the Car (First) of this cons
/// </summary>
/// <returns></returns>
public Object Car()
{
return this.car;
}
/// <summary>
/// Returns the Cdr (Rest) of this cons
/// </summary>
/// <returns></returns>
public Object Cdr()
{
return this.cdr;
}
/// <summary>
/// Returns the Car of the Car of this cons
/// </summary>
/// <returns></returns>
public Object Caar()
{
return ((Cons)this.Car()).Car();
}
/// <summary>
/// Returns the Car of the Cdr of this cons
/// </summary>
/// <returns></returns>
public Object Cadr()
{
return ((Cons)this.Cdr()).Car();
}
/// <summary>
/// Returns the Cdr of the Car of this cons
/// </summary>
/// <returns></returns>
public Object Cdar()
{
return ((Cons)this.Car()).Cdr();
}
/// <summary>
/// Returns the Cdr or the Cdr of this cons
/// </summary>
/// <returns></returns>
public Object Cddr()
{
return ((Cons)Cdr()).Cdr();
}
public Object Caaar()
{
return ((Cons)this.Caar()).Car();
}
public Object Caadr()
{
return ((Cons)this.Cdr()).Caar();
}
public Object Cadar()
{
return ((Cons)this.Car()).Cadr();
}
public Object Caddr()
{
return ((Cons)this.Cdr()).Cadr();
}
public Object Cdaar()
{
return ((Cons)this.Car()).Cdar();
}
public Object Cdadr()
{
return ((Cons)this.Cdr()).Cdar();
}
public Object Cddar()
{
return ((Cons)this.Car()).Cddr();
}
public Object Cdddr()
{
return ((Cons)this.Cdr()).Cddr();
}
public Object Rest()
{
return this.cdr;
}
public Object Nth(int n)
{
if (n == 0) return Car();
else return ((Cons)Cdr()).Nth(n -1);
}
public Object First()
{
return this.car;
}
public Object Second()
{
return (this.Nth(1));
}
public Object Third()
{
return (this.Nth(2));
}
public Cons Rplaca(Object obj)
{
this.car = obj;
return this;
}
public Cons Rplacd(Object obj)
{
this.cdr = obj;
return this;
}
public override int GetHashCode()
{
int h = 0;
foreach (object o in this)
{
h ^= o.GetHashCode();
}
return h;
}
public override bool Equals(object obj)
{
if (obj is Cons)
{
Cons that = (Cons)obj;
bool carsEqual = Primitives.Eql(this.Car(), that.Car());
bool cdrsEqual = Primitives.Eql(this.Cdr(), that.Cdr());
return carsEqual && cdrsEqual;
}
else
return false;
}
/// <summary>
/// Creates a list of characters from a string
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Cons FromString(string value)
{
Object cons = null;
for (int i = value.Length -1 ; i >= 0 ; i--)
{
cons = new Cons(value[i],cons);
}
return (Cons) cons;
}
#if SYSTEM_DATA
/// <summary>
/// Creates a list given a DataRow
/// </summary>
/// <param name="dataRow"></param>
/// <returns></returns>
public static Cons FromDataRow (DataRow dataRow)
{
object list = null;
foreach (object field in dataRow.ItemArray)
{
list = new Cons(field, list);
}
return (Cons)list;
}
/// <summary>
/// Creates a list given a DataTable
/// </summary>
/// <param name="dataTable"></param>
/// <returns></returns>
public static Cons FromDataTable (DataTable dataTable)
{
object list = null;
foreach (DataRow row in dataTable.Rows)
{
object subList = null;
foreach ( DataColumn column in dataTable.Columns)
{
subList = new Cons(row[column], subList);
}
list = new Cons(((Cons)subList).Reverse(), list);
}
return (Cons)list;
}
#endif
/// <summary>
/// Creates a list given a Hashtable
/// </summary>
/// <param name="hashtable"></param>
/// <returns></returns>
public static Cons FromList(IList list)
{
Object cons = null;
for (int i = list.Count -1 ; i >= 0 ; i--)
{
cons = new Cons(list[i],cons);
}
return (Cons) cons;
}
/// <summary>
/// Creates a list given a Hashtable
/// </summary>
/// <param name="hashtable"></param>
/// <returns></returns>
public static Cons FromDictionary(IDictionary hashtable)
{
object list = null;
foreach (object key in hashtable.Keys)
{
object value = hashtable[key];
list = new Cons(new Cons(key, new Cons(value)), list);
}
return (Cons)list;
}
/// <summary>
/// Creates a list from any ICollection
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
public static Cons FromICollection (ICollection collection)
{
object list = null;
foreach (object o in collection)
{
list = new Cons(o, list);
}
return ((Cons)list).Reverse(); //fix, the previous construct creates cons in prepend fashion
}
/// <summary>
/// Returns the length of the list
/// </summary>
/// <returns></returns>
public int Length()
{
int i=0;
object o = this;
if (car != null)
{
while (o != null)
{
i += 1;
o = ((Cons)o).Cdr();
}
}
return i;
}
/// <summary>
/// Returns the list expressed as an array of objects
/// </summary>
/// <returns></returns>
public object[] ToArray()
{
object[] objects = new object[this.Length()];
((ICollection)this).CopyTo(objects, 0);
return objects;
}
/// <summary>
/// Returns the list expressed as an array of objects
/// </summary>
/// <returns></returns>
public Array ToArray(Type type)
{
Array objects = Array.CreateInstance( type, Length());
((ICollection)this).CopyTo(objects, 0);
return objects;
}
/// <summary>
/// Returns the last item in a list
/// </summary>
/// <returns></returns>
public object Last()
{
object o = this;
while ((o is Cons) && (((Cons)o).Cdr() != null))
{
o = ((Cons)o).Cdr();
}
return o;
}
/// <summary>
/// Returns a new list with the items reversed
/// </summary>
/// <returns></returns>
public Cons Reverse ()
{
object list = null;
object o = this;
while ( o != null)
{
list = new Cons(((Cons) o).Car(),list);
o = ((Cons)o).Cdr();
}
return (Cons)list;
}
public Cons Copy()
{
return new Cons(this.Car(), this.Cdr());
}
/// <summary>
/// Returns a shallow copy of the list given as its argument
/// </summary>
/// <param name="args"></param>
/// <param name="environment"></param>
/// <returns></returns>
public Cons CopyList()
{
Cons result;
Cons dest;
object nextCons = this;
// Copy the first cons cell
dest = ((Cons)nextCons).Copy();
result = dest;
nextCons = ((Cons)nextCons).Cdr();
// Copy succesive cells
while (nextCons is Cons)
{
dest.Rplacd(((Cons)nextCons).Copy());
dest = (Cons)dest.Cdr();
nextCons = ((Cons)nextCons).Cdr();
}
return result;
}
object ICloneable.Clone()
{
return CopyList();
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
using System;
using System.Collections.Generic;
using Irony.Ast;
namespace Irony.Parsing
{
[Flags]
public enum StringOptions : short
{
None = 0,
IsChar = 0x01,
/// <summary>
/// Convert doubled start/end symbol to a single symbol; for ex. in SQL, '' -> '
/// </summary>
AllowsDoubledQuote = 0x02,
AllowsLineBreak = 0x04,
/// <summary>
/// Can include embedded expressions that should be evaluated on the fly; ex in Ruby: "hello #{name}"
/// </summary>
IsTemplate = 0x08,
NoEscapes = 0x10,
AllowsUEscapes = 0x20,
AllowsXEscapes = 0x40,
AllowsOctalEscapes = 0x80,
AllowsAllEscapes = AllowsUEscapes | AllowsXEscapes | AllowsOctalEscapes,
}
public class StringLiteral : CompoundTerminalBase
{
public enum StringFlagsInternal : short
{
HasEscapes = 0x100,
}
#region StringSubType
private class StringSubType
{
internal readonly StringOptions Flags;
internal readonly byte Index;
internal readonly string Start, End;
internal StringSubType(string start, string end, StringOptions flags, byte index)
{
this.Start = start;
this.End = end;
this.Flags = flags;
this.Index = index;
}
internal static int LongerStartFirst(StringSubType x, StringSubType y)
{
try
{
// In case any of them is null
if (x.Start.Length > y.Start.Length)
return -1;
}
catch
{ }
return 0;
}
}
private class StringSubTypeList : List<StringSubType>
{
internal void Add(string start, string end, StringOptions flags)
{
this.Add(new StringSubType(start, end, flags, (byte) this.Count));
}
}
#endregion StringSubType
#region constructors and initialization
public StringLiteral(string name) : base(name)
{
this.SetFlag(TermFlags.IsLiteral);
}
public StringLiteral(string name, string startEndSymbol, StringOptions options) : this(name)
{
this.subtypes.Add(startEndSymbol, startEndSymbol, options);
}
public StringLiteral(string name, string startEndSymbol) : this(name, startEndSymbol, StringOptions.None)
{
}
public StringLiteral(string name, string startEndSymbol, StringOptions options, Type astNodeType) : this(name, startEndSymbol, options)
{
this.AstConfig.NodeType = astNodeType;
}
public StringLiteral(string name, string startEndSymbol, StringOptions options, AstNodeCreator astNodeCreator) : this(name, startEndSymbol, options)
{
this.AstConfig.NodeCreator = astNodeCreator;
}
public void AddPrefix(string prefix, StringOptions flags)
{
this.AddPrefixFlag(prefix, (short) flags);
}
public void AddStartEnd(string startEndSymbol, StringOptions stringOptions)
{
this.AddStartEnd(startEndSymbol, startEndSymbol, stringOptions);
}
public void AddStartEnd(string startSymbol, string endSymbol, StringOptions stringOptions)
{
this.subtypes.Add(startSymbol, endSymbol, stringOptions);
}
#endregion constructors and initialization
#region Properties/Fields
private readonly StringSubTypeList subtypes = new StringSubTypeList();
/// <summary>
/// First chars of start-end symbols
/// </summary>
private string startSymbolsFirsts;
#endregion Properties/Fields
#region overrides: Init, GetFirsts, ReadBody, etc...
public override IList<string> GetFirsts()
{
var result = new StringList();
result.AddRange(Prefixes);
// We assume that prefix is always optional, so string can start with start-end symbol
foreach (char ch in this.startSymbolsFirsts)
{
result.Add(ch.ToString());
}
return result;
}
public override void Init(GrammarData grammarData)
{
base.Init(grammarData);
this.startSymbolsFirsts = string.Empty;
if (this.subtypes.Count == 0)
{
// "Error in string literal [{0}]: No start/end symbols specified."
grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrInvStrDef, this.Name);
return;
}
// Collect all start-end symbols in lists and create strings of first chars
// To detect duplicate start symbols
var allStartSymbols = new StringSet();
this.subtypes.Sort(StringSubType.LongerStartFirst);
var isTemplate = false;
foreach (StringSubType subType in this.subtypes)
{
if (allStartSymbols.Contains(subType.Start))
// "Duplicate start symbol {0} in string literal [{1}]."
grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrDupStartSymbolStr, subType.Start, this.Name);
allStartSymbols.Add(subType.Start);
this.startSymbolsFirsts += subType.Start[0].ToString();
isTemplate |= (subType.Flags & StringOptions.IsTemplate) != 0;
}
if (!this.CaseSensitivePrefixesSuffixes)
this.startSymbolsFirsts = this.startSymbolsFirsts.ToLower() + this.startSymbolsFirsts.ToUpper();
// Set multiline flag
foreach (StringSubType info in this.subtypes)
{
if ((info.Flags & StringOptions.AllowsLineBreak) != 0)
{
this.SetFlag(TermFlags.IsMultiline);
break;
}
}
// For templates only
if (isTemplate)
{
// Check that template settings object is provided
var templateSettings = this.AstConfig.Data as StringTemplateSettings;
if (templateSettings == null)
// "Error in string literal [{0}]: IsTemplate flag is set, but TemplateSettings is not provided."
grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplNoSettings, this.Name);
else if (templateSettings.ExpressionRoot == null)
// ""
grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplMissingExprRoot, this.Name);
else if (!Grammar.SnippetRoots.Contains(templateSettings.ExpressionRoot))
// ""
grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplExprNotRoot, this.Name);
}
// Create editor info
if (this.EditorInfo == null)
this.EditorInfo = new TokenEditorInfo(TokenType.String, TokenColor.String, TokenTriggers.None);
}
/// <summary>
/// Extract the string content from lexeme, adjusts the escaped and double-end symbols
/// </summary>
/// <param name="details"></param>
/// <returns></returns>
protected override bool ConvertValue(CompoundTokenDetails details)
{
string value = details.Body;
var escapeEnabled = !details.IsSet((short) StringOptions.NoEscapes);
// Fix all escapes
if (escapeEnabled && value.IndexOf(EscapeChar) >= 0)
{
details.Flags |= (int) StringFlagsInternal.HasEscapes;
var arr = value.Split(EscapeChar);
var ignoreNext = false;
// We skip the 0 element as it is not preceeded by "\"
for (int i = 1; i < arr.Length; i++)
{
if (ignoreNext)
{
ignoreNext = false;
continue;
}
string s = arr[i];
if (string.IsNullOrEmpty(s))
{
// It is "\\" - escaped escape symbol.
arr[i] = @"\";
ignoreNext = true;
continue;
}
// The char is being escaped is the first one; replace it with char in Escapes table
char first = s[0];
char newFirst;
if (Escapes.TryGetValue(first, out newFirst))
arr[i] = newFirst + s.Substring(1);
else
arr[i] = HandleSpecialEscape(arr[i], details);
}
value = string.Join(string.Empty, arr);
}
// Check for doubled end symbol
string endSymbol = details.EndSymbol;
if (details.IsSet((short) StringOptions.AllowsDoubledQuote) && value.IndexOf(endSymbol) >= 0)
value = value.Replace(endSymbol + endSymbol, endSymbol);
if (details.IsSet((short) StringOptions.IsChar))
{
if (value.Length != 1)
{
// "Invalid length of char literal - should be a single character.";
details.Error = Resources.ErrBadChar;
return false;
}
details.Value = value[0];
}
else
{
details.TypeCodes = new TypeCode[] { TypeCode.String };
details.Value = value;
}
return true;
}
/// <summary>
/// Should support: \Udddddddd, \udddd, \xdddd, \N{name}, \0, \ddd (octal),
/// </summary>
/// <param name="segment"></param>
/// <param name="details"></param>
/// <returns></returns>
protected virtual string HandleSpecialEscape(string segment, CompoundTokenDetails details)
{
if (string.IsNullOrEmpty(segment))
return string.Empty;
int len, p;
string digits;
char ch;
string result;
char first = segment[0];
switch (first)
{
case 'u':
case 'U':
if (details.IsSet((short) StringOptions.AllowsUEscapes))
{
len = (first == 'u' ? 4 : 8);
if (segment.Length < len + 1)
{
// "Invalid unicode escape ({0}), expected {1} hex digits."
details.Error = string.Format(Resources.ErrBadUnEscape, segment.Substring(len + 1), len);
return segment;
}
digits = segment.Substring(1, len);
ch = (char) Convert.ToUInt32(digits, 16);
result = ch + segment.Substring(len + 1);
return result;
}
break;
case 'x':
if (details.IsSet((short) StringOptions.AllowsXEscapes))
{
// x-escape allows variable number of digits, from one to 4; let's count them
// current position
p = 1;
while (p < 5 && p < segment.Length)
{
if (Strings.HexDigits.IndexOf(segment[p]) < 0)
break;
p++;
}
// p now point to char right after the last digit
if (p <= 1)
{
// @"Invalid \x escape, at least one digit expected.";
details.Error = Resources.ErrBadXEscape;
return segment;
}
digits = segment.Substring(1, p - 1);
ch = (char) Convert.ToUInt32(digits, 16);
result = ch + segment.Substring(p);
return result;
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
if (details.IsSet((short) StringOptions.AllowsOctalEscapes))
{
// Octal escape allows variable number of digits, from one to 3; let's count them
// Current position
p = 0;
while (p < 3 && p < segment.Length)
{
if (Strings.OctalDigits.IndexOf(segment[p]) < 0)
break;
p++;
}
// p now point to char right after the last digit
digits = segment.Substring(0, p);
ch = (char) Convert.ToUInt32(digits, 8);
result = ch + segment.Substring(p);
return result;
}
break;
}
// "Invalid escape sequence: \{0}"
details.Error = string.Format(Resources.ErrInvEscape, segment);
return segment;
}
protected override void InitDetails(ParsingContext context, CompoundTerminalBase.CompoundTokenDetails details)
{
base.InitDetails(context, details);
if (context.VsLineScanState.Value != 0)
{
// We are continuing partial string on the next line
details.Flags = context.VsLineScanState.TerminalFlags;
details.SubTypeIndex = context.VsLineScanState.TokenSubType;
var stringInfo = this.subtypes[context.VsLineScanState.TokenSubType];
details.StartSymbol = stringInfo.Start;
details.EndSymbol = stringInfo.End;
}
}
protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details)
{
if (!details.PartialContinues)
{
if (!ReadStartSymbol(source, details))
return false;
}
return CompleteReadBody(source, details);
}
protected override void ReadSuffix(ISourceStream source, CompoundTerminalBase.CompoundTokenDetails details)
{
base.ReadSuffix(source, details);
// "char" type can be identified by suffix (like VB where c suffix identifies char)
// in this case we have details.TypeCodes[0] == char and we need to set the IsChar flag
if (details.TypeCodes != null && details.TypeCodes[0] == TypeCode.Char)
details.Flags |= (int) StringOptions.IsChar;
else
// We may have IsChar flag set (from startEndSymbol, like in c# single quote identifies char)
// in this case set type code
if (details.IsSet((short) StringOptions.IsChar))
details.TypeCodes = new TypeCode[] { TypeCode.Char };
}
private bool CompleteReadBody(ISourceStream source, CompoundTokenDetails details)
{
var escapeEnabled = !details.IsSet((short) StringOptions.NoEscapes);
var start = source.PreviewPosition;
var endQuoteSymbol = details.EndSymbol;
// Doubled quote symbol
var endQuoteDoubled = endQuoteSymbol + endQuoteSymbol;
var lineBreakAllowed = details.IsSet((short) StringOptions.AllowsLineBreak);
// 1. Find the string end
// first get the position of the next line break; we are interested in it to detect malformed string,
// therefore do it only if linebreak is NOT allowed; if linebreak is allowed, set it to -1 (we don't care).
var nlPos = lineBreakAllowed ? -1 : source.Text.IndexOf('\n', source.PreviewPosition);
// Fix by ashmind for EOF right after opening symbol
while (true)
{
var endPos = source.Text.IndexOf(endQuoteSymbol, source.PreviewPosition);
// Check for partial token in line-scanning mode
if (endPos < 0 && details.PartialOk && lineBreakAllowed)
{
this.ProcessPartialBody(source, details);
return true;
}
// Check for malformed string: either EndSymbol not found, or LineBreak is found before EndSymbol
var malformed = endPos < 0 || nlPos >= 0 && nlPos < endPos;
if (malformed)
{
// Set source position for recovery: move to the next line if linebreak is not allowed.
if (nlPos > 0) endPos = nlPos;
if (endPos > 0) source.PreviewPosition = endPos + 1;
// "Mal-formed string literal - cannot find termination symbol.";
details.Error = Resources.ErrBadStrLiteral;
// We did find start symbol, so it is definitely string, only malformed
return true;
}
if (source.EOF())
return true;
// We found EndSymbol - check if it is escaped; if yes, skip it and continue search
if (escapeEnabled && this.IsEndQuoteEscaped(source.Text, endPos))
{
source.PreviewPosition = endPos + endQuoteSymbol.Length;
// Searching for end symbol
continue;
}
// Check if it is doubled end symbol
source.PreviewPosition = endPos;
if (details.IsSet((short) StringOptions.AllowsDoubledQuote) && source.MatchSymbol(endQuoteDoubled))
{
source.PreviewPosition = endPos + endQuoteDoubled.Length;
continue;
}
// Ok, this is normal endSymbol that terminates the string.
// Advance source position and get out from the loop
details.Body = source.Text.Substring(start, endPos - start);
source.PreviewPosition = endPos + endQuoteSymbol.Length;
// If we come here it means we're done - we found string end.
return true;
}
}
private bool IsEndQuoteEscaped(string text, int quotePosition)
{
var escaped = false;
var p = quotePosition - 1;
while (p > 0 && text[p] == this.EscapeChar)
{
escaped = !escaped;
p--;
}
return escaped;
}
private void ProcessPartialBody(ISourceStream source, CompoundTokenDetails details)
{
int from = source.PreviewPosition;
source.PreviewPosition = source.Text.Length;
details.Body = source.Text.Substring(from, source.PreviewPosition - from);
details.IsPartial = true;
}
private bool ReadStartSymbol(ISourceStream source, CompoundTokenDetails details)
{
if (this.startSymbolsFirsts.IndexOf(source.PreviewChar) < 0)
return false;
foreach (StringSubType subType in this.subtypes)
{
if (!source.MatchSymbol(subType.Start))
continue;
// We found start symbol
details.StartSymbol = subType.Start;
details.EndSymbol = subType.End;
details.Flags |= (short) subType.Flags;
details.SubTypeIndex = subType.Index;
source.PreviewPosition += subType.Start.Length;
return true;
}
return false;
}
#endregion overrides: Init, GetFirsts, ReadBody, etc...
}
/// <summary>
/// Container for settings of tempate string parser, to interpet strings having embedded values or expressions
/// like in Ruby:
/// "Hello, #{name}"
/// Default values match settings for Ruby strings
/// </summary>
public class StringTemplateSettings
{
public string EndTag = "}";
public NonTerminal ExpressionRoot;
public string StartTag = "#{";
}
}
| |
// 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.
//
// Idea got from and adapted to work in avalonia
// http://silverlight.codeplex.com/SourceControl/changeset/view/74775#Release/Silverlight4/Source/Controls.Layout.Toolkit/LayoutTransformer/LayoutTransformer.cs
//
using Avalonia.Controls.Primitives;
using Avalonia.Media;
using Avalonia.VisualTree;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reactive.Linq;
namespace Avalonia.Controls
{
public class LayoutTransformControl : ContentControl
{
public static readonly AvaloniaProperty<Transform> LayoutTransformProperty =
AvaloniaProperty.Register<LayoutTransformControl, Transform>(nameof(LayoutTransform));
static LayoutTransformControl()
{
LayoutTransformProperty.Changed
.AddClassHandler<LayoutTransformControl>(x => x.OnLayoutTransformChanged);
}
public Transform LayoutTransform
{
get { return GetValue(LayoutTransformProperty); }
set { SetValue(LayoutTransformProperty, value); }
}
public Control TransformRoot => _transformRoot ??
(_transformRoot = this.GetVisualChildren().OfType<Control>().FirstOrDefault());
/// <summary>
/// Provides the behavior for the "Arrange" pass of layout.
/// </summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
if (TransformRoot == null || LayoutTransform == null)
{
return base.ArrangeOverride(finalSize);
}
// Determine the largest available size after the transformation
Size finalSizeTransformed = ComputeLargestTransformedSize(finalSize);
if (IsSizeSmaller(finalSizeTransformed, TransformRoot.DesiredSize))
{
// Some elements do not like being given less space than they asked for (ex: TextBlock)
// Bump the working size up to do the right thing by them
finalSizeTransformed = TransformRoot.DesiredSize;
}
// Transform the working size to find its width/height
Rect transformedRect = new Rect(0, 0, finalSizeTransformed.Width, finalSizeTransformed.Height).TransformToAABB(_transformation);
// Create the Arrange rect to center the transformed content
Rect finalRect = new Rect(
-transformedRect.X + ((finalSize.Width - transformedRect.Width) / 2),
-transformedRect.Y + ((finalSize.Height - transformedRect.Height) / 2),
finalSizeTransformed.Width,
finalSizeTransformed.Height);
// Perform an Arrange on TransformRoot (containing Child)
Size arrangedsize;
TransformRoot.Arrange(finalRect);
arrangedsize = TransformRoot.Bounds.Size;
// This is the first opportunity under Silverlight to find out the Child's true DesiredSize
if (IsSizeSmaller(finalSizeTransformed, arrangedsize) && (Size.Empty == _childActualSize))
{
//// Unfortunately, all the work so far is invalid because the wrong DesiredSize was used
//// Make a note of the actual DesiredSize
//_childActualSize = arrangedsize;
//// Force a new measure/arrange pass
//InvalidateMeasure();
}
else
{
// Clear the "need to measure/arrange again" flag
_childActualSize = Size.Empty;
}
// Return result to perform the transformation
return finalSize;
}
/// <summary>
/// Provides the behavior for the "Measure" pass of layout.
/// </summary>
/// <param name="availableSize">The available size that this element can give to child elements.</param>
/// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns>
protected override Size MeasureOverride(Size availableSize)
{
if (TransformRoot == null || LayoutTransform == null)
{
return base.MeasureOverride(availableSize);
}
Size measureSize;
if (_childActualSize == Size.Empty)
{
// Determine the largest size after the transformation
measureSize = ComputeLargestTransformedSize(availableSize);
}
else
{
// Previous measure/arrange pass determined that Child.DesiredSize was larger than believed
measureSize = _childActualSize;
}
// Perform a measure on the TransformRoot (containing Child)
TransformRoot.Measure(measureSize);
var desiredSize = TransformRoot.DesiredSize;
// Transform DesiredSize to find its width/height
Rect transformedDesiredRect = new Rect(0, 0, desiredSize.Width, desiredSize.Height).TransformToAABB(_transformation);
Size transformedDesiredSize = new Size(transformedDesiredRect.Width, transformedDesiredRect.Height);
// Return result to allocate enough space for the transformation
return transformedDesiredSize;
}
/// <summary>
/// Builds the visual tree for the LayoutTransformerControl when a new
/// template is applied.
/// </summary>
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
base.OnTemplateApplied(e);
_matrixTransform = new MatrixTransform();
if (null != TransformRoot)
{
TransformRoot.RenderTransform = _matrixTransform;
TransformRoot.RenderTransformOrigin = new RelativePoint(0, 0, RelativeUnit.Absolute);
}
ApplyLayoutTransform();
}
/// <summary>
/// Acceptable difference between two doubles.
/// </summary>
private const double AcceptableDelta = 0.0001;
/// <summary>
/// Number of decimals to round the Matrix to.
/// </summary>
private const int DecimalsAfterRound = 4;
/// <summary>
/// Actual DesiredSize of Child element (the value it returned from its MeasureOverride method).
/// </summary>
private Size _childActualSize = Size.Empty;
/// <summary>
/// RenderTransform/MatrixTransform applied to TransformRoot.
/// </summary>
private MatrixTransform _matrixTransform;
/// <summary>
/// Transformation matrix corresponding to _matrixTransform.
/// </summary>
private Matrix _transformation;
private IDisposable _transformChangedEvent = null;
private Control _transformRoot;
/// <summary>
/// Returns true if Size a is smaller than Size b in either dimension.
/// </summary>
/// <param name="a">Second Size.</param>
/// <param name="b">First Size.</param>
/// <returns>True if Size a is smaller than Size b in either dimension.</returns>
private static bool IsSizeSmaller(Size a, Size b)
{
return (a.Width + AcceptableDelta < b.Width) || (a.Height + AcceptableDelta < b.Height);
}
/// <summary>
/// Rounds the non-offset elements of a Matrix to avoid issues due to floating point imprecision.
/// </summary>
/// <param name="matrix">Matrix to round.</param>
/// <param name="decimals">Number of decimal places to round to.</param>
/// <returns>Rounded Matrix.</returns>
private static Matrix RoundMatrix(Matrix matrix, int decimals)
{
return new Matrix(
Math.Round(matrix.M11, decimals),
Math.Round(matrix.M12, decimals),
Math.Round(matrix.M21, decimals),
Math.Round(matrix.M22, decimals),
matrix.M31,
matrix.M32);
}
/// <summary>
/// Applies the layout transform on the LayoutTransformerControl content.
/// </summary>
/// <remarks>
/// Only used in advanced scenarios (like animating the LayoutTransform).
/// Should be used to notify the LayoutTransformer control that some aspect
/// of its Transform property has changed.
/// </remarks>
private void ApplyLayoutTransform()
{
if (LayoutTransform == null) return;
// Get the transform matrix and apply it
_transformation = RoundMatrix(LayoutTransform.Value, DecimalsAfterRound);
if (null != _matrixTransform)
{
_matrixTransform.Matrix = _transformation;
}
// New transform means re-layout is necessary
InvalidateMeasure();
}
/// <summary>
/// Compute the largest usable size (greatest area) after applying the transformation to the specified bounds.
/// </summary>
/// <param name="arrangeBounds">Arrange bounds.</param>
/// <returns>Largest Size possible.</returns>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Closely corresponds to WPF's FrameworkElement.FindMaximalAreaLocalSpaceRect.")]
private Size ComputeLargestTransformedSize(Size arrangeBounds)
{
// Computed largest transformed size
Size computedSize = Size.Empty;
// Detect infinite bounds and constrain the scenario
bool infiniteWidth = double.IsInfinity(arrangeBounds.Width);
if (infiniteWidth)
{
// arrangeBounds.Width = arrangeBounds.Height;
arrangeBounds = arrangeBounds.WithWidth(arrangeBounds.Height);
}
bool infiniteHeight = double.IsInfinity(arrangeBounds.Height);
if (infiniteHeight)
{
//arrangeBounds.Height = arrangeBounds.Width;
arrangeBounds = arrangeBounds.WithHeight(arrangeBounds.Width);
}
// Capture the matrix parameters
double a = _transformation.M11;
double b = _transformation.M12;
double c = _transformation.M21;
double d = _transformation.M22;
// Compute maximum possible transformed width/height based on starting width/height
// These constraints define two lines in the positive x/y quadrant
double maxWidthFromWidth = Math.Abs(arrangeBounds.Width / a);
double maxHeightFromWidth = Math.Abs(arrangeBounds.Width / c);
double maxWidthFromHeight = Math.Abs(arrangeBounds.Height / b);
double maxHeightFromHeight = Math.Abs(arrangeBounds.Height / d);
// The transformed width/height that maximize the area under each segment is its midpoint
// At most one of the two midpoints will satisfy both constraints
double idealWidthFromWidth = maxWidthFromWidth / 2;
double idealHeightFromWidth = maxHeightFromWidth / 2;
double idealWidthFromHeight = maxWidthFromHeight / 2;
double idealHeightFromHeight = maxHeightFromHeight / 2;
// Compute slope of both constraint lines
double slopeFromWidth = -(maxHeightFromWidth / maxWidthFromWidth);
double slopeFromHeight = -(maxHeightFromHeight / maxWidthFromHeight);
if ((0 == arrangeBounds.Width) || (0 == arrangeBounds.Height))
{
// Check for empty bounds
computedSize = new Size(arrangeBounds.Width, arrangeBounds.Height);
}
else if (infiniteWidth && infiniteHeight)
{
// Check for completely unbound scenario
computedSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
}
else if (!_transformation.HasInverse)
{
// Check for singular matrix
computedSize = new Size(0, 0);
}
else if ((0 == b) || (0 == c))
{
// Check for 0/180 degree special cases
double maxHeight = (infiniteHeight ? double.PositiveInfinity : maxHeightFromHeight);
double maxWidth = (infiniteWidth ? double.PositiveInfinity : maxWidthFromWidth);
if ((0 == b) && (0 == c))
{
// No constraints
computedSize = new Size(maxWidth, maxHeight);
}
else if (0 == b)
{
// Constrained by width
double computedHeight = Math.Min(idealHeightFromWidth, maxHeight);
computedSize = new Size(
maxWidth - Math.Abs((c * computedHeight) / a),
computedHeight);
}
else if (0 == c)
{
// Constrained by height
double computedWidth = Math.Min(idealWidthFromHeight, maxWidth);
computedSize = new Size(
computedWidth,
maxHeight - Math.Abs((b * computedWidth) / d));
}
}
else if ((0 == a) || (0 == d))
{
// Check for 90/270 degree special cases
double maxWidth = (infiniteHeight ? double.PositiveInfinity : maxWidthFromHeight);
double maxHeight = (infiniteWidth ? double.PositiveInfinity : maxHeightFromWidth);
if ((0 == a) && (0 == d))
{
// No constraints
computedSize = new Size(maxWidth, maxHeight);
}
else if (0 == a)
{
// Constrained by width
double computedHeight = Math.Min(idealHeightFromHeight, maxHeight);
computedSize = new Size(
maxWidth - Math.Abs((d * computedHeight) / b),
computedHeight);
}
else if (0 == d)
{
// Constrained by height
double computedWidth = Math.Min(idealWidthFromWidth, maxWidth);
computedSize = new Size(
computedWidth,
maxHeight - Math.Abs((a * computedWidth) / c));
}
}
else if (idealHeightFromWidth <= ((slopeFromHeight * idealWidthFromWidth) + maxHeightFromHeight))
{
// Check the width midpoint for viability (by being below the height constraint line)
computedSize = new Size(idealWidthFromWidth, idealHeightFromWidth);
}
else if (idealHeightFromHeight <= ((slopeFromWidth * idealWidthFromHeight) + maxHeightFromWidth))
{
// Check the height midpoint for viability (by being below the width constraint line)
computedSize = new Size(idealWidthFromHeight, idealHeightFromHeight);
}
else
{
// Neither midpoint is viable; use the intersection of the two constraint lines instead
// Compute width by setting heights equal (m1*x+c1=m2*x+c2)
double computedWidth = (maxHeightFromHeight - maxHeightFromWidth) / (slopeFromWidth - slopeFromHeight);
// Compute height from width constraint line (y=m*x+c; using height would give same result)
computedSize = new Size(
computedWidth,
(slopeFromWidth * computedWidth) + maxHeightFromWidth);
}
// Return result
return computedSize;
}
private void OnLayoutTransformChanged(AvaloniaPropertyChangedEventArgs e)
{
var newTransform = e.NewValue as Transform;
if (_transformChangedEvent != null)
{
_transformChangedEvent.Dispose();
_transformChangedEvent = null;
}
if (newTransform != null)
{
_transformChangedEvent = Observable.FromEventPattern<EventHandler, EventArgs>(
v => newTransform.Changed += v, v => newTransform.Changed -= v)
.Subscribe(onNext: v => ApplyLayoutTransform());
}
ApplyLayoutTransform();
}
}
}
| |
//JSON RPC based on Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono
//http://jayrock.berlios.de/
using System;
using System.Collections;
using System.IO;
using System.Web;
using log4net;
using FluorineFx.Json.Services;
using FluorineFx.Util;
using FluorineFx.Messaging;
using FluorineFx.Messaging.Messages;
using FluorineFx.Messaging.Api;
using FluorineFx.Context;
namespace FluorineFx.Json.Rpc
{
sealed class JsonRpcExecutive : JsonRpcServiceFeature
{
private static readonly ILog log = LogManager.GetLogger(typeof(JsonRpcExecutive));
public JsonRpcExecutive(MessageBroker messageBroker)
: base(messageBroker)
{
}
protected override void ProcessRequest()
{
if (!StringUtils.CaselessEquals(Request.RequestType, "POST"))
{
throw new JsonRpcException(string.Format("HTTP {0} is not supported for RPC execution. Use HTTP POST only.", Request.RequestType));
}
// Sets the "Cache-Control" header value to "no-cache".
// NOTE: It does not send the common HTTP 1.0 request directive
// "Pragma" with the value "no-cache".
Response.Cache.SetCacheability(HttpCacheability.NoCache);
// Response will be plain text, though it would have been nice to
// be more specific, like text/json.
Response.ContentType = "text/plain";
// Dispatch
using (TextReader reader = GetRequestReader())
ProcessRequest(reader, Response.Output);
}
private TextReader GetRequestReader()
{
if (StringUtils.CaselessEquals(Request.ContentType, "application/x-www-form-urlencoded"))
{
string request = Request.Form.Count == 1 ? Request.Form[0] : Request.Form["JSON-RPC"];
return new StringReader(request);
}
else
{
return new StreamReader(Request.InputStream, Request.ContentEncoding);
}
}
private void ProcessRequest(TextReader input, TextWriter output)
{
ValidationUtils.ArgumentNotNull(input, "input");
ValidationUtils.ArgumentNotNull(output, "output");
IDictionary response;
try
{
IDictionary request = JavaScriptConvert.DeserializeObject(input) as IDictionary;
response = Invoke(request);
}
catch (MissingMethodException e)
{
response = CreateResponse(null, null, FromException(e));
}
catch (JsonReaderException e)
{
response = CreateResponse(null, null, FromException(e));
}
catch (JsonWriterException e)
{
response = CreateResponse(null, null, FromException(e));
}
string result = JavaScriptConvert.SerializeObject(response);
output.Write(result);
}
private IDictionary Invoke(IDictionary request)
{
ValidationUtils.ArgumentNotNull(request, "request");
object error = null;
object result = null;
ISession session = this.MessageBroker.SessionManager.GetHttpSession(HttpContext.Current);
FluorineContext.Current.SetSession(session);
//Context initialized, notify listeners.
if (session != null && session.IsNew)
session.NotifyCreated();
// Get the ID of the request.
object id = request["id"];
string credentials = request["credentials"] as string;
if (!StringUtils.IsNullOrEmpty(credentials))
{
try
{
CommandMessage commandMessage = new CommandMessage(CommandMessage.LoginOperation);
commandMessage.body = credentials;
IMessage message = this.MessageBroker.RouteMessage(commandMessage);
if (message is ErrorMessage)
{
error = FromException(message as ErrorMessage);
return CreateResponse(id, result, error);
}
}
catch (Exception ex)
{
error = FromException(ex);
return CreateResponse(id, result, error);
}
}
// If the ID is not there or was not set then this is a notification
// request from the client that does not expect any response. Right
// now, we don't support this.
bool isNotification = JavaScriptConvert.IsNull(id);
if (isNotification)
throw new NotSupportedException("Notification are not yet supported.");
log.Debug(string.Format("Received request with the ID {0}.", id.ToString()));
// Get the method name and arguments.
string methodName = StringUtils.MaskNullString((string)request["method"]);
if (methodName.Length == 0)
throw new JsonRpcException("No method name supplied for this request.");
if (methodName == "clearCredentials")
{
try
{
CommandMessage commandMessage = new CommandMessage(CommandMessage.LogoutOperation);
IMessage message = this.MessageBroker.RouteMessage(commandMessage);
if (message is ErrorMessage)
{
error = FromException(message as ErrorMessage);
return CreateResponse(id, result, error);
}
else
return CreateResponse(id, message.body, null);
}
catch (Exception ex)
{
error = FromException(ex);
return CreateResponse(id, result, error);
}
}
//Info("Invoking method {1} on service {0}.", ServiceName, methodName);
// Invoke the method on the service and handle errors.
try
{
RemotingMessage message = new RemotingMessage();
message.destination = this.Request.QueryString["destination"] as string;
message.source = this.Request.QueryString["source"] as string;
message.operation = methodName;
object argsObject = request["params"];
object[] args = (argsObject as JavaScriptArray).ToArray();
message.body = args;
IMessage response = this.MessageBroker.RouteMessage(message);
if (response is ErrorMessage)
error = FromException(response as ErrorMessage);
else
result = response.body;
/*
Method method = serviceClass.GetMethodByName(methodName);
object[] args;
string[] names = null;
object argsObject = request["params"];
IDictionary argByName = argsObject as IDictionary;
if (argByName != null)
{
names = new string[argByName.Count];
argByName.Keys.CopyTo(names, 0);
args = new object[argByName.Count];
argByName.Values.CopyTo(args, 0);
}
else
{
args = (argsObject as JavaScriptArray).ToArray();
}
result = method.Invoke(instance, names, args);
*/
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
throw;
}
// Setup and return the response object.
return CreateResponse(id, result, error);
}
private object FromException(Exception ex)
{
return JsonRpcError.FromException(ex, false);
}
private object FromException(ErrorMessage message)
{
return JsonRpcError.FromException(message, false);
}
private static IDictionary CreateResponse(object id, object result, object error)
{
JavaScriptObject response = new JavaScriptObject();
response["id"] = id;
if (error != null)
response["error"] = error;
else
response["result"] = result;
return response;
}
}
}
| |
using System;
using System.Threading.Tasks;
using Marten.Events;
using Marten.Storage;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
namespace Marten.Testing.Events
{
public class multi_tenancy_and_event_capture: IntegrationContext
{
public static TheoryData<TenancyStyle> TenancyStyles = new TheoryData<TenancyStyle>
{
{ TenancyStyle.Conjoined },
{ TenancyStyle.Single },
};
[Theory]
[MemberData(nameof(TenancyStyles))]
public void capture_events_for_a_tenant(TenancyStyle tenancyStyle)
{
InitStore(tenancyStyle);
Guid stream = Guid.NewGuid();
using (var session = theStore.OpenSession("Green"))
{
session.Events.Append(stream, new MembersJoined(), new MembersJoined());
session.SaveChanges();
}
using (var session = theStore.OpenSession("Green"))
{
var events = session.Events.FetchStream(stream);
foreach (var @event in events)
{
@event.TenantId.ShouldBe("Green");
}
}
}
[Theory]
[MemberData(nameof(TenancyStyles))]
public async Task capture_events_for_a_tenant_async(TenancyStyle tenancyStyle)
{
InitStore(tenancyStyle);
Guid stream = Guid.NewGuid();
using (var session = theStore.OpenSession("Green"))
{
session.Events.Append(stream, new MembersJoined(), new MembersJoined());
await session.SaveChangesAsync();
}
using (var session = theStore.OpenSession("Green"))
{
var events = await session.Events.FetchStreamAsync(stream);
foreach (var @event in events)
{
@event.TenantId.ShouldBe("Green");
}
}
}
[Theory]
[MemberData(nameof(TenancyStyles))]
public void capture_events_for_a_tenant_with_string_identifier(TenancyStyle tenancyStyle)
{
InitStore(tenancyStyle, StreamIdentity.AsString);
var stream = "SomeStream";
using (var session = theStore.OpenSession("Green"))
{
session.Events.Append(stream, new MembersJoined(), new MembersJoined());
session.SaveChanges();
}
using (var session = theStore.OpenSession("Green"))
{
var events = session.Events.FetchStream(stream);
foreach (var @event in events)
{
@event.TenantId.ShouldBe("Green");
}
}
}
[Theory]
[MemberData(nameof(TenancyStyles))]
public async Task capture_events_for_a_tenant_async_as_string_identifier(TenancyStyle tenancyStyle)
{
InitStore(tenancyStyle, StreamIdentity.AsString);
var stream = "SomeStream";
using (var session = theStore.OpenSession("Green"))
{
session.Events.Append(stream, new MembersJoined(), new MembersJoined());
await session.SaveChangesAsync();
}
using (var session = theStore.OpenSession("Green"))
{
var events = await session.Events.FetchStreamAsync(stream);
foreach (var @event in events)
{
@event.TenantId.ShouldBe("Green");
}
}
}
[Theory]
[MemberData(nameof(TenancyStyles))]
public void append_to_events_a_second_time_with_same_tenant_id(TenancyStyle tenancyStyle)
{
InitStore(tenancyStyle);
Guid stream = Guid.NewGuid();
using (var session = theStore.OpenSession("Green"))
{
session.Events.Append(stream, new MembersJoined(), new MembersJoined());
session.SaveChanges();
}
using (var session = theStore.OpenSession("Green"))
{
session.Events.Append(stream, new MembersJoined(), new MembersJoined());
session.SaveChanges();
}
using (var session = theStore.OpenSession("Green"))
{
var events = session.Events.FetchStream(stream);
foreach (var @event in events)
{
@event.TenantId.ShouldBe("Green");
}
}
}
[Fact]
public void try_to_append_across_tenants_with_tenancy_style_single()
{
InitStore(TenancyStyle.Single);
Guid stream = Guid.NewGuid();
using (var session = theStore.OpenSession("Green"))
{
session.Events.Append(stream, new MembersJoined(), new MembersJoined());
session.SaveChanges();
}
SpecificationExtensions.ShouldContain(Exception<Marten.Exceptions.MartenCommandException>.ShouldBeThrownBy(() =>
{
using (var session = theStore.OpenSession("Red"))
{
session.Events.Append(stream, new MembersJoined(), new MembersJoined());
session.SaveChanges();
}
}).Message, "The tenantid does not match the existing stream");
}
[Fact]
public void try_to_append_across_tenants_with_tenancy_style_conjoined()
{
InitStore(TenancyStyle.Conjoined);
Guid stream = Guid.NewGuid();
using (var session = theStore.OpenSession("Green"))
{
session.Events.Append(stream, new MembersJoined(), new MembersJoined());
session.SaveChanges();
}
Should.NotThrow(() =>
{
using (var session = theStore.OpenSession("Red"))
{
session.Events.Append(stream, new MembersJoined(), new MembersJoined());
session.SaveChanges();
}
});
}
private void InitStore(TenancyStyle tenancyStyle, StreamIdentity streamIdentity = StreamIdentity.AsGuid)
{
var databaseSchema = $"{GetType().Name}_{tenancyStyle.ToString().ToLower()}";
StoreOptions(_ =>
{
_.Events.DatabaseSchemaName = databaseSchema;
_.Events.TenancyStyle = tenancyStyle;
_.Events.StreamIdentity = streamIdentity;
_.Policies.AllDocumentsAreMultiTenanted();
});
}
public multi_tenancy_and_event_capture(DefaultStoreFixture fixture) : base(fixture)
{
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Aurora.Framework;
using log4net.Core;
namespace Aurora.Simulation.Base
{
public static class WebUtils
{
// this is the header field used to communicate the local request id
// used for performance and debugging
public const string OSHeaderRequestID = "opensim-request-id";
// number of milliseconds a call can take before it is considered
// a "long" call for warning & debugging purposes
public const int LongCallTime = 500;
private const int m_defaultTimeout = 20000;
public static Dictionary<string, object> ParseQueryString(string query)
{
Dictionary<string, object> result = new Dictionary<string, object>();
string[] terms = query.Split(new[] {'&'});
if (terms.Length == 0)
return result;
foreach (string t in terms)
{
string[] elems = t.Split(new[] {'='});
if (elems.Length == 0)
continue;
string name = HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = HttpUtility.UrlDecode(elems[1]);
if (name.EndsWith("[]"))
{
string cleanName = name.Substring(0, name.Length - 2);
if (result.ContainsKey(cleanName))
{
if (!(result[cleanName] is List<string>))
continue;
List<string> l = (List<string>) result[cleanName];
l.Add(value);
}
else
{
List<string> newList = new List<string> {value};
result[cleanName] = newList;
}
}
else
{
if (!result.ContainsKey(name))
result[name] = value;
}
}
return result;
}
public static string BuildQueryString(Dictionary<string, object> data)
{
string qstring = String.Empty;
foreach (KeyValuePair<string, object> kvp in data)
{
string part;
if (kvp.Value is List<string>)
{
List<string> l = (List<String>) kvp.Value;
foreach (string s in l)
{
part = HttpUtility.UrlEncode(kvp.Key) +
"[]=" + HttpUtility.UrlEncode(s);
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
else
{
if (kvp.Value.ToString() != String.Empty)
{
part = HttpUtility.UrlEncode(kvp.Key) +
"=" + HttpUtility.UrlEncode(kvp.Value.ToString());
}
else
{
part = HttpUtility.UrlEncode(kvp.Key);
}
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
return qstring;
}
public static string BuildXmlResponse(Dictionary<string, object> data)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
// Set the encoding declaration.
((XmlDeclaration) xmlnode).Encoding = "UTF-8";
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
BuildXmlData(rootElement, data);
return doc.InnerXml;
}
private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
{
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value == null)
continue;
if (parent.OwnerDocument != null)
{
XmlElement elem = parent.OwnerDocument.CreateElement("",
kvp.Key, "");
if (kvp.Value is Dictionary<string, object>)
{
XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
"type", "");
type.Value = "List";
elem.Attributes.Append(type);
BuildXmlData(elem, (Dictionary<string, object>) kvp.Value);
}
else if (kvp.Value is Dictionary<string, string>)
{
XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
"type", "");
type.Value = "List";
elem.Attributes.Append(type);
#if (!ISWIN)
Dictionary<string, object> value = new Dictionary<string, object>();
foreach (KeyValuePair<string, string> pair in ((Dictionary<string, string>) kvp.Value))
value.Add(pair.Key, pair.Value);
#else
Dictionary<string, object> value = ((Dictionary<string, string>) kvp.Value).ToDictionary<KeyValuePair<string, string>, string, object>(pair => pair.Key, pair => pair.Value);
#endif
BuildXmlData(elem, value);
}
else
{
elem.AppendChild(parent.OwnerDocument.CreateTextNode(
kvp.Value.ToString()));
}
parent.AppendChild(elem);
}
}
}
public static Dictionary<string, object> ParseXmlResponse(string data)
{
//MainConsole.Instance.DebugFormat("[XXX]: received xml string: {0}", data);
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
if (rootL.Count != 1)
return ret;
XmlNode rootNode = rootL[0];
ret = ParseElement(rootNode);
return ret;
}
private static Dictionary<string, object> ParseElement(XmlNode element)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlNodeList partL = element.ChildNodes;
foreach (XmlNode part in partL)
{
if (part.Attributes != null)
{
XmlNode type = part.Attributes.GetNamedItem("type");
if (type == null || type.Value != "List")
{
ret[part.Name] = part.InnerText;
}
else
{
ret[part.Name] = ParseElement(part);
}
}
}
return ret;
}
/// <summary>
/// POST URL-encoded form data to a web service that returns LLSD or
/// JSON data
/// </summary>
public static string PostToService(string url, OSDMap data)
{
return ServiceOSDRequest(url, data, "POST", m_defaultTimeout);
}
/// <summary>
/// GET JSON-encoded data to a web service that returns LLSD or
/// JSON data
/// </summary>
public static string GetFromService(string url)
{
return ServiceOSDRequest(url, null, "GET", m_defaultTimeout);
}
/// <summary>
/// PUT JSON-encoded data to a web service that returns LLSD or
/// JSON data
/// </summary>
public static string PutToService(string url, OSDMap data)
{
return ServiceOSDRequest(url, data, "PUT", m_defaultTimeout);
}
/// <summary>
/// Dictionary of end points
/// </summary>
private static Dictionary<string, object> m_endpointSerializer = new Dictionary<string, object>();
private static object EndPointLock(string url)
{
System.Uri uri = new System.Uri(url);
string endpoint = string.Format("{0}:{1}", uri.Host, uri.Port);
lock (m_endpointSerializer)
{
object eplock = null;
if (!m_endpointSerializer.TryGetValue(endpoint, out eplock))
{
eplock = new object();
m_endpointSerializer.Add(endpoint, eplock);
// m_log.WarnFormat("[WEB UTIL] add a new host to end point serializer {0}",endpoint);
}
return eplock;
}
}
public static string ServiceOSDRequest(string url, OSDMap data, string method, int timeout)
{
// MainConsole.Instance.DebugFormat("[WEB UTIL]: <{0}> start osd request for {1}, method {2}",reqnum,url,method);
//lock (EndPointLock(url))
{
string errorMessage = "unknown error";
int tickstart = Util.EnvironmentTickCount();
int tickdata = 0;
int tickserialize = 0;
byte[] buffer = data != null ? Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data, true)) : null;
HttpWebRequest request = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.Timeout = timeout;
request.KeepAlive = false;
request.MaximumAutomaticRedirections = 10;
request.ReadWriteTimeout = timeout / 4;
// If there is some input, write it into the request
if (buffer != null && buffer.Length > 0)
{
request.ContentType = "application/json";
request.ContentLength = buffer.Length; //Count bytes to send
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(buffer, 0, buffer.Length); //Send it
}
// capture how much time was spent writing, this may seem silly
// but with the number concurrent requests, this often blocks
tickdata = Util.EnvironmentTickCountSubtract(tickstart);
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
// capture how much time was spent writing, this may seem silly
// but with the number concurrent requests, this often blocks
tickserialize = Util.EnvironmentTickCountSubtract(tickstart) - tickdata;
string responseStr = responseStream.GetStreamString();
// MainConsole.Instance.DebugFormat("[WEB UTIL]: <{0}> response is <{1}>",reqnum,responseStr);
return responseStr;
}
}
}
catch (WebException we)
{
errorMessage = we.Message;
if (we.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse webResponse = (HttpWebResponse)we.Response;
if (webResponse.StatusCode == HttpStatusCode.BadRequest)
MainConsole.Instance.WarnFormat("[WebUtils]: bad request to {0}, data {1}", url,
data != null ? OSDParser.SerializeJsonString(data) : "");
else
MainConsole.Instance.WarnFormat("[WebUtils]: {0} to {1}, data {2}, response {3}", webResponse.StatusCode, url,
data != null ? OSDParser.SerializeJsonString(data) : "", webResponse.StatusDescription);
return "";
}
if (request != null)
request.Abort();
}
catch (Exception ex)
{
if (ex is System.UriFormatException)
errorMessage = ex.ToString() + " " + new System.Diagnostics.StackTrace().ToString();
else
errorMessage = ex.Message;
if (request != null)
request.Abort();
}
finally
{
if (MainConsole.Instance != null)
{
if (errorMessage == "unknown error")
{
// This just dumps a warning for any operation that takes more than 500 ms
int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
MainConsole.Instance.TraceFormat(
"[WebUtils]: osd request (URI:{0}, METHOD:{1}) took {2}ms overall, {3}ms writing, {4}ms deserializing",
url, method, tickdiff, tickdata, tickserialize);
if (tickdiff > 5000)
MainConsole.Instance.InfoFormat(
"[WebUtils]: osd request took too long (URI:{0}, METHOD:{1}) took {2}ms overall, {3}ms writing, {4}ms deserializing",
url, method, tickdiff, tickdata, tickserialize);
}
}
}
if (MainConsole.Instance != null)
MainConsole.Instance.WarnFormat("[WebUtils] osd request failed: {0} to {1}, data {2}", errorMessage, url,
data != null ? data.AsString() : "");
return "";
}
}
/// <summary>
/// Takes the value of an Accept header and returns the preferred types
/// ordered by q value (if it exists).
/// Example input: image/jpg;q=0.7, image/png;q=0.8, image/jp2
/// Exmaple output: ["jp2", "png", "jpg"]
/// NOTE: This doesn't handle the semantics of *'s...
/// </summary>
/// <param name = "accept"></param>
/// <returns></returns>
public static string[] GetPreferredImageTypes(string accept)
{
if (string.IsNullOrEmpty(accept))
return new string[0];
string[] types = accept.Split(new[] {','});
if (types.Length > 0)
{
List<string> list = new List<string>(types);
#if (!ISWIN)
list.RemoveAll(delegate(string s) { return !s.ToLower().StartsWith("image"); });
#else
list.RemoveAll(s => !s.ToLower().StartsWith("image"));
#endif
ArrayList tlist = new ArrayList(list);
tlist.Sort(new QBasedComparer());
string[] result = new string[tlist.Count];
for (int i = 0; i < tlist.Count; i++)
{
string mime = (string) tlist[i];
string[] parts = mime.Split(new[] {';'});
string[] pair = parts[0].Split(new[] {'/'});
if (pair.Length == 2)
result[i] = pair[1].ToLower();
else // oops, we don't know what this is...
result[i] = pair[0];
}
return result;
}
return new string[0];
}
/// <summary>
/// Extract the param from an uri.
/// </summary>
/// <param name = "uri">Something like this: /agent/uuid/ or /agent/uuid/handle/release/other</param>
/// <param name = "uuid">uuid on uuid field</param>
/// <param name="regionID"></param>
/// <param name = "action">optional action</param>
/// <param name = "other">Any other data</param>
public static bool GetParams(string uri, out UUID uuid, out UUID regionID, out string action, out string other)
{
uuid = UUID.Zero;
regionID = UUID.Zero;
action = "";
other = "";
uri = uri.Trim(new[] {'/'});
string[] parts = uri.Split('/');
if (parts.Length <= 1)
{
return false;
}
if (!UUID.TryParse(parts[1], out uuid))
return false;
if (parts.Length >= 3)
UUID.TryParse(parts[2], out regionID);
if (parts.Length >= 4)
action = parts[3];
if (parts.Length >= 5)
other = parts[4];
return true;
}
/// <summary>
/// Extract the param from an uri.
/// </summary>
/// <param name = "uri">Something like this: /agent/uuid/ or /agent/uuid/handle/release</param>
/// <param name = "uuid">uuid on uuid field</param>
/// <param name="regionID"></param>
/// <param name = "action">optional action</param>
public static bool GetParams(string uri, out UUID uuid, out UUID regionID, out string action)
{
uuid = UUID.Zero;
regionID = UUID.Zero;
action = "";
uri = uri.Trim(new[] {'/'});
string[] parts = uri.Split('/');
if (parts.Length <= 1)
{
return false;
}
if (!UUID.TryParse(parts[1], out uuid))
return false;
if (parts.Length >= 3)
UUID.TryParse(parts[2], out regionID);
if (parts.Length >= 4)
action = parts[3];
return true;
}
public static OSDMap GetOSDMap(string data)
{
return GetOSDMap(data, true);
}
public static OSDMap GetOSDMap(string data, bool doLogMessages)
{
if (data == "")
return null;
try
{
// We should pay attention to the content-type, but let's assume we know it's Json
OSD buffer = OSDParser.DeserializeJson(data);
if (buffer.Type == OSDType.Map)
{
OSDMap args = (OSDMap) buffer;
return args;
}
// uh?
if(doLogMessages)
MainConsole.Instance.Warn(("[WebUtils]: Got OSD of unexpected type " + buffer.Type.ToString()));
return null;
}
catch (Exception ex)
{
if (doLogMessages)
{
MainConsole.Instance.Warn("[WebUtils]: exception on parse of REST message " + ex);
MainConsole.Instance.Warn("[WebUtils]: bad data: " + data);
}
return null;
}
}
#region Nested type: QBasedComparer
public class QBasedComparer : IComparer
{
#region IComparer Members
public int Compare(Object x, Object y)
{
float qx = GetQ(x);
float qy = GetQ(y);
if (qx < qy)
return -1;
if (qx == qy)
return 0;
return 1;
}
#endregion
private float GetQ(Object o)
{
// Example: image/png;q=0.9
if (o is String)
{
string mime = (string) o;
string[] parts = mime.Split(new[] {';'});
if (parts.Length > 1)
{
string[] kvp = parts[1].Split(new[] {'='});
if (kvp.Length == 2 && kvp[0] == "q")
{
float qvalue = 1F;
float.TryParse(kvp[1], out qvalue);
return qvalue;
}
}
}
return 1F;
}
}
#endregion
}
/// <summary>
/// Class supporting the request side of an XML-RPC transaction.
/// </summary>
public sealed class ConfigurableKeepAliveXmlRpcRequest : XmlRpcRequest
{
private readonly XmlRpcResponseDeserializer _deserializer = new XmlRpcResponseDeserializer();
private readonly bool _disableKeepAlive = true;
private readonly Encoding _encoding = new ASCIIEncoding();
private readonly XmlRpcRequestSerializer _serializer = new XmlRpcRequestSerializer();
public string RequestResponse = String.Empty;
/// <summary>
/// Instantiate an <c>XmlRpcRequest</c> for a specified method and parameters.
/// </summary>
/// <param name = "methodName"><c>String</c> designating the <i>object.method</i> on the server the request
/// should be directed to.</param>
/// <param name = "parameters"><c>ArrayList</c> of XML-RPC type parameters to invoke the request with.</param>
/// <param name="disableKeepAlive"></param>
public ConfigurableKeepAliveXmlRpcRequest(String methodName, IList parameters, bool disableKeepAlive)
{
MethodName = methodName;
_params = parameters;
_disableKeepAlive = disableKeepAlive;
}
/// <summary>
/// Send the request to the server.
/// </summary>
/// <param name = "url"><c>String</c> The url of the XML-RPC server.</param>
/// <returns><c>XmlRpcResponse</c> The response generated.</returns>
public XmlRpcResponse Send(String url)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
if (request == null)
throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR,
XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " +
url);
request.Method = "POST";
request.ContentType = "text/xml";
request.AllowWriteStreamBuffering = true;
request.KeepAlive = !_disableKeepAlive;
Stream stream = request.GetRequestStream();
XmlTextWriter xml = new XmlTextWriter(stream, _encoding);
_serializer.Serialize(xml, this);
xml.Flush();
xml.Close();
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
StreamReader input = new StreamReader(response.GetResponseStream());
string inputXml = input.ReadToEnd();
XmlRpcResponse resp;
try
{
resp = (XmlRpcResponse) _deserializer.Deserialize(inputXml);
}
catch (Exception)
{
RequestResponse = inputXml;
throw;
}
input.Close();
response.Close();
return resp;
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using Moq;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Primitives.PopupPositioning;
using Avalonia.Controls.Templates;
using Avalonia.Layout;
using Avalonia.LogicalTree;
using Avalonia.Platform;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Avalonia.VisualTree;
using Xunit;
using Avalonia.Input;
using Avalonia.Rendering;
namespace Avalonia.Controls.UnitTests.Primitives
{
public class PopupTests
{
protected bool UsePopupHost;
[Fact]
public void Popup_Open_Without_Target_Should_Attach_Itself_Later()
{
using (CreateServices())
{
int openedEvent = 0;
var target = new Popup();
target.Opened += (s, a) => openedEvent++;
target.IsOpen = true;
var window = PreparedWindow(target);
window.Show();
Assert.Equal(1, openedEvent);
}
}
[Fact]
public void Popup_Without_TopLevel_Shouldnt_Call_Open()
{
int openedEvent = 0;
var target = new Popup();
target.Opened += (s, a) => openedEvent++;
target.IsOpen = true;
Assert.Equal(0, openedEvent);
}
[Fact]
public void Opening_Popup_Shouldnt_Throw_When_Not_In_Visual_Tree()
{
var target = new Popup();
target.IsOpen = true;
}
[Fact]
public void Opening_Popup_Shouldnt_Throw_When_In_Tree_Without_TopLevel()
{
Control c = new Control();
var target = new Popup();
((ISetLogicalParent)target).SetParent(c);
target.IsOpen = true;
}
[Fact]
public void Setting_Child_Should_Set_Child_Controls_LogicalParent()
{
var target = new Popup();
var child = new Control();
target.Child = child;
Assert.Equal(child.Parent, target);
Assert.Equal(((ILogical)child).LogicalParent, target);
}
[Fact]
public void Clearing_Child_Should_Clear_Child_Controls_Parent()
{
var target = new Popup();
var child = new Control();
target.Child = child;
target.Child = null;
Assert.Null(child.Parent);
Assert.Null(((ILogical)child).LogicalParent);
}
[Fact]
public void Child_Control_Should_Appear_In_LogicalChildren()
{
var target = new Popup();
var child = new Control();
target.Child = child;
Assert.Equal(new[] { child }, target.GetLogicalChildren());
}
[Fact]
public void Clearing_Child_Should_Remove_From_LogicalChildren()
{
var target = new Popup();
var child = new Control();
target.Child = child;
target.Child = null;
Assert.Equal(new ILogical[0], ((ILogical)target).LogicalChildren.ToList());
}
[Fact]
public void Setting_Child_Should_Fire_LogicalChildren_CollectionChanged()
{
var target = new Popup();
var child = new Control();
var called = false;
((ILogical)target).LogicalChildren.CollectionChanged += (s, e) =>
called = e.Action == NotifyCollectionChangedAction.Add;
target.Child = child;
Assert.True(called);
}
[Fact]
public void Clearing_Child_Should_Fire_LogicalChildren_CollectionChanged()
{
var target = new Popup();
var child = new Control();
var called = false;
target.Child = child;
((ILogical)target).LogicalChildren.CollectionChanged += (s, e) =>
called = e.Action == NotifyCollectionChangedAction.Remove;
target.Child = null;
Assert.True(called);
}
[Fact]
public void Changing_Child_Should_Fire_LogicalChildren_CollectionChanged()
{
var target = new Popup();
var child1 = new Control();
var child2 = new Control();
var called = false;
target.Child = child1;
((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true;
target.Child = child2;
Assert.True(called);
}
[Fact]
public void Setting_Child_Should_Not_Set_Childs_VisualParent()
{
var target = new Popup();
var child = new Control();
target.Child = child;
Assert.Null(((IVisual)child).VisualParent);
}
[Fact]
public void PopupRoot_Should_Initially_Be_Null()
{
using (CreateServices())
{
var target = new Popup();
Assert.Null(((Visual)target.Host));
}
}
[Fact]
public void PopupRoot_Should_Have_Popup_As_LogicalParent()
{
using (CreateServices())
{
var target = new Popup() {PlacementTarget = PreparedWindow()};
target.Open();
Assert.Equal(target, ((Visual)target.Host).Parent);
Assert.Equal(target, ((Visual)target.Host).GetLogicalParent());
}
}
[Fact]
public void PopupRoot_Should_Be_Detached_From_Logical_Tree_When_Popup_Is_Detached()
{
using (CreateServices())
{
var target = new Popup() {PlacementMode = PlacementMode.Pointer};
var root = PreparedWindow(target);
target.Open();
var popupRoot = (ILogical)((Visual)target.Host);
Assert.True(popupRoot.IsAttachedToLogicalTree);
root.Content = null;
Assert.False(((ILogical)target).IsAttachedToLogicalTree);
}
}
[Fact]
public void Popup_Open_Should_Raise_Single_Opened_Event()
{
using (CreateServices())
{
var window = PreparedWindow();
var target = new Popup() {PlacementMode = PlacementMode.Pointer};
window.Content = target;
int openedCount = 0;
target.Opened += (sender, args) =>
{
openedCount++;
};
target.Open();
Assert.Equal(1, openedCount);
}
}
[Fact]
public void Popup_Close_Should_Raise_Single_Closed_Event()
{
using (CreateServices())
{
var window = PreparedWindow();
var target = new Popup() {PlacementMode = PlacementMode.Pointer};
window.Content = target;
window.ApplyTemplate();
target.Open();
int closedCount = 0;
target.Closed += (sender, args) =>
{
closedCount++;
};
target.Close();
Assert.Equal(1, closedCount);
}
}
[Fact]
public void Popup_Close_On_Closed_Popup_Should_Not_Raise_Closed_Event()
{
using (CreateServices())
{
var window = PreparedWindow();
var target = new Popup() { PlacementMode = PlacementMode.Pointer };
window.Content = target;
window.ApplyTemplate();
int closedCount = 0;
target.Closed += (sender, args) =>
{
closedCount++;
};
target.Close();
target.Close();
target.Close();
target.Close();
Assert.Equal(0, closedCount);
}
}
[Fact]
public void Templated_Control_With_Popup_In_Template_Should_Set_TemplatedParent()
{
// Test uses OverlayPopupHost default template
using (CreateServices())
{
PopupContentControl target;
var root = PreparedWindow(target = new PopupContentControl
{
Content = new Border(),
Template = new FuncControlTemplate<PopupContentControl>(PopupContentControlTemplate),
});
root.Show();
target.ApplyTemplate();
var popup = (Popup)target.GetTemplateChildren().First(x => x.Name == "popup");
popup.Open();
var popupRoot = (Control)popup.Host;
popupRoot.Measure(Size.Infinity);
popupRoot.Arrange(new Rect(popupRoot.DesiredSize));
var children = popupRoot.GetVisualDescendants().ToList();
var types = children.Select(x => x.GetType().Name).ToList();
if (UsePopupHost)
{
Assert.Equal(
new[]
{
"VisualLayerManager",
"ContentPresenter",
"ContentPresenter",
"Border",
},
types);
}
else
{
Assert.Equal(
new[]
{
"Panel",
"Border",
"VisualLayerManager",
"ContentPresenter",
"ContentPresenter",
"Border",
},
types);
}
var templatedParents = children
.OfType<IControl>()
.Select(x => x.TemplatedParent).ToList();
if (UsePopupHost)
{
Assert.Equal(
new object[]
{
popupRoot,
popupRoot,
target,
null,
},
templatedParents);
}
else
{
Assert.Equal(
new object[]
{
popupRoot,
popupRoot,
popupRoot,
popupRoot,
target,
null,
},
templatedParents);
}
}
}
[Fact]
public void DataContextBeginUpdate_Should_Not_Be_Called_For_Controls_That_Dont_Inherit()
{
using (CreateServices())
{
TestControl child;
var popup = new Popup
{
Child = child = new TestControl(),
DataContext = "foo",
PlacementTarget = PreparedWindow()
};
var beginCalled = false;
child.DataContextBeginUpdate += (s, e) => beginCalled = true;
// Test for #1245. Here, the child's logical parent is the popup but it's not yet
// attached to a visual tree because the popup hasn't been opened.
Assert.Same(popup, ((ILogical)child).LogicalParent);
Assert.Same(popup, child.InheritanceParent);
Assert.Null(child.GetVisualRoot());
popup.Open();
// #1245 was caused by the fact that DataContextBeginUpdate was called on `target`
// when the PopupRoot was created, even though PopupRoot isn't the
// InheritanceParent of child.
Assert.False(beginCalled);
}
}
[Fact]
public void Popup_Host_Type_Should_Match_Platform_Preference()
{
using (CreateServices())
{
var target = new Popup() {PlacementTarget = PreparedWindow()};
target.Open();
if (UsePopupHost)
Assert.IsType<OverlayPopupHost>(target.Host);
else
Assert.IsType<PopupRoot>(target.Host);
}
}
[Fact]
public void OverlayDismissEventPassThrough_Should_Pass_Event_To_Window_Contents()
{
using (CreateServices())
{
var renderer = new Mock<IRenderer>();
var platform = AvaloniaLocator.Current.GetService<IWindowingPlatform>();
var windowImpl = Mock.Get(platform.CreateWindow());
windowImpl.Setup(x => x.CreateRenderer(It.IsAny<IRenderRoot>())).Returns(renderer.Object);
var window = new Window(windowImpl.Object);
window.ApplyTemplate();
var target = new Popup()
{
PlacementTarget = window ,
IsLightDismissEnabled = true,
OverlayDismissEventPassThrough = true,
};
var raised = 0;
var border = new Border();
window.Content = border;
renderer.Setup(x =>
x.HitTestFirst(new Point(10, 15), window, It.IsAny<Func<IVisual, bool>>()))
.Returns(border);
border.PointerPressed += (s, e) =>
{
Assert.Same(border, e.Source);
++raised;
};
target.Open();
Assert.True(target.IsOpen);
var e = CreatePointerPressedEventArgs(window, new Point(10, 15));
var overlay = LightDismissOverlayLayer.GetLightDismissOverlayLayer(window);
overlay.RaiseEvent(e);
Assert.Equal(1, raised);
Assert.False(target.IsOpen);
}
}
[Fact]
public void Focusable_Controls_In_Popup_Should_Get_Focus()
{
using (CreateServicesWithFocus())
{
var window = PreparedWindow();
var tb = new TextBox();
var b = new Button();
var p = new Popup
{
PlacementTarget = window,
Child = new StackPanel
{
Children =
{
tb,
b
}
}
};
((ISetLogicalParent)p).SetParent(p.PlacementTarget);
window.Show();
p.Open();
if(p.Host is OverlayPopupHost host)
{
//Need to measure/arrange for visual children to show up
//in OverlayPopupHost
host.Measure(Size.Infinity);
host.Arrange(new Rect(host.DesiredSize));
}
tb.Focus();
Assert.True(FocusManager.Instance?.Current == tb);
//Ensure focus remains in the popup
var nextFocus = KeyboardNavigationHandler.GetNext(FocusManager.Instance.Current, NavigationDirection.Next);
Assert.True(nextFocus == b);
p.Close();
}
}
[Fact]
public void Closing_Popup_Sets_Focus_On_PlacementTarget()
{
using (CreateServicesWithFocus())
{
var window = PreparedWindow();
var tb = new TextBox();
var p = new Popup
{
PlacementTarget = window,
Child = tb
};
((ISetLogicalParent)p).SetParent(p.PlacementTarget);
window.Show();
p.Open();
if (p.Host is OverlayPopupHost host)
{
//Need to measure/arrange for visual children to show up
//in OverlayPopupHost
host.Measure(Size.Infinity);
host.Arrange(new Rect(host.DesiredSize));
}
tb.Focus();
p.Close();
var focus = FocusManager.Instance?.Current;
Assert.True(focus == window);
}
}
[Fact]
public void Prog_Close_Popup_NoLightDismiss_Doesnt_Move_Focus_To_PlacementTarget()
{
using (CreateServicesWithFocus())
{
var window = PreparedWindow();
var windowTB = new TextBox();
window.Content = windowTB;
var popupTB = new TextBox();
var p = new Popup
{
PlacementTarget = window,
IsLightDismissEnabled = false,
Child = popupTB
};
((ISetLogicalParent)p).SetParent(p.PlacementTarget);
window.Show();
p.Open();
if (p.Host is OverlayPopupHost host)
{
//Need to measure/arrange for visual children to show up
//in OverlayPopupHost
host.Measure(Size.Infinity);
host.Arrange(new Rect(host.DesiredSize));
}
popupTB.Focus();
windowTB.Focus();
var focus = FocusManager.Instance?.Current;
Assert.True(focus == windowTB);
p.Close();
Assert.True(focus == windowTB);
}
}
[Fact]
public void Popup_Should_Follow_Placement_Target_On_Window_Move()
{
using (CreateServices())
{
var popup = new Popup { Width = 400, Height = 200 };
var window = PreparedWindow(popup);
popup.Open();
if (popup.Host is PopupRoot popupRoot)
{
// Moving the window must move the popup (screen coordinates have changed)
var raised = false;
popupRoot.PositionChanged += (_, args) =>
{
Assert.Equal(new PixelPoint(10, 10), args.Point);
raised = true;
};
window.Position = new PixelPoint(10, 10);
Assert.True(raised);
}
}
}
[Fact]
public void Popup_Should_Follow_Placement_Target_On_Window_Resize()
{
using (CreateServices())
{
var placementTarget = new Panel()
{
Width = 10,
Height = 10,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
var popup = new Popup() { PlacementTarget = placementTarget, Width = 10, Height = 10 };
((ISetLogicalParent)popup).SetParent(popup.PlacementTarget);
var window = PreparedWindow(placementTarget);
window.Show();
popup.Open();
// The target's initial placement is (395,295) which is a 10x10 panel centered in a 800x600 window
Assert.Equal(placementTarget.Bounds, new Rect(395D, 295D, 10, 10));
if (popup.Host is PopupRoot popupRoot)
{
// Resizing the window to 700x500 must move the popup to (345,255) as this is the new
// location of the placement target
var raised = false;
popupRoot.PositionChanged += (_, args) =>
{
Assert.Equal(new PixelPoint(345, 255), args.Point);
raised = true;
};
window.PlatformImpl?.Resize(new Size(700D, 500D), PlatformResizeReason.Unspecified);
Assert.True(raised);
}
}
}
[Fact]
public void Popup_Should_Follow_Popup_Root_Placement_Target()
{
// When the placement target of a popup is another popup (e.g. nested menu items), the child popup must
// follow the parent popup if it moves (due to root window movement or resize)
using (CreateServices())
{
// The child popup is placed directly over the parent popup for position testing
var parentPopup = new Popup() { Width = 10, Height = 10 };
var childPopup = new Popup() {
Width = 20,
Height = 20,
PlacementTarget = parentPopup,
PlacementMode = PlacementMode.AnchorAndGravity,
PlacementAnchor = PopupAnchor.TopLeft,
PlacementGravity = PopupGravity.BottomRight
};
((ISetLogicalParent)childPopup).SetParent(childPopup.PlacementTarget);
var window = PreparedWindow(parentPopup);
window.Show();
parentPopup.Open();
childPopup.Open();
if (childPopup.Host is PopupRoot popupRoot)
{
var raised = false;
popupRoot.PositionChanged += (_, args) =>
{
// The parent's initial placement is (395,295) which is a 10x10 popup centered
// in a 800x600 window. When the window is moved, the child's final placement is (405, 305)
// which is the parent's placement moved 10 pixels left and down.
Assert.Equal(new PixelPoint(405, 305), args.Point);
raised = true;
};
window.Position = new PixelPoint(10, 10);
Assert.True(raised);
}
}
}
private IDisposable CreateServices()
{
return UnitTestApplication.Start(TestServices.StyledWindow.With(windowingPlatform:
new MockWindowingPlatform(null,
x =>
{
if(UsePopupHost)
return null;
return MockWindowingPlatform.CreatePopupMock(x).Object;
})));
}
private IDisposable CreateServicesWithFocus()
{
return UnitTestApplication.Start(TestServices.StyledWindow.With(windowingPlatform:
new MockWindowingPlatform(null,
x =>
{
if (UsePopupHost)
return null;
return MockWindowingPlatform.CreatePopupMock(x).Object;
}),
focusManager: new FocusManager(),
keyboardDevice: () => new KeyboardDevice()));
}
private PointerPressedEventArgs CreatePointerPressedEventArgs(Window source, Point p)
{
var pointer = new Pointer(Pointer.GetNextFreeId(), PointerType.Mouse, true);
return new PointerPressedEventArgs(
source,
pointer,
source,
p,
0,
new PointerPointProperties(RawInputModifiers.None, PointerUpdateKind.LeftButtonPressed),
KeyModifiers.None);
}
private Window PreparedWindow(object content = null)
{
var w = new Window { Content = content };
w.ApplyTemplate();
return w;
}
private static IControl PopupContentControlTemplate(PopupContentControl control, INameScope scope)
{
return new Popup
{
Name = "popup",
PlacementTarget = control,
Child = new ContentPresenter
{
[~ContentPresenter.ContentProperty] = control[~ContentControl.ContentProperty],
}
}.RegisterInNameScope(scope);
}
private class PopupContentControl : ContentControl
{
}
private class TestControl : Decorator
{
public event EventHandler DataContextBeginUpdate;
public new IAvaloniaObject InheritanceParent => base.InheritanceParent;
protected override void OnDataContextBeginUpdate()
{
DataContextBeginUpdate?.Invoke(this, EventArgs.Empty);
base.OnDataContextBeginUpdate();
}
}
}
public class PopupTestsWithPopupRoot : PopupTests
{
public PopupTestsWithPopupRoot()
{
UsePopupHost = true;
}
}
}
| |
// 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.Diagnostics;
using System.Text;
namespace Microsoft.AspNetCore.HttpSys.Internal
{
// We don't use the cooked URL because http.sys unescapes all percent-encoded values. However,
// we also can't just use the raw Uri, since http.sys supports not only UTF-8, but also ANSI/DBCS and
// Unicode code points. System.Uri only supports UTF-8.
// The purpose of this class is to decode all UTF-8 percent encoded characters, with the
// exception of %2F ('/'), which is left encoded
internal static class RequestUriBuilder
{
private static readonly Encoding UTF8 = new UTF8Encoding(
encoderShouldEmitUTF8Identifier: false,
throwOnInvalidBytes: true);
public static string DecodeAndUnescapePath(Span<byte> rawUrlBytes)
{
Debug.Assert(rawUrlBytes.Length != 0, "Length of the URL cannot be zero.");
var rawPath = RawUrlHelper.GetPath(rawUrlBytes);
if (rawPath.Length == 0)
{
return "/";
}
// OPTIONS *
// RemoveDotSegments Asserts path always starts with a '/'
if (rawPath.Length == 1 && rawPath[0] == (byte)'*')
{
return "*";
}
var unescapedPath = Unescape(rawPath);
var length = PathNormalizer.RemoveDotSegments(unescapedPath);
return UTF8.GetString(unescapedPath.Slice(0, length));
}
/// <summary>
/// Unescape a given path string in place. The given path string may contain escaped char.
/// </summary>
/// <param name="rawPath">The raw path string to be unescaped</param>
/// <returns>The unescaped path string</returns>
private static Span<byte> Unescape(Span<byte> rawPath)
{
// the slot to read the input
var reader = 0;
// the slot to write the unescaped byte
var writer = 0;
// the end of the path
var end = rawPath.Length;
while (true)
{
if (reader == end)
{
break;
}
if (rawPath[reader] == '%')
{
var decodeReader = reader;
// If decoding process succeeds, the writer iterator will be moved
// to the next write-ready location. On the other hand if the scanned
// percent-encodings cannot be interpreted as sequence of UTF-8 octets,
// these bytes should be copied to output as is.
// The decodeReader iterator is always moved to the first byte not yet
// be scanned after the process. A failed decoding means the chars
// between the reader and decodeReader can be copied to output untouched.
if (!DecodeCore(ref decodeReader, ref writer, end, rawPath))
{
Copy(reader, decodeReader, ref writer, rawPath);
}
reader = decodeReader;
}
else
{
rawPath[writer++] = rawPath[reader++];
}
}
return rawPath.Slice(0, writer);
}
/// <summary>
/// Unescape the percent-encodings
/// </summary>
/// <param name="reader">The iterator point to the first % char</param>
/// <param name="writer">The place to write to</param>
/// <param name="end">The end of the buffer</param>
/// <param name="buffer">The byte array</param>
private static bool DecodeCore(ref int reader, ref int writer, int end, Span<byte> buffer)
{
// preserves the original head. if the percent-encodings cannot be interpreted as sequence of UTF-8 octets,
// bytes from this till the last scanned one will be copied to the memory pointed by writer.
var byte1 = UnescapePercentEncoding(ref reader, end, buffer);
if (!byte1.HasValue)
{
return false;
}
if (byte1 == 0)
{
throw new InvalidOperationException("The path contains null characters.");
}
if (byte1 <= 0x7F)
{
// first byte < U+007f, it is a single byte ASCII
buffer[writer++] = (byte)byte1;
return true;
}
int byte2 = 0, byte3 = 0, byte4 = 0;
// anticipate more bytes
var currentDecodeBits = 0;
var byteCount = 1;
var expectValueMin = 0;
if ((byte1 & 0xE0) == 0xC0)
{
// 110x xxxx, expect one more byte
currentDecodeBits = byte1.Value & 0x1F;
byteCount = 2;
expectValueMin = 0x80;
}
else if ((byte1 & 0xF0) == 0xE0)
{
// 1110 xxxx, expect two more bytes
currentDecodeBits = byte1.Value & 0x0F;
byteCount = 3;
expectValueMin = 0x800;
}
else if ((byte1 & 0xF8) == 0xF0)
{
// 1111 0xxx, expect three more bytes
currentDecodeBits = byte1.Value & 0x07;
byteCount = 4;
expectValueMin = 0x10000;
}
else
{
// invalid first byte
return false;
}
var remainingBytes = byteCount - 1;
while (remainingBytes > 0)
{
// read following three chars
if (reader == buffer.Length)
{
return false;
}
var nextItr = reader;
var nextByte = UnescapePercentEncoding(ref nextItr, end, buffer);
if (!nextByte.HasValue)
{
return false;
}
if ((nextByte & 0xC0) != 0x80)
{
// the follow up byte is not in form of 10xx xxxx
return false;
}
currentDecodeBits = (currentDecodeBits << 6) | (nextByte.Value & 0x3F);
remainingBytes--;
if (remainingBytes == 1 && currentDecodeBits >= 0x360 && currentDecodeBits <= 0x37F)
{
// this is going to end up in the range of 0xD800-0xDFFF UTF-16 surrogates that
// are not allowed in UTF-8;
return false;
}
if (remainingBytes == 2 && currentDecodeBits >= 0x110)
{
// this is going to be out of the upper Unicode bound 0x10FFFF.
return false;
}
reader = nextItr;
if (byteCount - remainingBytes == 2)
{
byte2 = nextByte.Value;
}
else if (byteCount - remainingBytes == 3)
{
byte3 = nextByte.Value;
}
else if (byteCount - remainingBytes == 4)
{
byte4 = nextByte.Value;
}
}
if (currentDecodeBits < expectValueMin)
{
// overlong encoding (e.g. using 2 bytes to encode something that only needed 1).
return false;
}
// all bytes are verified, write to the output
if (byteCount > 0)
{
buffer[writer++] = (byte)byte1;
}
if (byteCount > 1)
{
buffer[writer++] = (byte)byte2;
}
if (byteCount > 2)
{
buffer[writer++] = (byte)byte3;
}
if (byteCount > 3)
{
buffer[writer++] = (byte)byte4;
}
return true;
}
private static void Copy(int begin, int end, ref int writer, Span<byte> buffer)
{
while (begin != end)
{
buffer[writer++] = buffer[begin++];
}
}
/// <summary>
/// Read the percent-encoding and try unescape it.
///
/// The operation first peek at the character the <paramref name="scan"/>
/// iterator points at. If it is % the <paramref name="scan"/> is then
/// moved on to scan the following to characters. If the two following
/// characters are hexadecimal literals they will be unescaped and the
/// value will be returned.
///
/// If the first character is not % the <paramref name="scan"/> iterator
/// will be removed beyond the location of % and -1 will be returned.
///
/// If the following two characters can't be successfully unescaped the
/// <paramref name="scan"/> iterator will be move behind the % and -1
/// will be returned.
/// </summary>
/// <param name="scan">The value to read</param>
/// <param name="end">The end of the buffer</param>
/// <param name="buffer">The byte array</param>
/// <returns>The unescaped byte if success. Otherwise return -1.</returns>
private static int? UnescapePercentEncoding(ref int scan, int end, ReadOnlySpan<byte> buffer)
{
if (buffer[scan++] != '%')
{
return -1;
}
var probe = scan;
var value1 = ReadHex(ref probe, end, buffer);
if (!value1.HasValue)
{
return null;
}
var value2 = ReadHex(ref probe, end, buffer);
if (!value2.HasValue)
{
return null;
}
if (SkipUnescape(value1.Value, value2.Value))
{
return null;
}
scan = probe;
return (value1.Value << 4) + value2.Value;
}
/// <summary>
/// Read the next char and convert it into hexadecimal value.
///
/// The <paramref name="scan"/> iterator will be moved to the next
/// byte no matter no matter whether the operation successes.
/// </summary>
/// <param name="scan">The value to read</param>
/// <param name="end">The end of the buffer</param>
/// <param name="buffer">The byte array</param>
/// <returns>The hexadecimal value if successes, otherwise -1.</returns>
private static int? ReadHex(ref int scan, int end, ReadOnlySpan<byte> buffer)
{
if (scan == end)
{
return null;
}
var value = buffer[scan++];
var isHead = (((value >= '0') && (value <= '9')) ||
((value >= 'A') && (value <= 'F')) ||
((value >= 'a') && (value <= 'f')));
if (!isHead)
{
return null;
}
if (value <= '9')
{
return value - '0';
}
else if (value <= 'F')
{
return (value - 'A') + 10;
}
else // a - f
{
return (value - 'a') + 10;
}
}
private static bool SkipUnescape(int value1, int value2)
{
// skip %2F - '/'
if (value1 == 2 && value2 == 15)
{
return true;
}
return false;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using osu.Framework.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace osu.Framework.Testing
{
public class DynamicClassCompiler<T> : IDisposable
where T : IDynamicallyCompile
{
public event Action CompilationStarted;
public event Action<Type> CompilationFinished;
public event Action<Exception> CompilationFailed;
private readonly List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
private readonly HashSet<string> requiredFiles = new HashSet<string>();
private T target;
public void SetRecompilationTarget(T target)
{
if (this.target?.GetType().Name != target?.GetType().Name)
{
requiredFiles.Clear();
referenceBuilder.Reset();
}
this.target = target;
}
private ITypeReferenceBuilder referenceBuilder;
public void Start()
{
var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
#if NETCOREAPP
referenceBuilder = new RoslynTypeReferenceBuilder();
#else
referenceBuilder = new EmptyTypeReferenceBuilder();
#endif
Task.Run(async () =>
{
Logger.Log("Initialising dynamic compilation...");
var basePath = getSolutionPath(di);
if (!Directory.Exists(basePath))
return;
await referenceBuilder.Initialise(Directory.GetFiles(getSolutionPath(di), "*.sln").First());
foreach (var dir in Directory.GetDirectories(basePath))
{
// only watch directories which house a csproj. this avoids submodules and directories like .git which can contain many files.
if (!Directory.GetFiles(dir, "*.csproj").Any())
continue;
var fsw = new FileSystemWatcher(dir, @"*.cs")
{
EnableRaisingEvents = true,
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.FileName,
};
fsw.Renamed += onChange;
fsw.Changed += onChange;
fsw.Created += onChange;
watchers.Add(fsw);
}
Logger.Log("Dynamic compilation is now available.");
});
}
private static string getSolutionPath(DirectoryInfo d)
{
if (d == null)
return null;
return d.GetFiles().Any(f => f.Extension == ".sln") ? d.FullName : getSolutionPath(d.Parent);
}
private void onChange(object sender, FileSystemEventArgs args) => Task.Run(async () => await recompileAsync(target?.GetType(), args.FullPath));
private int currentVersion;
private bool isCompiling;
private async Task recompileAsync(Type targetType, string changedFile)
{
if (targetType == null || isCompiling)
return;
isCompiling = true;
try
{
while (!checkFileReady(changedFile))
Thread.Sleep(10);
Logger.Log($@"Recompiling {Path.GetFileName(targetType.Name)}...", LoggingTarget.Runtime, LogLevel.Important);
CompilationStarted?.Invoke();
var newRequiredFiles = await referenceBuilder.GetReferencedFiles(targetType, changedFile);
foreach (var f in newRequiredFiles)
requiredFiles.Add(f);
var requiredAssemblies = await referenceBuilder.GetReferencedAssemblies(targetType, changedFile);
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
// ReSharper disable once RedundantExplicitArrayCreation this doesn't compile when the array is empty
var parseOptions = new CSharpParseOptions(preprocessorSymbols: new string[]
{
#if DEBUG
"DEBUG",
#endif
#if TRACE
"TRACE",
#endif
#if RELEASE
"RELEASE",
#endif
}, languageVersion: LanguageVersion.Latest);
var references = requiredAssemblies.Where(a => !string.IsNullOrEmpty(a))
.Select(a => MetadataReference.CreateFromFile(a));
// ensure we don't duplicate the dynamic suffix.
string assemblyNamespace = targetType.Assembly.GetName().Name?.Replace(".Dynamic", "");
string assemblyVersion = $"{++currentVersion}.0.*";
string dynamicNamespace = $"{assemblyNamespace}.Dynamic";
var compilation = CSharpCompilation.Create(
dynamicNamespace,
requiredFiles.Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), parseOptions, file))
// Compile the assembly with a new version so that it replaces the existing one
.Append(CSharpSyntaxTree.ParseText($"using System.Reflection; [assembly: AssemblyVersion(\"{assemblyVersion}\")]", parseOptions)),
references,
options
);
using (var ms = new MemoryStream())
{
var compilationResult = compilation.Emit(ms);
if (compilationResult.Success)
{
ms.Seek(0, SeekOrigin.Begin);
CompilationFinished?.Invoke(
Assembly.Load(ms.ToArray()).GetModules()[0].GetTypes().LastOrDefault(t => t.FullName == targetType.FullName)
);
}
else
{
var exceptions = new List<Exception>();
foreach (var diagnostic in compilationResult.Diagnostics)
{
if (diagnostic.Severity < DiagnosticSeverity.Error)
continue;
exceptions.Add(new InvalidOperationException(diagnostic.ToString()));
}
throw new AggregateException(exceptions.ToArray());
}
}
}
catch (Exception ex)
{
CompilationFailed?.Invoke(ex);
}
finally
{
isCompiling = false;
}
}
/// <summary>
/// Check whether a file has finished being written to.
/// </summary>
private static bool checkFileReady(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
return inputStream.Length > 0;
}
catch (Exception)
{
return false;
}
}
#region IDisposable Support
private bool isDisposed;
protected virtual void Dispose(bool disposing)
{
if (!isDisposed)
{
isDisposed = true;
watchers.ForEach(w => w.Dispose());
}
}
~DynamicClassCompiler()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Azure.Management.RecoveryServices.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.RecoveryServices
{
public partial class RecoveryServicesManagementClient : ServiceClient<RecoveryServicesManagementClient>, IRecoveryServicesManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private string _resourceNamespace;
public string ResourceNamespace
{
get { return this._resourceNamespace; }
set { this._resourceNamespace = value; }
}
private IReplicationUsagesOperations _replicationUsages;
/// <summary>
/// Definition of vault usage operations for the Recovery Services
/// extension.
/// </summary>
public virtual IReplicationUsagesOperations ReplicationUsages
{
get { return this._replicationUsages; }
}
private IResourceGroupsOperations _resourceGroup;
/// <summary>
/// Definition of cloud service operations for the Recovery services
/// extension.
/// </summary>
public virtual IResourceGroupsOperations ResourceGroup
{
get { return this._resourceGroup; }
}
private IVaultExtendedInfoOperations _vaultExtendedInfo;
/// <summary>
/// Definition of vault extended info operations for the Recovery
/// Services extension.
/// </summary>
public virtual IVaultExtendedInfoOperations VaultExtendedInfo
{
get { return this._vaultExtendedInfo; }
}
private IVaultOperations _vaults;
/// <summary>
/// Definition of vault operations for the Recovery Services extension.
/// </summary>
public virtual IVaultOperations Vaults
{
get { return this._vaults; }
}
private IVaultUsageOperations _vaultUsage;
/// <summary>
/// Definition of vault operations for the Recovery Services extension.
/// </summary>
public virtual IVaultUsageOperations VaultUsage
{
get { return this._vaultUsage; }
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesManagementClient
/// class.
/// </summary>
public RecoveryServicesManagementClient()
: base()
{
this._replicationUsages = new ReplicationUsagesOperations(this);
this._resourceGroup = new ResourceGroupsOperations(this);
this._vaultExtendedInfo = new VaultExtendedInfoOperations(this);
this._vaults = new VaultOperations(this);
this._vaultUsage = new VaultUsageOperations(this);
this._apiVersion = "2015-01-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesManagementClient
/// class.
/// </summary>
/// <param name='resourceNamespace'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public RecoveryServicesManagementClient(string resourceNamespace, SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (resourceNamespace == null)
{
throw new ArgumentNullException("resourceNamespace");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._resourceNamespace = resourceNamespace;
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesManagementClient
/// class.
/// </summary>
/// <param name='resourceNamespace'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public RecoveryServicesManagementClient(string resourceNamespace, SubscriptionCloudCredentials credentials)
: this()
{
if (resourceNamespace == null)
{
throw new ArgumentNullException("resourceNamespace");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._resourceNamespace = resourceNamespace;
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesManagementClient
/// class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public RecoveryServicesManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._replicationUsages = new ReplicationUsagesOperations(this);
this._resourceGroup = new ResourceGroupsOperations(this);
this._vaultExtendedInfo = new VaultExtendedInfoOperations(this);
this._vaults = new VaultOperations(this);
this._vaultUsage = new VaultUsageOperations(this);
this._apiVersion = "2015-01-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesManagementClient
/// class.
/// </summary>
/// <param name='resourceNamespace'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public RecoveryServicesManagementClient(string resourceNamespace, SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (resourceNamespace == null)
{
throw new ArgumentNullException("resourceNamespace");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._resourceNamespace = resourceNamespace;
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the RecoveryServicesManagementClient
/// class.
/// </summary>
/// <param name='resourceNamespace'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public RecoveryServicesManagementClient(string resourceNamespace, SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (resourceNamespace == null)
{
throw new ArgumentNullException("resourceNamespace");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._resourceNamespace = resourceNamespace;
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// RecoveryServicesManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of RecoveryServicesManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<RecoveryServicesManagementClient> client)
{
base.Clone(client);
if (client is RecoveryServicesManagementClient)
{
RecoveryServicesManagementClient clonedClient = ((RecoveryServicesManagementClient)client);
clonedClient._resourceNamespace = this._resourceNamespace;
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of
/// thespecified operation. After calling an asynchronous operation,
/// you can call Get Operation Status to determine whether the
/// operation has succeeded, failed, or is still in progress. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
/// for more information)
/// </summary>
/// <param name='requestId'>
/// Required. The request ID for the request you wish to track. The
/// request ID is returned in the x-ms-request-id response header for
/// every request.
/// </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 also includes error
/// information regarding the failure.
/// </returns>
public async Task<RecoveryServicesOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
{
// Validate
if (requestId == null)
{
throw new ArgumentNullException("requestId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("requestId", requestId);
TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId);
}
url = url + "/operations/";
url = url + Uri.EscapeDataString(requestId);
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RecoveryServicesOperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RecoveryServicesOperationStatusResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
JToken recoveryServicesOperationStatusResponseValue = responseDoc["RecoveryServicesOperationStatusResponse"];
if (recoveryServicesOperationStatusResponseValue != null && recoveryServicesOperationStatusResponseValue.Type != JTokenType.Null)
{
RecoveryServicesOperationStatusResponse recoveryServicesOperationStatusResponseInstance = new RecoveryServicesOperationStatusResponse();
JToken idValue = recoveryServicesOperationStatusResponseValue["ID"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
recoveryServicesOperationStatusResponseInstance.Id = idInstance;
}
JToken statusValue = recoveryServicesOperationStatusResponseValue["Status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
RecoveryServicesOperationStatus statusInstance = ((RecoveryServicesOperationStatus)Enum.Parse(typeof(RecoveryServicesOperationStatus), ((string)statusValue), true));
recoveryServicesOperationStatusResponseInstance.Status = statusInstance;
}
JToken httpStatusCodeValue = recoveryServicesOperationStatusResponseValue["HttpStatusCode"];
if (httpStatusCodeValue != null && httpStatusCodeValue.Type != JTokenType.Null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), ((string)httpStatusCodeValue), true));
recoveryServicesOperationStatusResponseInstance.HttpStatusCode = httpStatusCodeInstance;
}
JToken errorValue = recoveryServicesOperationStatusResponseValue["Error"];
if (errorValue != null && errorValue.Type != JTokenType.Null)
{
RecoveryServicesOperationStatusResponse.ErrorDetails errorInstance = new RecoveryServicesOperationStatusResponse.ErrorDetails();
recoveryServicesOperationStatusResponseInstance.Error = errorInstance;
JToken codeValue = errorValue["Code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = errorValue["Message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
}
}
}
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();
}
}
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: ErrorDetailPage.cs 776 2011-01-12 21:09:24Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
#endregion
/// <summary>
/// Renders an HTML page displaying details about an error from the
/// error log.
/// </summary>
internal sealed class ErrorDetailPage : ErrorPageBase
{
private ErrorLogEntry _errorEntry;
protected override void OnLoad(EventArgs e)
{
//
// Retrieve the ID of the error to display and read it from
// the store.
//
string errorId = this.Request.QueryString["id"] ?? string.Empty;
if (errorId.Length == 0)
return;
_errorEntry = this.ErrorLog.GetError(errorId);
//
// Perhaps the error has been deleted from the store? Whatever
// the reason, bail out silently.
//
if (_errorEntry == null)
{
Response.Status = HttpStatus.NotFound.ToString();
return;
}
//
// Setup the title of the page.
//
this.PageTitle = string.Format("Error: {0} [{1}]", _errorEntry.Error.Type, _errorEntry.Id);
base.OnLoad(e);
}
protected override void RenderContents(HtmlTextWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
if (_errorEntry != null)
RenderError(writer);
else
RenderNoError(writer);
}
private static void RenderNoError(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
writer.RenderBeginTag(HtmlTextWriterTag.P);
writer.Write("Error not found in log.");
writer.RenderEndTag(); // </p>
writer.WriteLine();
}
private void RenderError(HtmlTextWriter writer)
{
Debug.Assert(writer != null);
Error error = _errorEntry.Error;
//
// Write out the page title containing error type and message.
//
writer.AddAttribute(HtmlTextWriterAttribute.Id, "PageTitle");
writer.RenderBeginTag(HtmlTextWriterTag.H1);
HtmlEncode(error.Message, writer);
writer.RenderEndTag(); // </h1>
writer.WriteLine();
SpeedBar.Render(writer,
SpeedBar.Home.Format(BasePageName),
SpeedBar.Help,
SpeedBar.About.Format(BasePageName));
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTitle");
writer.RenderBeginTag(HtmlTextWriterTag.P);
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorType");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
HtmlEncode(error.Type, writer);
writer.RenderEndTag(); // </span>
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTypeMessageSeparator");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.Write(": ");
writer.RenderEndTag(); // </span>
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorMessage");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
HtmlEncode(error.Message, writer);
writer.RenderEndTag(); // </span>
writer.RenderEndTag(); // </p>
writer.WriteLine();
//
// Do we have details, like the stack trace? If so, then write
// them out in a pre-formatted (pre) element.
// NOTE: There is an assumption here that detail will always
// contain a stack trace. If it doesn't then pre-formatting
// might not be the right thing to do here.
//
if (error.Detail.Length != 0)
{
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorDetail");
writer.RenderBeginTag(HtmlTextWriterTag.Pre);
writer.Flush();
MarkupStackTrace(error.Detail, writer.InnerWriter);
writer.RenderEndTag(); // </pre>
writer.WriteLine();
}
//
// Write out the error log time. This will be in the local
// time zone of the server. Would be a good idea to indicate
// it here for the user.
//
writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorLogTime");
writer.RenderBeginTag(HtmlTextWriterTag.P);
HtmlEncode(string.Format("Logged on {0} at {1}",
error.Time.ToLongDateString(),
error.Time.ToLongTimeString()), writer);
writer.RenderEndTag(); // </p>
writer.WriteLine();
//
// Render alternate links.
//
writer.RenderBeginTag(HtmlTextWriterTag.P);
writer.Write("See also:");
writer.RenderEndTag(); // </p>
writer.WriteLine();
writer.RenderBeginTag(HtmlTextWriterTag.Ul);
//
// Do we have an HTML formatted message from ASP.NET? If yes
// then write out a link to it instead of embedding it
// with the rest of the content since it is an entire HTML
// document in itself.
//
if (error.WebHostHtmlMessage.Length != 0)
{
writer.RenderBeginTag(HtmlTextWriterTag.Li);
string htmlUrl = this.BasePageName + "/html?id=" + HttpUtility.UrlEncode(_errorEntry.Id);
writer.AddAttribute(HtmlTextWriterAttribute.Href, htmlUrl);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("Original ASP.NET error page");
writer.RenderEndTag(); // </a>
writer.RenderEndTag(); // </li>
}
//
// Add a link to the source XML and JSON data.
//
writer.RenderBeginTag(HtmlTextWriterTag.Li);
writer.Write("Raw/Source data in ");
writer.AddAttribute(HtmlTextWriterAttribute.Href, "xml" + Request.Url.Query);
writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate);
writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/xml");
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("XML");
writer.RenderEndTag(); // </a>
writer.Write(" or in ");
writer.AddAttribute(HtmlTextWriterAttribute.Href, "json" + Request.Url.Query);
writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate);
writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/json");
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("JSON");
writer.RenderEndTag(); // </a>
writer.RenderEndTag(); // </li>
//
// End of alternate links.
//
writer.RenderEndTag(); // </ul>
//
// If this error has context, then write it out.
// ServerVariables are good enough for most purposes, so
// we only write those out at this time.
//
RenderCollection(writer, error.ServerVariables,
"ServerVariables", "Server Variables");
base.RenderContents(writer);
}
private void RenderCollection(HtmlTextWriter writer,
NameValueCollection collection, string id, string title)
{
Debug.Assert(writer != null);
Debug.AssertStringNotEmpty(id);
Debug.AssertStringNotEmpty(title);
//
// If the collection isn't there or it's empty, then bail out.
//
if (collection == null || collection.Count == 0)
return;
//
// Surround the entire section with a <div> element.
//
writer.AddAttribute(HtmlTextWriterAttribute.Id, id);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
//
// Write out the table caption.
//
writer.AddAttribute(HtmlTextWriterAttribute.Class, "table-caption");
writer.RenderBeginTag(HtmlTextWriterTag.P);
this.HtmlEncode(title, writer);
writer.RenderEndTag(); // </p>
writer.WriteLine();
//
// Some values can be large and add scroll bars to the page
// as well as ruin some formatting. So we encapsulate the
// table into a scrollable view that is controlled via the
// style sheet.
//
writer.AddAttribute(HtmlTextWriterAttribute.Class, "scroll-view");
writer.RenderBeginTag(HtmlTextWriterTag.Div);
//
// Create a table to display the name/value pairs of the
// collection in 2 columns.
//
Table table = new Table();
table.CellSpacing = 0;
//
// Create the header row and columns.
//
TableRow headRow = new TableRow();
TableHeaderCell headCell;
headCell = new TableHeaderCell();
headCell.Wrap = false;
headCell.Text = "Name";
headCell.CssClass = "name-col";
headRow.Cells.Add(headCell);
headCell = new TableHeaderCell();
headCell.Wrap = false;
headCell.Text = "Value";
headCell.CssClass = "value-col";
headRow.Cells.Add(headCell);
table.Rows.Add(headRow);
//
// Create a row for each entry in the collection.
//
string[] keys = collection.AllKeys;
Array.Sort(keys, StringComparer.InvariantCulture);
for (int keyIndex = 0; keyIndex < keys.Length; keyIndex++)
{
string key = keys[keyIndex];
TableRow bodyRow = new TableRow();
bodyRow.CssClass = keyIndex % 2 == 0 ? "even-row" : "odd-row";
TableCell cell;
//
// Create the key column.
//
cell = new TableCell();
cell.Text = HtmlEncode(key);
cell.CssClass = "key-col";
bodyRow.Cells.Add(cell);
//
// Create the value column.
//
cell = new TableCell();
cell.Text = HtmlEncode(collection[key]);
cell.CssClass = "value-col";
bodyRow.Cells.Add(cell);
table.Rows.Add(bodyRow);
}
//
// Write out the table and close container tags.
//
table.RenderControl(writer);
writer.RenderEndTag(); // </div>
writer.WriteLine();
writer.RenderEndTag(); // </div>
writer.WriteLine();
}
private static readonly Regex _reStackTrace = new Regex(@"
^
\s*
\w+ \s+
(?<type> .+ ) \.
(?<method> .+? )
(?<params> \( (?<params> .*? ) \) )
( \s+
\w+ \s+
(?<file> [a-z] \: .+? )
\: \w+ \s+
(?<line> [0-9]+ ) \p{P}? )?
\s*
$",
RegexOptions.IgnoreCase
| RegexOptions.Multiline
| RegexOptions.ExplicitCapture
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled);
private void MarkupStackTrace(string text, TextWriter writer)
{
Debug.Assert(text != null);
Debug.Assert(writer != null);
int anchor = 0;
foreach (Match match in _reStackTrace.Matches(text))
{
HtmlEncode(text.Substring(anchor, match.Index - anchor), writer);
MarkupStackFrame(text, match, writer);
anchor = match.Index + match.Length;
}
HtmlEncode(text.Substring(anchor), writer);
}
private void MarkupStackFrame(string text, Match match, TextWriter writer)
{
Debug.Assert(text != null);
Debug.Assert(match != null);
Debug.Assert(writer != null);
int anchor = match.Index;
GroupCollection groups = match.Groups;
//
// Type + Method
//
Group type = groups["type"];
HtmlEncode(text.Substring(anchor, type.Index - anchor), writer);
anchor = type.Index;
writer.Write("<span class='st-frame'>");
anchor = StackFrameSpan(text, anchor, "st-type", type, writer);
anchor = StackFrameSpan(text, anchor, "st-method", groups["method"], writer);
//
// Parameters
//
Group parameters = groups["params"];
HtmlEncode(text.Substring(anchor, parameters.Index - anchor), writer);
writer.Write("<span class='st-params'>(");
int position = 0;
foreach (string parameter in parameters.Captures[0].Value.Split(','))
{
int spaceIndex = parameter.LastIndexOf(' ');
if (spaceIndex <= 0)
{
Span(writer, "st-param", parameter.Trim());
}
else
{
if (position++ > 0)
writer.Write(", ");
string argType = parameter.Substring(0, spaceIndex).Trim();
Span(writer, "st-param-type", argType);
writer.Write(' ');
string argName = parameter.Substring(spaceIndex + 1).Trim();
Span(writer, "st-param-name", argName);
}
}
writer.Write(")</span>");
anchor = parameters.Index + parameters.Length;
//
// File + Line
//
anchor = StackFrameSpan(text, anchor, "st-file", groups["file"], writer);
anchor = StackFrameSpan(text, anchor, "st-line", groups["line"], writer);
writer.Write("</span>");
//
// Epilogue
//
int end = match.Index + match.Length;
HtmlEncode(text.Substring(anchor, end - anchor), writer);
}
private int StackFrameSpan(string text, int anchor, string klass, Group group, TextWriter writer)
{
Debug.Assert(text != null);
Debug.Assert(group != null);
Debug.Assert(writer != null);
return group.Success
? StackFrameSpan(text, anchor, klass, group.Value, group.Index, group.Length, writer)
: anchor;
}
private int StackFrameSpan(string text, int anchor, string klass, string value, int index, int length, TextWriter writer)
{
Debug.Assert(text != null);
Debug.Assert(writer != null);
HtmlEncode(text.Substring(anchor, index - anchor), writer);
Span(writer, klass, value);
return index + length;
}
private void Span(TextWriter writer, string klass, string value)
{
Debug.Assert(writer != null);
writer.Write("<span class='");
writer.Write(klass);
writer.Write("'>");
HtmlEncode(value, writer);
writer.Write("</span>");
}
private string HtmlEncode(string text)
{
return Server.HtmlEncode(text);
}
private void HtmlEncode(string text, TextWriter writer)
{
Debug.Assert(writer != null);
Server.HtmlEncode(text, writer);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable stack.
/// </summary>
/// <typeparam name="T">The type of element stored by the stack.</typeparam>
[DebuggerDisplay("IsEmpty = {IsEmpty}; Top = {_head}")]
[DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableStack<T> : IImmutableStack<T>
{
/// <summary>
/// The singleton empty stack.
/// </summary>
/// <remarks>
/// Additional instances representing the empty stack may exist on deserialized stacks.
/// </remarks>
private static readonly ImmutableStack<T> s_EmptyField = new ImmutableStack<T>();
/// <summary>
/// The element on the top of the stack.
/// </summary>
private readonly T _head;
/// <summary>
/// A stack that contains the rest of the elements (under the top element).
/// </summary>
private readonly ImmutableStack<T> _tail;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableStack{T}"/> class
/// that acts as the empty stack.
/// </summary>
private ImmutableStack()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableStack{T}"/> class.
/// </summary>
/// <param name="head">The head element on the stack.</param>
/// <param name="tail">The rest of the elements on the stack.</param>
private ImmutableStack(T head, ImmutableStack<T> tail)
{
Debug.Assert(tail != null);
_head = head;
_tail = tail;
}
/// <summary>
/// Gets the empty stack, upon which all stacks are built.
/// </summary>
public static ImmutableStack<T> Empty
{
get
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty);
Contract.Assume(s_EmptyField.IsEmpty);
return s_EmptyField;
}
}
/// <summary>
/// Gets the empty stack, upon which all stacks are built.
/// </summary>
public ImmutableStack<T> Clear()
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty);
Contract.Assume(s_EmptyField.IsEmpty);
return Empty;
}
/// <summary>
/// Gets an empty stack.
/// </summary>
IImmutableStack<T> IImmutableStack<T>.Clear()
{
return this.Clear();
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return _tail == null; }
}
/// <summary>
/// Gets the element on the top of the stack.
/// </summary>
/// <returns>
/// The element on the top of the stack.
/// </returns>
/// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception>
[Pure]
public T Peek()
{
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
return _head;
}
/// <summary>
/// Pushes an element onto a stack and returns the new stack.
/// </summary>
/// <param name="value">The element to push onto the stack.</param>
/// <returns>The new stack.</returns>
[Pure]
public ImmutableStack<T> Push(T value)
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(!Contract.Result<ImmutableStack<T>>().IsEmpty);
return new ImmutableStack<T>(value, this);
}
/// <summary>
/// Pushes an element onto a stack and returns the new stack.
/// </summary>
/// <param name="value">The element to push onto the stack.</param>
/// <returns>The new stack.</returns>
[Pure]
IImmutableStack<T> IImmutableStack<T>.Push(T value)
{
return this.Push(value);
}
/// <summary>
/// Returns a stack that lacks the top element on this stack.
/// </summary>
/// <returns>A stack; never <c>null</c></returns>
/// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception>
[Pure]
public ImmutableStack<T> Pop()
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
return _tail;
}
/// <summary>
/// Pops the top element off the stack.
/// </summary>
/// <param name="value">The value that was removed from the stack.</param>
/// <returns>
/// A stack; never <c>null</c>
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")]
[Pure]
public ImmutableStack<T> Pop(out T value)
{
value = this.Peek();
return this.Pop();
}
/// <summary>
/// Returns a stack that lacks the top element on this stack.
/// </summary>
/// <returns>A stack; never <c>null</c></returns>
/// <exception cref="InvalidOperationException">Thrown when the stack is empty.</exception>
[Pure]
IImmutableStack<T> IImmutableStack<T>.Pop()
{
return this.Pop();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An <see cref="Enumerator"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.IsEmpty ?
Enumerable.Empty<T>().GetEnumerator() :
new EnumeratorObject(this);
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator IEnumerable.GetEnumerator()
{
return new EnumeratorObject(this);
}
/// <summary>
/// Reverses the order of a stack.
/// </summary>
/// <returns>The reversed stack.</returns>
[Pure]
internal ImmutableStack<T> Reverse()
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty == this.IsEmpty);
var r = this.Clear();
for (ImmutableStack<T> f = this; !f.IsEmpty; f = f.Pop())
{
r = r.Push(f.Peek());
}
return r;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="Propagator.Evaluator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Mapping.Update.Internal
{
using System.Collections.Generic;
using System.Data.Common.CommandTrees;
using System.Data.Common.Utils;
using System.Data.Entity;
using System.Data.Metadata.Edm;
using System.Diagnostics;
using System.Globalization;
internal partial class Propagator
{
/// <summary>
/// Helper class supporting the evaluation of highly constrained expressions of the following
/// form:
///
/// P := P AND P | P OR P | NOT P | V is of type | V eq V | V
/// V := P
/// V := Property(V) | Constant | CASE WHEN P THEN V ... ELSE V | Row | new Instance | Null
///
/// The evaluator supports SQL style ternary logic for unknown results (bool? is used, where
/// null --> unknown, true --> TRUE and false --> FALSE
/// </summary>
/// <remarks>
/// Assumptions:
///
/// - The node and the row passed in must be type compatible.
///
/// Any var refs in the node must have the same type as the input row. This is a natural
/// requirement given the usage of this method in the propagator, since each propagator handler
/// produces rows of the correct type for its parent. Keep in mind that every var ref in a CQT is
/// bound specifically to the direct child.
///
/// - Equality comparisons are CLR culture invariant. Practically, this introduces the following
/// differences from SQL comparisons:
///
/// - String comparisons are not collation sensitive
/// - The constants we compare come from a fixed repertoire of scalar types implementing IComparable
///
///
/// For the purposes of update mapping view evaluation, these assumptions are safe because we
/// only support mapping of non-null constants to fields (these constants are non-null discriminators)
/// and key comparisons (where the key values are replicated across a reference).
/// </remarks>
private class Evaluator : UpdateExpressionVisitor<PropagatorResult>
{
#region Constructors
/// <summary>
/// Constructs an evaluator for evaluating expressions for the given row.
/// </summary>
/// <param name="row">Row to match</param>
/// <param name="parent">Propagator context</param>
private Evaluator(PropagatorResult row, Propagator parent)
{
EntityUtil.CheckArgumentNull(row, "row");
EntityUtil.CheckArgumentNull(parent, "parent");
m_row = row;
m_parent = parent;
}
#endregion
#region Fields
private PropagatorResult m_row;
private Propagator m_parent;
private static readonly string s_visitorName = typeof(Evaluator).FullName;
#endregion
#region Properties
override protected string VisitorName
{
get { return s_visitorName; }
}
#endregion
#region Methods
/// <summary>
/// Utility method filtering out a set of rows given a predicate.
/// </summary>
/// <param name="predicate">Match criteria.</param>
/// <param name="rows">Input rows.</param>
/// <param name="parent">Propagator context</param>
/// <returns>Input rows matching criteria.</returns>
internal static IEnumerable<PropagatorResult> Filter(DbExpression predicate, IEnumerable<PropagatorResult> rows, Propagator parent)
{
foreach (PropagatorResult row in rows)
{
if (EvaluatePredicate(predicate, row, parent))
{
yield return row;
}
}
}
/// <summary>
/// Utility method determining whether a row matches a predicate.
/// </summary>
/// <remarks>
/// See Walker class for an explanation of this coding pattern.
/// </remarks>
/// <param name="predicate">Match criteria.</param>
/// <param name="row">Input row.</param>
/// <param name="parent">Propagator context</param>
/// <returns><c>true</c> if the row matches the criteria; <c>false</c> otherwise</returns>
internal static bool EvaluatePredicate(DbExpression predicate, PropagatorResult row, Propagator parent)
{
Evaluator evaluator = new Evaluator(row, parent);
PropagatorResult expressionResult = predicate.Accept(evaluator);
bool? result = ConvertResultToBool(expressionResult);
// unknown --> false at base of predicate
return result ?? false;
}
/// <summary>
/// Evaluates scalar node.
/// </summary>
/// <param name="node">Sub-query returning a scalar value.</param>
/// <param name="row">Row to evaluate.</param>
/// <param name="parent">Propagator context.</param>
/// <returns>Scalar result.</returns>
static internal PropagatorResult Evaluate(DbExpression node, PropagatorResult row, Propagator parent)
{
DbExpressionVisitor<PropagatorResult> evaluator = new Evaluator(row, parent);
return node.Accept(evaluator);
}
/// <summary>
/// Given an expression, converts to a (nullable) bool. Only boolean constant and null are
/// supported.
/// </summary>
/// <param name="result">Result to convert</param>
/// <returns>true if true constant; false if false constant; null is null constant</returns>
private static bool? ConvertResultToBool(PropagatorResult result)
{
Debug.Assert(null != result && result.IsSimple, "Must be a simple Boolean result");
if (result.IsNull)
{
return null;
}
else
{
// rely on cast exception to identify invalid cases (CQT validation should already take care of this)
return (bool)result.GetSimpleValue();
}
}
/// <summary>
/// Converts a (nullable) bool to an expression.
/// </summary>
/// <param name="booleanValue">Result</param>
/// <param name="inputs">Inputs contributing to the result</param>
/// <returns>DbExpression</returns>
private static PropagatorResult ConvertBoolToResult(bool? booleanValue, params PropagatorResult[] inputs)
{
object result;
if (booleanValue.HasValue)
{
result = booleanValue.Value; ;
}
else
{
result = null;
}
PropagatorFlags flags = PropagateUnknownAndPreserveFlags(null, inputs);
return PropagatorResult.CreateSimpleValue(flags, result);
}
#region DbExpressionVisitor implementation
/// <summary>
/// Determines whether the argument being evaluated has a given type (declared in the IsOfOnly predicate).
/// </summary>
/// <param name="predicate">IsOfOnly predicate.</param>
/// <returns>True if the row being evaluated is of the requested type; false otherwise.</returns>
public override PropagatorResult Visit(DbIsOfExpression predicate)
{
EntityUtil.CheckArgumentNull(predicate, "predicate");
if (DbExpressionKind.IsOfOnly != predicate.ExpressionKind)
{
throw ConstructNotSupportedException(predicate);
}
PropagatorResult childResult = Visit(predicate.Argument);
bool result;
if (childResult.IsNull)
{
// Null value expressions are typed, but the semantics of null are slightly different.
result = false;
}
else
{
result = childResult.StructuralType.EdmEquals(predicate.OfType.EdmType);
}
return ConvertBoolToResult(result, childResult);
}
/// <summary>
/// Determines whether the row being evaluated has the given type (declared in the IsOf predicate).
/// </summary>
/// <param name="predicate">Equals predicate.</param>
/// <returns>True if the values being compared are equivalent; false otherwise.</returns>
public override PropagatorResult Visit(DbComparisonExpression predicate)
{
EntityUtil.CheckArgumentNull(predicate, "predicate");
if (DbExpressionKind.Equals == predicate.ExpressionKind)
{
// Retrieve the left and right hand sides of the equality predicate.
PropagatorResult leftResult = Visit(predicate.Left);
PropagatorResult rightResult = Visit(predicate.Right);
bool? result;
if (leftResult.IsNull || rightResult.IsNull)
{
result = null; // unknown
}
else
{
object left = leftResult.GetSimpleValue();
object right = rightResult.GetSimpleValue();
// Perform a comparison between the sides of the equality predicate using invariant culture.
// See assumptions outlined in the documentation for this class for additional information.
result = ByValueEqualityComparer.Default.Equals(left, right);
}
return ConvertBoolToResult(result, leftResult, rightResult);
}
else
{
throw ConstructNotSupportedException(predicate);
}
}
/// <summary>
/// Evaluates an 'and' expression given results of evalating its children.
/// </summary>
/// <param name="predicate">And predicate</param>
/// <returns>True if both child predicates are satisfied; false otherwise.</returns>
public override PropagatorResult Visit(DbAndExpression predicate)
{
EntityUtil.CheckArgumentNull(predicate, "predicate");
PropagatorResult left = Visit(predicate.Left);
PropagatorResult right = Visit(predicate.Right);
bool? leftResult = ConvertResultToBool(left);
bool? rightResult = ConvertResultToBool(right);
bool? result;
// Optimization: if either argument is false, preserved and known, return a
// result that is false, preserved and known.
if ((leftResult.HasValue && !leftResult.Value && PreservedAndKnown(left)) ||
(rightResult.HasValue && !rightResult.Value && PreservedAndKnown(right)))
{
return CreatePerservedAndKnownResult(false);
}
result = EntityUtil.ThreeValuedAnd(leftResult, rightResult);
return ConvertBoolToResult(result, left, right);
}
/// <summary>
/// Evaluates an 'or' expression given results of evaluating its children.
/// </summary>
/// <param name="predicate">'Or' predicate</param>
/// <returns>True if either child predicate is satisfied; false otherwise.</returns>
public override PropagatorResult Visit(DbOrExpression predicate)
{
EntityUtil.CheckArgumentNull(predicate, "predicate");
PropagatorResult left = Visit(predicate.Left);
PropagatorResult right = Visit(predicate.Right);
bool? leftResult = ConvertResultToBool(left);
bool? rightResult = ConvertResultToBool(right);
bool? result;
// Optimization: if either argument is true, preserved and known, return a
// result that is true, preserved and known.
if ((leftResult.HasValue && leftResult.Value && PreservedAndKnown(left)) ||
(rightResult.HasValue && rightResult.Value && PreservedAndKnown(right)))
{
return CreatePerservedAndKnownResult(true);
}
result = EntityUtil.ThreeValuedOr(leftResult, rightResult);
return ConvertBoolToResult(result, left, right);
}
private static PropagatorResult CreatePerservedAndKnownResult(object value)
{
// Known is the default (no explicit flag required)
return PropagatorResult.CreateSimpleValue(PropagatorFlags.Preserve, value);
}
private static bool PreservedAndKnown(PropagatorResult result)
{
// Check that the preserve flag is set, and the unknown flag is not set
return PropagatorFlags.Preserve == (result.PropagatorFlags & (PropagatorFlags.Preserve | PropagatorFlags.Unknown));
}
/// <summary>
/// Evalutes a 'not' expression given results
/// </summary>
/// <param name="predicate">'Not' predicate</param>
/// <returns>True of the argument to the 'not' predicate evaluator to false; false otherwise</returns>
public override PropagatorResult Visit(DbNotExpression predicate)
{
EntityUtil.CheckArgumentNull(predicate, "predicate");
PropagatorResult child = Visit(predicate.Argument);
bool? childResult = ConvertResultToBool(child);
bool? result = EntityUtil.ThreeValuedNot(childResult);
return ConvertBoolToResult(result, child);
}
/// <summary>
/// Returns the result of evaluating a case expression.
/// </summary>
/// <param name="node">Case expression node.</param>
/// <returns>Result of evaluating case expression over the input row for this visitor.</returns>
public override PropagatorResult Visit(DbCaseExpression node)
{
Debug.Assert(null != node, "node is not visited when null");
int match = -1;
int statementOrdinal = 0;
List<PropagatorResult> inputs = new List<PropagatorResult>();
foreach (DbExpression when in node.When)
{
PropagatorResult whenResult = Visit(when);
inputs.Add(whenResult);
bool matches = ConvertResultToBool(whenResult) ?? false; // ternary logic resolution
if (matches)
{
match = statementOrdinal;
break;
}
statementOrdinal++;
}
PropagatorResult matchResult;
if (-1 == match) { matchResult = Visit(node.Else); } else { matchResult = Visit(node.Then[match]); }
inputs.Add(matchResult);
// Clone the result to avoid modifying expressions that may be used elsewhere
// (design invariant: only set markup for expressions you create)
PropagatorFlags resultFlags = PropagateUnknownAndPreserveFlags(matchResult, inputs);
PropagatorResult result = matchResult.ReplicateResultWithNewFlags(resultFlags);
return result;
}
/// <summary>
/// Evaluates a var ref. In practice, this corresponds to the input row for the visitor (the row is
/// a member of the referenced input for a projection or filter).
/// We assert that types are consistent here.
/// </summary>
/// <param name="node">Var ref expression node</param>
/// <returns>Input row for the visitor.</returns>
public override PropagatorResult Visit(DbVariableReferenceExpression node)
{
Debug.Assert(null != node, "node is not visited when null");
return m_row;
}
/// <summary>
/// Evaluates a property expression given the result of evaluating the property's instance.
/// </summary>
/// <param name="node">Property expression node.</param>
/// <returns>DbExpression resulting from the evaluation of property.</returns>
public override PropagatorResult Visit(DbPropertyExpression node)
{
Debug.Assert(null != node, "node is not visited when null");
// Retrieve the result of evaluating the instance for the property.
PropagatorResult instance = Visit(node.Instance);
PropagatorResult result;
if (instance.IsNull)
{
result = PropagatorResult.CreateSimpleValue(instance.PropagatorFlags, null);
}
else
{
// find member
result = instance.GetMemberValue(node.Property);
}
// We do not markup the result since the property value already contains the necessary context
// (determined at record extraction time)
return result;
}
/// <summary>
/// Evaluates a constant expression (trivial: the result is the constant expression)
/// </summary>
/// <param name="node">Constant expression node.</param>
/// <returns>Constant expression</returns>
public override PropagatorResult Visit(DbConstantExpression node)
{
Debug.Assert(null != node, "node is not visited when null");
// Flag the expression as 'preserve', since constants (by definition) cannot vary
PropagatorResult result = PropagatorResult.CreateSimpleValue(PropagatorFlags.Preserve, node.Value);
return result;
}
/// <summary>
/// Evaluates a ref key expression based on the result of evaluating the argument to the ref.
/// </summary>
/// <param name="node">Ref key expression node.</param>
/// <returns>The structural key of the ref as a new instance (record).</returns>
public override PropagatorResult Visit(DbRefKeyExpression node)
{
Debug.Assert(null != node, "node is not visited when null");
// Retrieve the result of evaluating the child argument.
PropagatorResult argument = Visit(node.Argument);
// Return the argument directly (propagator results treat refs as standard structures)
return argument;
}
/// <summary>
/// Evaluates a null expression (trivial: the result is the null expression)
/// </summary>
/// <param name="node">Null expression node.</param>
/// <returns>Null expression</returns>
public override PropagatorResult Visit(DbNullExpression node)
{
Debug.Assert(null != node, "node is not visited when null");
// Flag the expression as 'preserve', since nulls (by definition) cannot vary
PropagatorResult result = PropagatorResult.CreateSimpleValue(PropagatorFlags.Preserve, null);
return result;
}
/// <summary>
/// Evaluates treat expression given a result for the argument to the treat.
/// </summary>
/// <param name="node">Treat expression</param>
/// <returns>Null if the argument is of the given type, the argument otherwise</returns>
public override PropagatorResult Visit(DbTreatExpression node)
{
Debug.Assert(null != node, "node is not visited when null");
PropagatorResult childResult = Visit(node.Argument);
TypeUsage nodeType = node.ResultType;
if (MetadataHelper.IsSuperTypeOf(nodeType.EdmType, childResult.StructuralType))
{
// Doing an up cast is not required because all property/ordinal
// accesses are unaffected for more derived types (derived members
// are appended)
return childResult;
}
// "Treat" where the result does not implement the given type results in a null
// result
PropagatorResult result = PropagatorResult.CreateSimpleValue(childResult.PropagatorFlags, null);
return result;
}
/// <summary>
/// Casts argument to expression.
/// </summary>
/// <param name="node">Cast expression node</param>
/// <returns>Result of casting argument</returns>
public override PropagatorResult Visit(DbCastExpression node)
{
Debug.Assert(null != node, "node is not visited when null");
PropagatorResult childResult = Visit(node.Argument);
TypeUsage nodeType = node.ResultType;
if (!childResult.IsSimple || BuiltInTypeKind.PrimitiveType != nodeType.EdmType.BuiltInTypeKind)
{
throw EntityUtil.NotSupported(Strings.Update_UnsupportedCastArgument(nodeType.EdmType.Name));
}
object resultValue;
if (childResult.IsNull)
{
resultValue = null;
}
else
{
try
{
resultValue = Cast(childResult.GetSimpleValue(), ((PrimitiveType)nodeType.EdmType).ClrEquivalentType);
}
catch
{
Debug.Fail("view generator failed to validate cast in update mapping view");
throw;
}
}
PropagatorResult result = childResult.ReplicateResultWithNewValue(resultValue);
return result;
}
/// <summary>
/// Casts an object instance to the specified model type.
/// </summary>
/// <param name="value">Value to cast</param>
/// <param name="clrPrimitiveType">clr type to which the value is casted to</param>
/// <returns>Cast value</returns>
private static object Cast(object value, Type clrPrimitiveType)
{
IFormatProvider formatProvider = CultureInfo.InvariantCulture;
if (null == value || value == DBNull.Value || value.GetType() == clrPrimitiveType)
{
return value;
}
else
{
//Convert is not handling DateTime to DateTimeOffset conversion
if ( (value is DateTime) && (clrPrimitiveType == typeof(DateTimeOffset)))
{
return new DateTimeOffset(((DateTime)value).Ticks, TimeSpan.Zero);
}
else
{
return Convert.ChangeType(value, clrPrimitiveType, formatProvider);
}
}
}
/// <summary>
/// Evaluate a null expression.
/// </summary>
/// <param name="node">Is null expression</param>
/// <returns>A boolean expression describing the result of evaluating the Is Null predicate</returns>
public override PropagatorResult Visit(DbIsNullExpression node)
{
Debug.Assert(null != node, "node is not visited when null");
PropagatorResult argumentResult = Visit(node.Argument);
bool result = argumentResult.IsNull;
return ConvertBoolToResult(result, argumentResult);
}
#endregion
/// <summary>
/// Supports propagation of preserve and unknown values when evaluating expressions. If any input
/// to an expression is marked as unknown, the same is true of the result of evaluating
/// that expression. If all inputs to an expression are marked 'preserve', then the result is also
/// marked preserve.
/// </summary>
/// <param name="result">Result to markup</param>
/// <param name="inputs">Expressions contributing to the result</param>
/// <returns>Marked up result.</returns>
private static PropagatorFlags PropagateUnknownAndPreserveFlags(PropagatorResult result, IEnumerable<PropagatorResult> inputs)
{
bool unknown = false;
bool preserve = true;
bool noInputs = true;
// aggregate all flags on the inputs
foreach (PropagatorResult input in inputs)
{
noInputs = false;
PropagatorFlags inputFlags = input.PropagatorFlags;
if (PropagatorFlags.NoFlags != (PropagatorFlags.Unknown & inputFlags))
{
unknown = true;
}
if (PropagatorFlags.NoFlags == (PropagatorFlags.Preserve & inputFlags))
{
preserve = false;
}
}
if (noInputs) { preserve = false; }
if (null != result)
{
// Merge with existing flags
PropagatorFlags flags = result.PropagatorFlags;
if (unknown)
{
flags |= PropagatorFlags.Unknown;
}
if (!preserve)
{
flags &= ~PropagatorFlags.Preserve;
}
return flags;
}
else
{
// if there is no input result, create new markup from scratch
PropagatorFlags flags = PropagatorFlags.NoFlags;
if (unknown)
{
flags |= PropagatorFlags.Unknown;
}
if (preserve)
{
flags |= PropagatorFlags.Preserve;
}
return flags;
}
}
#endregion
}
}
}
| |
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 Quibill.Web.Areas.HelpPage.ModelDescriptions;
using Quibill.Web.Areas.HelpPage.Models;
namespace Quibill.Web.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);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace System.Xml.XPath
{
internal class XNodeNavigator : XPathNavigator, IXmlLineInfo
{
internal static readonly string xmlPrefixNamespace = XNamespace.Xml.NamespaceName;
internal static readonly string xmlnsPrefixNamespace = XNamespace.Xmlns.NamespaceName;
private const int DocumentContentMask =
(1 << (int)XmlNodeType.Element) |
(1 << (int)XmlNodeType.ProcessingInstruction) |
(1 << (int)XmlNodeType.Comment);
private static readonly int[] s_ElementContentMasks = {
0, // Root
(1 << (int)XmlNodeType.Element), // Element
0, // Attribute
0, // Namespace
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text), // Text
0, // SignificantWhitespace
0, // Whitespace
(1 << (int)XmlNodeType.ProcessingInstruction), // ProcessingInstruction
(1 << (int)XmlNodeType.Comment), // Comment
(1 << (int)XmlNodeType.Element) |
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text) |
(1 << (int)XmlNodeType.ProcessingInstruction) |
(1 << (int)XmlNodeType.Comment) // All
};
private const int TextMask =
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text);
private static XAttribute s_XmlNamespaceDeclaration;
// The navigator position is encoded by the tuple (source, parent).
// Namespace declaration uses (instance, parent element).
// Common XObjects uses (instance, null).
private XObject _source;
private XElement _parent;
private XmlNameTable _nameTable;
public XNodeNavigator(XNode node, XmlNameTable nameTable)
{
_source = node;
_nameTable = nameTable != null ? nameTable : CreateNameTable();
}
public XNodeNavigator(XNodeNavigator other)
{
_source = other._source;
_parent = other._parent;
_nameTable = other._nameTable;
}
public override string BaseURI
{
get
{
if (_source != null)
{
return _source.BaseUri;
}
if (_parent != null)
{
return _parent.BaseUri;
}
return string.Empty;
}
}
public override bool HasAttributes
{
get
{
XElement element = _source as XElement;
if (element != null)
{
foreach (XAttribute attribute in element.Attributes())
{
if (!attribute.IsNamespaceDeclaration)
{
return true;
}
}
}
return false;
}
}
public override bool HasChildren
{
get
{
XContainer container = _source as XContainer;
if (container != null)
{
foreach (XNode node in container.Nodes())
{
if (IsContent(container, node))
{
return true;
}
}
}
return false;
}
}
public override bool IsEmptyElement
{
get
{
XElement e = _source as XElement;
return e != null && e.IsEmpty;
}
}
public override string LocalName
{
get { return _nameTable.Add(GetLocalName()); }
}
private string GetLocalName()
{
XElement e = _source as XElement;
if (e != null)
{
return e.Name.LocalName;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null && a.Name.NamespaceName.Length == 0)
{
return string.Empty; // backcompat
}
return a.Name.LocalName;
}
XProcessingInstruction p = _source as XProcessingInstruction;
if (p != null)
{
return p.Target;
}
return string.Empty;
}
public override string Name
{
get
{
string prefix = GetPrefix();
if (prefix.Length == 0)
{
return _nameTable.Add(GetLocalName());
}
return _nameTable.Add(string.Concat(prefix, ":", GetLocalName()));
}
}
public override string NamespaceURI
{
get { return _nameTable.Add(GetNamespaceURI()); }
}
private string GetNamespaceURI()
{
XElement e = _source as XElement;
if (e != null)
{
return e.Name.NamespaceName;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null)
{
return string.Empty; // backcompat
}
return a.Name.NamespaceName;
}
return string.Empty;
}
public override XmlNameTable NameTable
{
get { return _nameTable; }
}
public override XPathNodeType NodeType
{
get
{
if (_source != null)
{
switch (_source.NodeType)
{
case XmlNodeType.Element:
return XPathNodeType.Element;
case XmlNodeType.Attribute:
XAttribute attribute = (XAttribute)_source;
return attribute.IsNamespaceDeclaration ? XPathNodeType.Namespace : XPathNodeType.Attribute;
case XmlNodeType.Document:
return XPathNodeType.Root;
case XmlNodeType.Comment:
return XPathNodeType.Comment;
case XmlNodeType.ProcessingInstruction:
return XPathNodeType.ProcessingInstruction;
default:
return XPathNodeType.Text;
}
}
return XPathNodeType.Text;
}
}
public override string Prefix
{
get { return _nameTable.Add(GetPrefix()); }
}
private string GetPrefix()
{
XElement e = _source as XElement;
if (e != null)
{
string prefix = e.GetPrefixOfNamespace(e.Name.Namespace);
if (prefix != null)
{
return prefix;
}
return string.Empty;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null)
{
return string.Empty; // backcompat
}
string prefix = a.GetPrefixOfNamespace(a.Name.Namespace);
if (prefix != null)
{
return prefix;
}
}
return string.Empty;
}
public override object UnderlyingObject
{
get
{
return _source;
}
}
public override string Value
{
get
{
if (_source != null)
{
switch (_source.NodeType)
{
case XmlNodeType.Element:
return ((XElement)_source).Value;
case XmlNodeType.Attribute:
return ((XAttribute)_source).Value;
case XmlNodeType.Document:
XElement root = ((XDocument)_source).Root;
return root != null ? root.Value : string.Empty;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
return CollectText((XText)_source);
case XmlNodeType.Comment:
return ((XComment)_source).Value;
case XmlNodeType.ProcessingInstruction:
return ((XProcessingInstruction)_source).Data;
default:
return string.Empty;
}
}
return string.Empty;
}
}
public override XPathNavigator Clone()
{
return new XNodeNavigator(this);
}
public override bool IsSamePosition(XPathNavigator navigator)
{
XNodeNavigator other = navigator as XNodeNavigator;
if (other == null)
{
return false;
}
return IsSamePosition(this, other);
}
public override bool MoveTo(XPathNavigator navigator)
{
XNodeNavigator other = navigator as XNodeNavigator;
if (other != null)
{
_source = other._source;
_parent = other._parent;
return true;
}
return false;
}
public override bool MoveToAttribute(string localName, string namespaceName)
{
XElement e = _source as XElement;
if (e != null)
{
foreach (XAttribute attribute in e.Attributes())
{
if (attribute.Name.LocalName == localName &&
attribute.Name.NamespaceName == namespaceName &&
!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
return false;
}
public override bool MoveToChild(string localName, string namespaceName)
{
XContainer c = _source as XContainer;
if (c != null)
{
foreach (XElement element in c.Elements())
{
if (element.Name.LocalName == localName &&
element.Name.NamespaceName == namespaceName)
{
_source = element;
return true;
}
}
}
return false;
}
public override bool MoveToChild(XPathNodeType type)
{
XContainer c = _source as XContainer;
if (c != null)
{
int mask = GetElementContentMask(type);
if ((TextMask & mask) != 0 && c.GetParent() == null && c is XDocument)
{
mask &= ~TextMask;
}
foreach (XNode node in c.Nodes())
{
if (((1 << (int)node.NodeType) & mask) != 0)
{
_source = node;
return true;
}
}
}
return false;
}
public override bool MoveToFirstAttribute()
{
XElement e = _source as XElement;
if (e != null)
{
foreach (XAttribute attribute in e.Attributes())
{
if (!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
return false;
}
public override bool MoveToFirstChild()
{
XContainer container = _source as XContainer;
if (container != null)
{
foreach (XNode node in container.Nodes())
{
if (IsContent(container, node))
{
_source = node;
return true;
}
}
}
return false;
}
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
XElement e = _source as XElement;
if (e != null)
{
XAttribute a = null;
switch (scope)
{
case XPathNamespaceScope.Local:
a = GetFirstNamespaceDeclarationLocal(e);
break;
case XPathNamespaceScope.ExcludeXml:
a = GetFirstNamespaceDeclarationGlobal(e);
while (a != null && a.Name.LocalName == "xml")
{
a = GetNextNamespaceDeclarationGlobal(a);
}
break;
case XPathNamespaceScope.All:
a = GetFirstNamespaceDeclarationGlobal(e);
if (a == null)
{
a = GetXmlNamespaceDeclaration();
}
break;
}
if (a != null)
{
_source = a;
_parent = e;
return true;
}
}
return false;
}
public override bool MoveToId(string id)
{
throw new NotSupportedException(SR.NotSupported_MoveToId);
}
public override bool MoveToNamespace(string localName)
{
XElement e = _source as XElement;
if (e != null)
{
if (localName == "xmlns")
{
return false; // backcompat
}
if (localName != null && localName.Length == 0)
{
localName = "xmlns"; // backcompat
}
XAttribute a = GetFirstNamespaceDeclarationGlobal(e);
while (a != null)
{
if (a.Name.LocalName == localName)
{
_source = a;
_parent = e;
return true;
}
a = GetNextNamespaceDeclarationGlobal(a);
}
if (localName == "xml")
{
_source = GetXmlNamespaceDeclaration();
_parent = e;
return true;
}
}
return false;
}
public override bool MoveToNext()
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
XNode next = null;
for (XNode node = currentNode; node != null; node = next)
{
next = node.NextNode;
if (next == null)
{
break;
}
if (IsContent(container, next) && !(node is XText && next is XText))
{
_source = next;
return true;
}
}
}
}
return false;
}
public override bool MoveToNext(string localName, string namespaceName)
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
foreach (XElement element in currentNode.ElementsAfterSelf())
{
if (element.Name.LocalName == localName &&
element.Name.NamespaceName == namespaceName)
{
_source = element;
return true;
}
}
}
return false;
}
public override bool MoveToNext(XPathNodeType type)
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
int mask = GetElementContentMask(type);
if ((TextMask & mask) != 0 && container.GetParent() == null && container is XDocument)
{
mask &= ~TextMask;
}
XNode next = null;
for (XNode node = currentNode; node != null; node = next)
{
next = node.NextNode;
if (((1 << (int)next.NodeType) & mask) != 0 && !(node is XText && next is XText))
{
_source = next;
return true;
}
}
}
}
return false;
}
public override bool MoveToNextAttribute()
{
XAttribute currentAttribute = _source as XAttribute;
if (currentAttribute != null && _parent == null)
{
XElement e = (XElement)currentAttribute.GetParent();
if (e != null)
{
for (XAttribute attribute = currentAttribute.NextAttribute; attribute != null; attribute = attribute.NextAttribute)
{
if (!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
}
return false;
}
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
XAttribute a = _source as XAttribute;
if (a != null && _parent != null && !IsXmlNamespaceDeclaration(a))
{
switch (scope)
{
case XPathNamespaceScope.Local:
if (a.GetParent() != _parent)
{
return false;
}
a = GetNextNamespaceDeclarationLocal(a);
break;
case XPathNamespaceScope.ExcludeXml:
do
{
a = GetNextNamespaceDeclarationGlobal(a);
} while (a != null &&
(a.Name.LocalName == "xml" ||
HasNamespaceDeclarationInScope(a, _parent)));
break;
case XPathNamespaceScope.All:
do
{
a = GetNextNamespaceDeclarationGlobal(a);
} while (a != null &&
HasNamespaceDeclarationInScope(a, _parent));
if (a == null &&
!HasNamespaceDeclarationInScope(GetXmlNamespaceDeclaration(), _parent))
{
a = GetXmlNamespaceDeclaration();
}
break;
}
if (a != null)
{
_source = a;
return true;
}
}
return false;
}
public override bool MoveToParent()
{
if (_parent != null)
{
_source = _parent;
_parent = null;
return true;
}
XNode parentNode = _source.GetParent();
if (parentNode != null)
{
_source = parentNode;
return true;
}
return false;
}
public override bool MoveToPrevious()
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
XNode previous = null;
foreach (XNode node in container.Nodes())
{
if (node == currentNode)
{
if (previous != null)
{
_source = previous;
return true;
}
return false;
}
if (IsContent(container, node))
{
previous = node;
}
}
}
}
return false;
}
public override XmlReader ReadSubtree()
{
XContainer c = _source as XContainer;
if (c == null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadNodeType, NodeType));
return c.CreateReader();
}
bool IXmlLineInfo.HasLineInfo()
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.HasLineInfo();
}
return false;
}
int IXmlLineInfo.LineNumber
{
get
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.LineNumber;
}
return 0;
}
}
int IXmlLineInfo.LinePosition
{
get
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.LinePosition;
}
return 0;
}
}
private static string CollectText(XText n)
{
string s = n.Value;
if (n.GetParent() != null)
{
foreach (XNode node in n.NodesAfterSelf())
{
XText t = node as XText;
if (t == null) break;
s += t.Value;
}
}
return s;
}
private static XmlNameTable CreateNameTable()
{
XmlNameTable nameTable = new NameTable();
nameTable.Add(string.Empty);
nameTable.Add(xmlnsPrefixNamespace);
nameTable.Add(xmlPrefixNamespace);
return nameTable;
}
private static bool IsContent(XContainer c, XNode n)
{
if (c.GetParent() != null || c is XElement)
{
return true;
}
return ((1 << (int)n.NodeType) & DocumentContentMask) != 0;
}
private static bool IsSamePosition(XNodeNavigator n1, XNodeNavigator n2)
{
return n1._source == n2._source && n1._source.GetParent() == n2._source.GetParent();
}
private static bool IsXmlNamespaceDeclaration(XAttribute a)
{
return (object)a == (object)GetXmlNamespaceDeclaration();
}
private static int GetElementContentMask(XPathNodeType type)
{
return s_ElementContentMasks[(int)type];
}
private static XAttribute GetFirstNamespaceDeclarationGlobal(XElement e)
{
do
{
XAttribute a = GetFirstNamespaceDeclarationLocal(e);
if (a != null)
{
return a;
}
e = e.Parent;
} while (e != null);
return null;
}
private static XAttribute GetFirstNamespaceDeclarationLocal(XElement e)
{
foreach (XAttribute attribute in e.Attributes())
{
if (attribute.IsNamespaceDeclaration)
{
return attribute;
}
}
return null;
}
private static XAttribute GetNextNamespaceDeclarationGlobal(XAttribute a)
{
XElement e = (XElement)a.GetParent();
if (e == null)
{
return null;
}
XAttribute next = GetNextNamespaceDeclarationLocal(a);
if (next != null)
{
return next;
}
e = e.Parent;
if (e == null)
{
return null;
}
return GetFirstNamespaceDeclarationGlobal(e);
}
private static XAttribute GetNextNamespaceDeclarationLocal(XAttribute a)
{
XElement e = a.Parent;
if (e == null)
{
return null;
}
a = a.NextAttribute;
while (a != null)
{
if (a.IsNamespaceDeclaration)
{
return a;
}
a = a.NextAttribute;
}
return null;
}
private static XAttribute GetXmlNamespaceDeclaration()
{
if (s_XmlNamespaceDeclaration == null)
{
System.Threading.Interlocked.CompareExchange(ref s_XmlNamespaceDeclaration, new XAttribute(XNamespace.Xmlns.GetName("xml"), xmlPrefixNamespace), null);
}
return s_XmlNamespaceDeclaration;
}
private static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e)
{
XName name = a.Name;
while (e != null && e != a.GetParent())
{
if (e.Attribute(name) != null)
{
return true;
}
e = e.Parent;
}
return false;
}
}
internal readonly struct XPathEvaluator
{
public object Evaluate<T>(XNode node, string expression, IXmlNamespaceResolver resolver) where T : class
{
XPathNavigator navigator = node.CreateNavigator();
object result = navigator.Evaluate(expression, resolver);
XPathNodeIterator iterator = result as XPathNodeIterator;
if (iterator != null)
{
return EvaluateIterator<T>(iterator);
}
if (!(result is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, result.GetType()));
return (T)result;
}
private IEnumerable<T> EvaluateIterator<T>(XPathNodeIterator result)
{
foreach (XPathNavigator navigator in result)
{
object r = navigator.UnderlyingObject;
if (!(r is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, r.GetType()));
yield return (T)r;
XText t = r as XText;
if (t != null && t.GetParent() != null)
{
do
{
t = t.NextNode as XText;
if (t == null) break;
yield return (T)(object)t;
} while (t != t.GetParent().LastNode);
}
}
}
}
/// <summary>
/// Extension methods
/// </summary>
public static class Extensions
{
/// <summary>
/// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/>
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <returns>An <see cref="XPathNavigator"/></returns>
public static XPathNavigator CreateNavigator(this XNode node)
{
return node.CreateNavigator(null);
}
/// <summary>
/// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/>
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="nameTable">The <see cref="XmlNameTable"/> to be used by
/// the <see cref="XPathNavigator"/></param>
/// <returns>An <see cref="XPathNavigator"/></returns>
public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable nameTable)
{
if (node == null) throw new ArgumentNullException(nameof(node));
if (node is XDocumentType) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.DocumentType));
XText text = node as XText;
if (text != null)
{
if (text.GetParent() is XDocument) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.Whitespace));
node = CalibrateText(text);
}
return new XNodeNavigator(node, nameTable);
}
/// <summary>
/// Evaluates an XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>The result of evaluating the expression which can be typed as bool, double, string or
/// IEnumerable</returns>
public static object XPathEvaluate(this XNode node, string expression)
{
return node.XPathEvaluate(expression, null);
}
/// <summary>
/// Evaluates an XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"> for the namespace
/// prefixes used in the XPath expression</see></param>
/// <returns>The result of evaluating the expression which can be typed as bool, double, string or
/// IEnumerable</returns>
public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
if (node == null) throw new ArgumentNullException(nameof(node));
return new XPathEvaluator().Evaluate<object>(node, expression, resolver);
}
/// <summary>
/// Select an <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>An <see cref="XElement"> or null</see></returns>
public static XElement XPathSelectElement(this XNode node, string expression)
{
return node.XPathSelectElement(expression, null);
}
/// <summary>
/// Select an <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace
/// prefixes used in the XPath expression</param>
/// <returns>An <see cref="XElement"> or null</see></returns>
public static XElement XPathSelectElement(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
return node.XPathSelectElements(expression, resolver).FirstOrDefault();
}
/// <summary>
/// Select a set of <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>An <see cref="IEnumerable<XElement>"/> corresponding to the resulting set of elements</returns>
public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression)
{
return node.XPathSelectElements(expression, null);
}
/// <summary>
/// Select a set of <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace
/// prefixes used in the XPath expression</param>
/// <returns>An <see cref="IEnumerable<XElement>"/> corresponding to the resulting set of elements</returns>
public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
if (node == null) throw new ArgumentNullException(nameof(node));
return (IEnumerable<XElement>)new XPathEvaluator().Evaluate<XElement>(node, expression, resolver);
}
private static XText CalibrateText(XText n)
{
XContainer parentNode = n.GetParent();
if (parentNode == null)
{
return n;
}
foreach (XNode node in parentNode.Nodes())
{
XText t = node as XText;
bool isTextNode = t != null;
if (isTextNode && node == n)
{
return t;
}
}
System.Diagnostics.Debug.Fail("Parent node doesn't contain itself.");
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Schema;
using System.Xml;
namespace System.Xml.Serialization
{
internal class ReflectionXmlSerializationWriter : XmlSerializationWriter
{
private XmlMapping _mapping;
internal static TypeDesc StringTypeDesc { get; private set; } = (new TypeScope()).GetTypeDesc(typeof(string));
internal static TypeDesc QnameTypeDesc { get; private set; } = (new TypeScope()).GetTypeDesc(typeof(XmlQualifiedName));
public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWriter, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
{
Init(xmlWriter, namespaces, encodingStyle, id, null);
if (!xmlMapping.IsWriteable || !xmlMapping.GenerateSerializer)
{
throw new ArgumentException(SR.Format(SR.XmlInternalError, nameof(xmlMapping)));
}
if (xmlMapping is XmlTypeMapping || xmlMapping is XmlMembersMapping)
{
_mapping = xmlMapping;
}
else
{
throw new ArgumentException(SR.Format(SR.XmlInternalError, nameof(xmlMapping)));
}
}
protected override void InitCallbacks()
{
TypeScope scope = _mapping.Scope;
foreach (TypeMapping mapping in scope.TypeMappings)
{
if (mapping.IsSoap &&
(mapping is StructMapping || mapping is EnumMapping) &&
!mapping.TypeDesc.IsRoot)
{
AddWriteCallback(
mapping.TypeDesc.Type,
mapping.TypeName,
mapping.Namespace,
CreateXmlSerializationWriteCallback(mapping, mapping.TypeName, mapping.Namespace, mapping.TypeDesc.IsNullable)
);
}
}
}
public void WriteObject(object o)
{
XmlMapping xmlMapping = _mapping;
if (xmlMapping is XmlTypeMapping xmlTypeMapping)
{
WriteObjectOfTypeElement(o, xmlTypeMapping);
}
else if (xmlMapping is XmlMembersMapping xmlMembersMapping)
{
GenerateMembersElement(o, xmlMembersMapping);
}
}
private void WriteObjectOfTypeElement(object o, XmlTypeMapping mapping)
{
GenerateTypeElement(o, mapping);
}
private void GenerateTypeElement(object o, XmlTypeMapping xmlMapping)
{
ElementAccessor element = xmlMapping.Accessor;
TypeMapping mapping = element.Mapping;
WriteStartDocument();
if (o == null)
{
string ns = (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty);
if (element.IsNullable)
{
if (mapping.IsSoap)
{
WriteNullTagEncoded(element.Name, ns);
}
else
{
WriteNullTagLiteral(element.Name, ns);
}
}
else
{
WriteEmptyTag(element.Name, ns);
}
return;
}
if (!mapping.TypeDesc.IsValueType && !mapping.TypeDesc.Type.IsPrimitive)
{
TopLevelElement();
}
WriteMember(o, null, new ElementAccessor[] { element }, null, null, mapping.TypeDesc, !element.IsSoap);
if (mapping.IsSoap)
{
WriteReferencedElements();
}
}
private void WriteMember(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, bool writeAccessors)
{
if (memberTypeDesc.IsArrayLike &&
!(elements.Length == 1 && elements[0].Mapping is ArrayMapping))
{
WriteArray(o, choiceSource, elements, text, choice, memberTypeDesc);
}
else
{
WriteElements(o, choiceSource, elements, text, choice, writeAccessors, memberTypeDesc.IsNullable);
}
}
private void WriteArray(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc)
{
if (elements.Length == 0 && text == null)
{
return;
}
if (arrayTypeDesc.IsNullable && o == null)
{
return;
}
if (choice != null)
{
if (choiceSource == null || ((Array)choiceSource).Length < ((Array)o).Length)
{
throw CreateInvalidChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName);
}
}
WriteArrayItems(elements, text, choice, arrayTypeDesc, o);
}
private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc, object o)
{
TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc;
var arr = o as IList;
if (arr != null)
{
for (int i = 0; i < arr.Count; i++)
{
object ai = arr[i];
WriteElements(ai, null/*choiceName + "i"*/, elements, text, choice, true, true);
}
}
else
{
var a = o as IEnumerable;
// #10593: This assert may not be true. We need more tests for this method.
Debug.Assert(a != null);
IEnumerator e = a.GetEnumerator();
if (e != null)
{
while (e.MoveNext())
{
object ai = e.Current;
WriteElements(ai, null/*choiceName + "i"*/, elements, text, choice, true, true);
}
}
}
}
private void WriteElements(object o, object enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, bool writeAccessors, bool isNullable)
{
if (elements.Length == 0 && text == null)
return;
if (elements.Length == 1 && text == null)
{
WriteElement(o, elements[0], writeAccessors);
}
else
{
if (isNullable && choice == null && o == null)
{
return;
}
int anyCount = 0;
var namedAnys = new List<ElementAccessor>();
ElementAccessor unnamedAny = null; // can only have one
string enumTypeName = choice?.Mapping.TypeDesc.FullName;
for (int i = 0; i < elements.Length; i++)
{
ElementAccessor element = elements[i];
if (element.Any)
{
anyCount++;
if (element.Name != null && element.Name.Length > 0)
namedAnys.Add(element);
else if (unnamedAny == null)
unnamedAny = element;
}
else if (choice != null)
{
if (o != null && o.GetType() == element.Mapping.TypeDesc.Type)
{
WriteElement(o, element, writeAccessors);
return;
}
}
else
{
TypeDesc td = element.IsUnbounded ? element.Mapping.TypeDesc.CreateArrayTypeDesc() : element.Mapping.TypeDesc;
if (o.GetType() == td.Type)
{
WriteElement(o, element, writeAccessors);
return;
}
}
}
if (anyCount > 0)
{
if (o is XmlElement elem)
{
foreach (ElementAccessor element in namedAnys)
{
if (element.Name == elem.Name && element.Namespace == elem.NamespaceURI)
{
WriteElement(elem, element, writeAccessors);
return;
}
}
if (choice != null)
{
throw CreateChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName, elem.Name, elem.NamespaceURI);
}
if (unnamedAny != null)
{
WriteElement(elem, unnamedAny, writeAccessors);
return;
}
throw CreateUnknownAnyElementException(elem.Name, elem.NamespaceURI);
}
}
if (text != null)
{
bool useReflection = text.Mapping.TypeDesc.UseReflection;
string fullTypeName = text.Mapping.TypeDesc.CSharpName;
WriteText(o, text);
return;
}
if (elements.Length > 0 && o != null)
{
throw CreateUnknownTypeException(o);
}
}
}
private void WriteText(object o, TextAccessor text)
{
if (text.Mapping is PrimitiveMapping primitiveMapping)
{
string stringValue;
if (text.Mapping is EnumMapping enumMapping)
{
stringValue = WriteEnumMethod(enumMapping, o);
}
else
{
if (!WritePrimitiveValue(primitiveMapping.TypeDesc, o, false, out stringValue))
{
// #10593: Add More Tests for Serialization Code
Debug.Assert(o is byte[]);
}
}
if (o is byte[] byteArray)
{
WriteValue(byteArray);
}
else
{
WriteValue(stringValue);
}
}
else if (text.Mapping is SpecialMapping specialMapping)
{
switch (specialMapping.TypeDesc.Kind)
{
case TypeKind.Node:
((XmlNode)o).WriteTo(Writer);
break;
default:
throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
}
}
}
private void WriteElement(object o, ElementAccessor element, bool writeAccessor)
{
string name = writeAccessor ? element.Name : element.Mapping.TypeName;
string ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping.Namespace) : string.Empty);
if (element.Mapping is NullableMapping nullableMapping)
{
if (o != null)
{
ElementAccessor e = element.Clone();
e.Mapping = nullableMapping.BaseMapping;
WriteElement(o, e, writeAccessor);
}
else if (element.IsNullable)
{
WriteNullTagLiteral(element.Name, ns);
}
}
else if (element.Mapping is ArrayMapping)
{
var mapping = element.Mapping as ArrayMapping;
if (element.IsNullable && o == null)
{
WriteNullTagLiteral(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty);
}
else if (mapping.IsSoap)
{
if (mapping.Elements == null || mapping.Elements.Length != 1)
{
throw new InvalidOperationException(SR.XmlInternalError);
}
if (!writeAccessor)
{
WritePotentiallyReferencingElement(name, ns, o, mapping.TypeDesc.Type, true, element.IsNullable);
}
else
{
WritePotentiallyReferencingElement(name, ns, o, null, false, element.IsNullable);
}
}
else if (element.IsUnbounded)
{
TypeDesc arrayTypeDesc = mapping.TypeDesc.CreateArrayTypeDesc();
var enumerable = (IEnumerable)o;
foreach (var e in enumerable)
{
element.IsUnbounded = false;
WriteElement(e, element, writeAccessor);
element.IsUnbounded = true;
}
}
else
{
if (o != null)
{
WriteStartElement(name, ns, false);
WriteArrayItems(mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, o);
WriteEndElement();
}
}
}
else if (element.Mapping is EnumMapping)
{
if (element.Mapping.IsSoap)
{
Writer.WriteStartElement(name, ns);
WriteEnumMethod((EnumMapping)element.Mapping, o);
WriteEndElement();
}
else
{
WritePrimitive(WritePrimitiveMethodRequirement.WriteElementString, name, ns, element.Default, o, element.Mapping, false, true, element.IsNullable);
}
}
else if (element.Mapping is PrimitiveMapping)
{
var mapping = element.Mapping as PrimitiveMapping;
if (mapping.TypeDesc == QnameTypeDesc)
{
WriteQualifiedNameElement(name, ns, element.Default, (XmlQualifiedName)o, element.IsNullable, mapping.IsSoap, mapping);
}
else
{
WritePrimitiveMethodRequirement suffixNullable = mapping.IsSoap ? WritePrimitiveMethodRequirement.Encoded : WritePrimitiveMethodRequirement.None;
WritePrimitiveMethodRequirement suffixRaw = mapping.TypeDesc.XmlEncodingNotRequired ? WritePrimitiveMethodRequirement.Raw : WritePrimitiveMethodRequirement.None;
WritePrimitive(element.IsNullable
? WritePrimitiveMethodRequirement.WriteNullableStringLiteral | suffixNullable | suffixRaw
: WritePrimitiveMethodRequirement.WriteElementString | suffixRaw,
name, ns, element.Default, o, mapping, mapping.IsSoap, true, element.IsNullable);
}
}
else if (element.Mapping is StructMapping)
{
var mapping = element.Mapping as StructMapping;
if (mapping.IsSoap)
{
WritePotentiallyReferencingElement(name, ns, o, !writeAccessor ? mapping.TypeDesc.Type : null, !writeAccessor, element.IsNullable);
}
else
{
WriteStructMethod(mapping, name, ns, o, element.IsNullable, needType: false);
}
}
else if (element.Mapping is SpecialMapping)
{
if (element.Mapping is SerializableMapping)
{
WriteSerializable((IXmlSerializable)o, name, ns, element.IsNullable, !element.Any);
}
else
{
// XmlNode, XmlElement
if (o is XmlNode node)
{
WriteElementLiteral(node, name, ns, element.IsNullable, element.Any);
}
else
{
throw CreateInvalidAnyTypeException(o);
}
}
}
else
{
throw new InvalidOperationException(SR.XmlInternalError);
}
}
private XmlSerializationWriteCallback CreateXmlSerializationWriteCallback(TypeMapping mapping, string name, string ns, bool isNullable)
{
if (mapping is StructMapping structMapping)
{
return (o) =>
{
WriteStructMethod(structMapping, name, ns, o, isNullable, needType: false);
};
}
else if (mapping is EnumMapping enumMapping)
{
return (o) =>
{
WriteEnumMethod(enumMapping, o);
};
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
}
}
private void WriteQualifiedNameElement(string name, string ns, object defaultValue, XmlQualifiedName o, bool nullable, bool isSoap, PrimitiveMapping mapping)
{
bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport;
if (hasDefault && IsDefaultValue(mapping, o, defaultValue, nullable))
return;
if (isSoap)
{
if (nullable)
{
WriteNullableQualifiedNameEncoded(name, ns, o, new XmlQualifiedName(mapping.TypeName, mapping.Namespace));
}
else
{
WriteElementQualifiedName(name, ns, o, new XmlQualifiedName(mapping.TypeName, mapping.Namespace));
}
}
else
{
if (nullable)
{
WriteNullableQualifiedNameLiteral(name, ns, o);
}
else
{
WriteElementQualifiedName(name, ns, o);
}
}
}
private void WriteStructMethod(StructMapping mapping, string n, string ns, object o, bool isNullable, bool needType)
{
if (mapping.IsSoap && mapping.TypeDesc.IsRoot) return;
if (!mapping.IsSoap)
{
if (o == null)
{
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType
&& o.GetType() != mapping.TypeDesc.Type)
{
if (WriteDerivedTypes(mapping, n, ns, o, isNullable))
{
return;
}
if (mapping.TypeDesc.IsRoot)
{
if (WriteEnumAndArrayTypes(mapping, o, n, ns))
{
return;
}
WriteTypedPrimitive(n, ns, o, true);
return;
}
throw CreateUnknownTypeException(o);
}
}
if (!mapping.TypeDesc.IsAbstract)
{
if (mapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(mapping.TypeDesc.Type))
{
EscapeName = false;
}
XmlSerializerNamespaces xmlnsSource = null;
MemberMapping[] members = TypeScope.GetAllMembers(mapping);
int xmlnsMember = FindXmlnsIndex(members);
if (xmlnsMember >= 0)
{
MemberMapping member = members[xmlnsMember];
xmlnsSource = (XmlSerializerNamespaces)GetMemberValue(o, member.Name);
}
if (!mapping.IsSoap)
{
WriteStartElement(n, ns, o, false, xmlnsSource);
if (!mapping.TypeDesc.IsRoot)
{
if (needType)
{
WriteXsiType(mapping.TypeName, mapping.Namespace);
}
}
}
else if (xmlnsSource != null)
{
WriteNamespaceDeclarations(xmlnsSource);
}
for (int i = 0; i < members.Length; i++)
{
MemberMapping m = members[i];
bool isSpecified = true;
bool shouldPersist = true;
if (m.CheckSpecified != SpecifiedAccessor.None)
{
string specifiedMemberName = m.Name + "Specified";
isSpecified = (bool)GetMemberValue(o, specifiedMemberName);
}
if (m.CheckShouldPersist)
{
string methodInvoke = "ShouldSerialize" + m.Name;
MethodInfo method = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke);
shouldPersist = (bool)method.Invoke(o, Array.Empty<object>());
}
if (m.Attribute != null)
{
if (isSpecified && shouldPersist)
{
object memberValue = GetMemberValue(o, m.Name);
WriteMember(memberValue, m.Attribute, m.TypeDesc, o);
}
}
}
for (int i = 0; i < members.Length; i++)
{
MemberMapping m = members[i];
if (m.Xmlns != null)
continue;
bool isSpecified = true;
bool shouldPersist = true;
if (m.CheckSpecified != SpecifiedAccessor.None)
{
string specifiedMemberName = m.Name + "Specified";
isSpecified = (bool)GetMemberValue(o, specifiedMemberName);
}
if (m.CheckShouldPersist)
{
string methodInvoke = "ShouldSerialize" + m.Name;
MethodInfo method = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke);
shouldPersist = (bool)method.Invoke(o, Array.Empty<object>());
}
bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null);
if (!checkShouldPersist)
{
shouldPersist = true;
}
if (isSpecified && shouldPersist)
{
object choiceSource = null;
if (m.ChoiceIdentifier != null)
{
choiceSource = GetMemberValue(o, m.ChoiceIdentifier.MemberName);
}
object memberValue = GetMemberValue(o, m.Name);
WriteMember(memberValue, choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true);
}
}
if (!mapping.IsSoap)
{
WriteEndElement(o);
}
}
}
private object GetMemberValue(object o, string memberName)
{
MemberInfo memberInfo = ReflectionXmlSerializationHelper.GetMember(o.GetType(), memberName);
object memberValue = GetMemberValue(o, memberInfo);
return memberValue;
}
private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, string n, string ns)
{
if (o is Enum)
{
Writer.WriteStartElement(n, ns);
EnumMapping enumMapping = null;
Type enumType = o.GetType();
foreach (var m in _mapping.Scope.TypeMappings)
{
if (m is EnumMapping em && em.TypeDesc.Type == enumType)
{
enumMapping = em;
break;
}
}
if (enumMapping == null)
throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
WriteXsiType(enumMapping.TypeName, ns);
Writer.WriteString(WriteEnumMethod(enumMapping, o));
Writer.WriteEndElement();
return true;
}
if (o is Array)
{
Writer.WriteStartElement(n, ns);
ArrayMapping arrayMapping = null;
Type arrayType = o.GetType();
foreach (var m in _mapping.Scope.TypeMappings)
{
if (m is ArrayMapping am && am.TypeDesc.Type == arrayType)
{
arrayMapping = am;
break;
}
}
if (arrayMapping == null)
throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
WriteXsiType(arrayMapping.TypeName, ns);
WriteMember(o, null, arrayMapping.ElementsSortedByDerivation, null, null, arrayMapping.TypeDesc, true);
Writer.WriteEndElement();
return true;
}
return false;
}
private string WriteEnumMethod(EnumMapping mapping, object v)
{
string returnString = null;
if (mapping != null)
{
ConstantMapping[] constants = mapping.Constants;
if (constants.Length > 0)
{
bool foundValue = false;
var enumValue = Convert.ToInt64(v);
for (int i = 0; i < constants.Length; i++)
{
ConstantMapping c = constants[i];
if (enumValue == c.Value)
{
returnString = c.XmlName;
foundValue = true;
break;
}
}
if (!foundValue)
{
if (mapping.IsFlags)
{
string[] xmlNames = new string[constants.Length];
long[] valueIds = new long[constants.Length];
for (int i = 0; i < constants.Length; i++)
{
xmlNames[i] = constants[i].XmlName;
valueIds[i] = constants[i].Value;
}
returnString = FromEnum(enumValue, xmlNames, valueIds);
}
else
{
throw CreateInvalidEnumValueException(v, mapping.TypeDesc.FullName);
}
}
}
}
else
{
returnString = v.ToString();
}
if (mapping.IsSoap)
{
WriteXsiType(mapping.TypeName, mapping.Namespace);
Writer.WriteString(returnString);
return null;
}
else
{
return returnString;
}
}
private object GetMemberValue(object o, MemberInfo memberInfo)
{
if (memberInfo is PropertyInfo memberProperty)
{
return memberProperty.GetValue(o);
}
else if (memberInfo is FieldInfo memberField)
{
return memberField.GetValue(o);
}
throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
}
private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDesc memberTypeDesc, object container)
{
if (memberTypeDesc.IsAbstract) return;
if (memberTypeDesc.IsArrayLike)
{
var sb = new StringBuilder();
TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc;
bool canOptimizeWriteListSequence = CanOptimizeWriteListSequence(arrayElementTypeDesc);
if (attribute.IsList)
{
if (canOptimizeWriteListSequence)
{
Writer.WriteStartAttribute(null, attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty);
}
}
if (memberValue != null)
{
var a = (IEnumerable)memberValue;
IEnumerator e = a.GetEnumerator();
bool shouldAppendWhitespace = false;
if (e != null)
{
while (e.MoveNext())
{
object ai = e.Current;
if (attribute.IsList)
{
string stringValue;
if (attribute.Mapping is EnumMapping enumMapping)
{
stringValue = WriteEnumMethod(enumMapping, ai);
}
else
{
if (!WritePrimitiveValue(arrayElementTypeDesc, ai, true, out stringValue))
{
// #10593: Add More Tests for Serialization Code
Debug.Assert(ai is byte[]);
}
}
// check to see if we can write values of the attribute sequentially
if (canOptimizeWriteListSequence)
{
if (shouldAppendWhitespace)
{
Writer.WriteString(" ");
}
if (ai is byte[])
{
WriteValue((byte[])ai);
}
else
{
WriteValue(stringValue);
}
}
else
{
if (shouldAppendWhitespace)
{
sb.Append(" ");
}
sb.Append(stringValue);
}
}
else
{
WriteAttribute(ai, attribute, container);
}
shouldAppendWhitespace = true;
}
if (attribute.IsList)
{
// check to see if we can write values of the attribute sequentially
if (canOptimizeWriteListSequence)
{
Writer.WriteEndAttribute();
}
else
{
if (sb.Length != 0)
{
string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty;
WriteAttribute(attribute.Name, ns, sb.ToString());
}
}
}
}
}
}
else
{
WriteAttribute(memberValue, attribute, container);
}
}
private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) {
// check to see if we can write values of the attribute sequentially
// currently we have only one data type (XmlQualifiedName) that we can not write "inline",
// because we need to output xmlns:qx="..." for each of the qnames
return (listElementTypeDesc != null && listElementTypeDesc != QnameTypeDesc);
}
private void WriteAttribute(object memberValue, AttributeAccessor attribute, object container)
{
// TODO: this block is never hit by our tests.
if (attribute.Mapping is SpecialMapping special)
{
if (special.TypeDesc.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue)
{
WriteXmlAttribute((XmlNode)memberValue, container);
}
else
{
throw new InvalidOperationException(SR.XmlInternalError);
}
}
else
{
string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty;
WritePrimitive(WritePrimitiveMethodRequirement.WriteAttribute, attribute.Name, ns, attribute.Default, memberValue, attribute.Mapping, false, false, false);
}
}
private int FindXmlnsIndex(MemberMapping[] members)
{
for (int i = 0; i < members.Length; i++)
{
if (members[i].Xmlns == null)
continue;
return i;
}
return -1;
}
private bool WriteDerivedTypes(StructMapping mapping, string n, string ns, object o, bool isNullable)
{
Type t = o.GetType();
for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping)
{
if (t == derived.TypeDesc.Type)
{
WriteStructMethod(derived, n, ns, o, isNullable, needType: true);
return true;
}
if (WriteDerivedTypes(derived, n, ns, o, isNullable))
{
return true;
}
}
return false;
}
private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, string ns, object defaultValue, object o, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable)
{
TypeDesc typeDesc = mapping.TypeDesc;
bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport;
if (hasDefault)
{
if (mapping is EnumMapping)
{
if (((EnumMapping)mapping).IsFlags)
{
IEnumerable<string> defaultEnumFlagValues = defaultValue.ToString().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
string defaultEnumFlagString = string.Join(", ", defaultEnumFlagValues);
if (o.ToString() == defaultEnumFlagString)
return;
}
else
{
if (o.ToString() == defaultValue.ToString())
return;
}
}
else
{
if (IsDefaultValue(mapping, o, defaultValue, isNullable))
{
return;
}
}
}
XmlQualifiedName xmlQualifiedName = null;
if (writeXsiType)
{
xmlQualifiedName = new XmlQualifiedName(mapping.TypeName, mapping.Namespace);
}
string stringValue = null;
bool hasValidStringValue = false;
if (mapping is EnumMapping enumMapping)
{
stringValue = WriteEnumMethod(enumMapping, o);
hasValidStringValue = true;
}
else
{
hasValidStringValue = WritePrimitiveValue(typeDesc, o, isElement, out stringValue);
}
if (hasValidStringValue)
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteElementString))
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw))
{
WriteElementString(name, ns, stringValue, xmlQualifiedName);
}
else
{
WriteElementStringRaw(name, ns, stringValue, xmlQualifiedName);
}
}
else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteNullableStringLiteral))
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.Encoded))
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw))
{
WriteNullableStringEncoded(name, ns, stringValue, xmlQualifiedName);
}
else
{
WriteNullableStringEncodedRaw(name, ns, stringValue, xmlQualifiedName);
}
}
else
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw))
{
WriteNullableStringLiteral(name, ns, stringValue);
}
else
{
WriteNullableStringLiteralRaw(name, ns, stringValue);
}
}
}
else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteAttribute))
{
WriteAttribute(name, ns, stringValue);
}
else
{
// #10593: Add More Tests for Serialization Code
Debug.Assert(false);
}
}
else if (o is byte[] a)
{
if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteElementString | WritePrimitiveMethodRequirement.Raw))
{
WriteElementStringRaw(name, ns, FromByteArrayBase64(a));
}
else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteNullableStringLiteral | WritePrimitiveMethodRequirement.Raw))
{
WriteNullableStringLiteralRaw(name, ns, FromByteArrayBase64(a));
}
else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteAttribute))
{
WriteAttribute(name, ns, a);
}
else
{
// #10593: Add More Tests for Serialization Code
Debug.Assert(false);
}
}
else
{
// #10593: Add More Tests for Serialization Code
Debug.Assert(false);
}
}
private bool hasRequirement(WritePrimitiveMethodRequirement value, WritePrimitiveMethodRequirement requirement)
{
return (value & requirement) == requirement;
}
private bool IsDefaultValue(TypeMapping mapping, object o, object value, bool isNullable)
{
if (value is string && ((string)value).Length == 0)
{
string str = (string)o;
return str == null || str.Length == 0;
}
else
{
return value.Equals(o);
}
}
private bool WritePrimitiveValue(TypeDesc typeDesc, object o, bool isElement, out string stringValue)
{
if (typeDesc == StringTypeDesc || typeDesc.FormatterName == "String")
{
stringValue = (string)o;
return true;
}
else
{
if (!typeDesc.HasCustomFormatter)
{
stringValue = ConvertPrimitiveToString(o, typeDesc);
return true;
}
else if (o is byte[] && typeDesc.FormatterName == "ByteArrayHex")
{
stringValue = FromByteArrayHex((byte[])o);
return true;
}
else if (o is DateTime)
{
if (typeDesc.FormatterName == "DateTime")
{
stringValue = FromDateTime((DateTime)o);
return true;
}
else if (typeDesc.FormatterName == "Date")
{
stringValue = FromDate((DateTime)o);
return true;
}
else if (typeDesc.FormatterName == "Time")
{
stringValue = FromTime((DateTime)o);
return true;
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Invalid DateTime"));
}
}
else if (typeDesc == QnameTypeDesc)
{
stringValue = FromXmlQualifiedName((XmlQualifiedName)o);
return true;
}
else if (o is string)
{
switch (typeDesc.FormatterName)
{
case "XmlName":
stringValue = FromXmlName((string)o);
break;
case "XmlNCName":
stringValue = FromXmlNCName((string)o);
break;
case "XmlNmToken":
stringValue = FromXmlNmToken((string)o);
break;
case "XmlNmTokens":
stringValue = FromXmlNmTokens((string)o);
break;
default:
stringValue = null;
return false;
}
return true;
}
else if (o is char && typeDesc.FormatterName == "Char")
{
stringValue = FromChar((char)o);
return true;
}
else if (o is byte[])
{
// we deal with byte[] specially in WritePrimitive()
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
}
}
stringValue = null;
return false;
}
private string ConvertPrimitiveToString(object o, TypeDesc typeDesc)
{
string stringValue;
switch (typeDesc.FormatterName)
{
case "Boolean":
stringValue = XmlConvert.ToString((bool)o);
break;
case "Int32":
stringValue = XmlConvert.ToString((int)o);
break;
case "Int16":
stringValue = XmlConvert.ToString((short)o);
break;
case "Int64":
stringValue = XmlConvert.ToString((long)o);
break;
case "Single":
stringValue = XmlConvert.ToString((float)o);
break;
case "Double":
stringValue = XmlConvert.ToString((double)o);
break;
case "Decimal":
stringValue = XmlConvert.ToString((decimal)o);
break;
case "Byte":
stringValue = XmlConvert.ToString((byte)o);
break;
case "SByte":
stringValue = XmlConvert.ToString((sbyte)o);
break;
case "UInt16":
stringValue = XmlConvert.ToString((ushort)o);
break;
case "UInt32":
stringValue = XmlConvert.ToString((uint)o);
break;
case "UInt64":
stringValue = XmlConvert.ToString((ulong)o);
break;
// Types without direct mapping (ambiguous)
case "Guid":
stringValue = XmlConvert.ToString((Guid)o);
break;
case "Char":
stringValue = XmlConvert.ToString((char)o);
break;
case "TimeSpan":
stringValue = XmlConvert.ToString((TimeSpan)o);
break;
default:
stringValue = o.ToString();
break;
}
return stringValue;
}
private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMapping)
{
ElementAccessor element = xmlMembersMapping.Accessor;
MembersMapping mapping = (MembersMapping)element.Mapping;
bool hasWrapperElement = mapping.HasWrapperElement;
bool writeAccessors = mapping.WriteAccessors;
bool isRpc = xmlMembersMapping.IsSoap && writeAccessors;
WriteStartDocument();
if (!mapping.IsSoap)
{
TopLevelElement();
}
object[] p = (object[])o;
int pLength = p.Length;
if (hasWrapperElement)
{
WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty), mapping.IsSoap);
int xmlnsMember = FindXmlnsIndex(mapping.Members);
if (xmlnsMember >= 0)
{
MemberMapping member = mapping.Members[xmlnsMember];
var source = (XmlSerializerNamespaces)p[xmlnsMember];
if (pLength > xmlnsMember)
{
WriteNamespaceDeclarations(source);
}
}
for (int i = 0; i < mapping.Members.Length; i++)
{
MemberMapping member = mapping.Members[i];
if (member.Attribute != null && !member.Ignore)
{
object source = p[i];
bool? specifiedSource = null;
if (member.CheckSpecified != SpecifiedAccessor.None)
{
string memberNameSpecified = member.Name + "Specified";
for (int j = 0; j < Math.Min(pLength, mapping.Members.Length); j++)
{
if (mapping.Members[j].Name == memberNameSpecified)
{
specifiedSource = (bool) p[j];
break;
}
}
}
if (pLength > i && (specifiedSource == null || specifiedSource.Value))
{
WriteMember(source, member.Attribute, member.TypeDesc, null);
}
}
}
}
for (int i = 0; i < mapping.Members.Length; i++)
{
MemberMapping member = mapping.Members[i];
if (member.Xmlns != null)
continue;
if (member.Ignore)
continue;
bool? specifiedSource = null;
if (member.CheckSpecified != SpecifiedAccessor.None)
{
string memberNameSpecified = member.Name + "Specified";
for (int j = 0; j < Math.Min(pLength, mapping.Members.Length); j++)
{
if (mapping.Members[j].Name == memberNameSpecified)
{
specifiedSource = (bool)p[j];
break;
}
}
}
if (pLength > i)
{
if (specifiedSource == null || specifiedSource.Value)
{
object source = p[i];
object enumSource = null;
if (member.ChoiceIdentifier != null)
{
for (int j = 0; j < mapping.Members.Length; j++)
{
if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName)
{
enumSource = p[j];
break;
}
}
}
if (isRpc && member.IsReturnValue && member.Elements.Length > 0)
{
WriteRpcResult(member.Elements[0].Name, string.Empty);
}
// override writeAccessors choice when we've written a wrapper element
WriteMember(source, enumSource, member.ElementsSortedByDerivation, member.Text, member.ChoiceIdentifier, member.TypeDesc, writeAccessors || hasWrapperElement);
}
}
}
if (hasWrapperElement)
{
WriteEndElement();
}
if (element.IsSoap)
{
if (!hasWrapperElement && !writeAccessors)
{
// doc/bare case -- allow extra members
if (pLength > mapping.Members.Length)
{
for (int i = mapping.Members.Length; i < pLength; i++)
{
if (p[i] != null)
{
WritePotentiallyReferencingElement(null, null, p[i], p[i].GetType(), true, false);
}
}
}
}
WriteReferencedElements();
}
}
[Flags]
private enum WritePrimitiveMethodRequirement
{
None = 0,
Raw = 1,
WriteAttribute = 2,
WriteElementString = 4,
WriteNullableStringLiteral = 8,
Encoded = 16
}
}
internal class ReflectionXmlSerializationHelper
{
public static MemberInfo GetMember(Type declaringType, string memberName)
{
MemberInfo[] memberInfos = declaringType.GetMember(memberName);
if (memberInfos == null || memberInfos.Length == 0)
{
bool foundMatchedMember = false;
Type currentType = declaringType.BaseType;
while (currentType != null)
{
memberInfos = currentType.GetMember(memberName);
if (memberInfos != null && memberInfos.Length != 0)
{
foundMatchedMember = true;
break;
}
currentType = currentType.BaseType;
}
if (!foundMatchedMember)
{
throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"Could not find member named {memberName} of type {declaringType.ToString()}"));
}
declaringType = currentType;
}
MemberInfo memberInfo = memberInfos[0];
if (memberInfos.Length != 1)
{
foreach (MemberInfo mi in memberInfos)
{
if (declaringType == mi.DeclaringType)
{
memberInfo = mi;
break;
}
}
}
return memberInfo;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace AzureLinkboard.Web.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type PostAttachmentsCollectionRequest.
/// </summary>
public partial class PostAttachmentsCollectionRequest : BaseRequest, IPostAttachmentsCollectionRequest
{
/// <summary>
/// Constructs a new PostAttachmentsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public PostAttachmentsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Attachment to the collection via POST.
/// </summary>
/// <param name="attachment">The Attachment to add.</param>
/// <returns>The created Attachment.</returns>
public System.Threading.Tasks.Task<Attachment> AddAsync(Attachment attachment)
{
return this.AddAsync(attachment, CancellationToken.None);
}
/// <summary>
/// Adds the specified Attachment to the collection via POST.
/// </summary>
/// <param name="attachment">The Attachment to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Attachment.</returns>
public System.Threading.Tasks.Task<Attachment> AddAsync(Attachment attachment, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
attachment.ODataType = string.Concat("#", StringHelper.ConvertTypeToLowerCamelCase(attachment.GetType().FullName));
return this.SendAsync<Attachment>(attachment, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IPostAttachmentsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IPostAttachmentsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<PostAttachmentsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IPostAttachmentsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IPostAttachmentsCollectionRequest Expand(Expression<Func<Attachment, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IPostAttachmentsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IPostAttachmentsCollectionRequest Select(Expression<Func<Attachment, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IPostAttachmentsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IPostAttachmentsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IPostAttachmentsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IPostAttachmentsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
namespace MetroFramework.Drawing.Html.Core.Utils
{
/// <summary>
/// Defines HTML strings
/// </summary>
internal static class HtmlConstants
{
public const string A = "a";
// public const string ABBR = "ABBR";
// public const string ACRONYM = "ACRONYM";
// public const string ADDRESS = "ADDRESS";
// public const string APPLET = "APPLET";
// public const string AREA = "AREA";
// public const string B = "B";
// public const string BASE = "BASE";
// public const string BASEFONT = "BASEFONT";
// public const string BDO = "BDO";
// public const string BIG = "BIG";
// public const string BLOCKQUOTE = "BLOCKQUOTE";
// public const string BODY = "BODY";
// public const string BR = "BR";
// public const string BUTTON = "BUTTON";
public const string Caption = "caption";
// public const string CENTER = "CENTER";
// public const string CITE = "CITE";
// public const string CODE = "CODE";
public const string Col = "col";
public const string Colgroup = "colgroup";
public const string Display = "display";
// public const string DD = "DD";
// public const string DEL = "DEL";
// public const string DFN = "DFN";
// public const string DIR = "DIR";
// public const string DIV = "DIV";
// public const string DL = "DL";
// public const string DT = "DT";
// public const string EM = "EM";
// public const string FIELDSET = "FIELDSET";
public const string Font = "font";
// public const string FORM = "FORM";
// public const string FRAME = "FRAME";
// public const string FRAMESET = "FRAMESET";
// public const string H1 = "H1";
// public const string H2 = "H2";
// public const string H3 = "H3";
// public const string H4 = "H4";
// public const string H5 = "H5";
// public const string H6 = "H6";
// public const string HEAD = "HEAD";
public const string Hr = "hr";
// public const string HTML = "HTML";
// public const string I = "I";
public const string Iframe = "iframe";
public const string Img = "img";
// public const string INPUT = "INPUT";
// public const string INS = "INS";
// public const string ISINDEX = "ISINDEX";
// public const string KBD = "KBD";
// public const string LABEL = "LABEL";
// public const string LEGEND = "LEGEND";
public const string Li = "li";
// public const string LINK = "LINK";
// public const string MAP = "MAP";
// public const string MENU = "MENU";
// public const string META = "META";
// public const string NOFRAMES = "NOFRAMES";
// public const string NOSCRIPT = "NOSCRIPT";
// public const string OBJECT = "OBJECT";
// public const string OL = "OL";
// public const string OPTGROUP = "OPTGROUP";
// public const string OPTION = "OPTION";
// public const string P = "P";
// public const string PARAM = "PARAM";
// public const string PRE = "PRE";
// public const string Q = "Q";
// public const string S = "S";
// public const string SAMP = "SAMP";
// public const string SCRIPT = "SCRIPT";
// public const string SELECT = "SELECT";
// public const string SMALL = "SMALL";
// public const string SPAN = "SPAN";
// public const string STRIKE = "STRIKE";
// public const string STRONG = "STRONG";
public const string Style = "style";
// public const string SUB = "SUB";
// public const string SUP = "SUP";
public const string Table = "table";
public const string Tbody = "tbody";
public const string Td = "td";
// public const string TEXTAREA = "TEXTAREA";
public const string Tfoot = "tfoot";
public const string Th = "th";
public const string Thead = "thead";
// public const string TITLE = "TITLE";
public const string Tr = "tr";
// public const string TT = "TT";
// public const string U = "U";
// public const string UL = "UL";
// public const string VAR = "VAR";
// public const string abbr = "abbr";
// public const string accept = "accept";
// public const string accesskey = "accesskey";
// public const string action = "action";
public const string Align = "align";
// public const string alink = "alink";
// public const string alt = "alt";
// public const string archive = "archive";
// public const string axis = "axis";
public const string Background = "background";
public const string Bgcolor = "bgcolor";
public const string Border = "border";
public const string Bordercolor = "bordercolor";
public const string Cellpadding = "cellpadding";
public const string Cellspacing = "cellspacing";
// public const string char_ = "char";
// public const string charoff = "charoff";
// public const string charset = "charset";
// public const string checked_ = "checked";
// public const string cite = "cite";
public const string Class = "class";
// public const string classid = "classid";
// public const string clear = "clear";
// public const string code = "code";
// public const string codebase = "codebase";
// public const string codetype = "codetype";
public const string Color = "color";
// public const string cols = "cols";
// public const string colspan = "colspan";
// public const string compact = "compact";
// public const string content = "content";
// public const string coords = "coords";
// public const string data = "data";
// public const string datetime = "datetime";
// public const string declare = "declare";
// public const string defer = "defer";
public const string Dir = "dir";
// public const string disabled = "disabled";
// public const string enctype = "enctype";
public const string Face = "face";
// public const string for_ = "for";
// public const string frame = "frame";
// public const string frameborder = "frameborder";
// public const string headers = "headers";
public const string Height = "height";
public const string Href = "href";
// public const string hreflang = "hreflang";
public const string Hspace = "hspace";
// public const string http_equiv = "http-equiv";
// public const string id = "id";
// public const string ismap = "ismap";
// public const string label = "label";
// public const string lang = "lang";
// public const string language = "language";
// public const string link = "link";
// public const string longdesc = "longdesc";
// public const string marginheight = "marginheight";
// public const string marginwidth = "marginwidth";
// public const string maxlength = "maxlength";
// public const string media = "media";
// public const string method = "method";
// public const string multiple = "multiple";
// public const string name = "name";
// public const string nohref = "nohref";
// public const string noresize = "noresize";
// public const string noshade = "noshade";
public const string Nowrap = "nowrap";
// public const string object_ = "object";
// public const string onblur = "onblur";
// public const string onchange = "onchange";
// public const string onclick = "onclick";
// public const string ondblclick = "ondblclick";
// public const string onfocus = "onfocus";
// public const string onkeydown = "onkeydown";
// public const string onkeypress = "onkeypress";
// public const string onkeyup = "onkeyup";
// public const string onload = "onload";
// public const string onmousedown = "onmousedown";
// public const string onmousemove = "onmousemove";
// public const string onmouseout = "onmouseout";
// public const string onmouseover = "onmouseover";
// public const string onmouseup = "onmouseup";
// public const string onreset = "onreset";
// public const string onselect = "onselect";
// public const string onsubmit = "onsubmit";
// public const string onunload = "onunload";
// public const string profile = "profile";
// public const string prompt = "prompt";
// public const string readonly_ = "readonly";
// public const string rel = "rel";
// public const string rev = "rev";
// public const string rows = "rows";
// public const string rowspan = "rowspan";
// public const string rules = "rules";
// public const string scheme = "scheme";
// public const string scope = "scope";
// public const string scrolling = "scrolling";
// public const string selected = "selected";
// public const string shape = "shape";
public const string Size = "size";
// public const string span = "span";
// public const string src = "src";
// public const string standby = "standby";
// public const string start = "start";
// public const string style = "style";
// public const string summary = "summary";
// public const string tabindex = "tabindex";
// public const string target = "target";
// public const string text = "text";
// public const string title = "title";
// public const string type = "type";
// public const string usemap = "usemap";
public const string Valign = "valign";
// public const string value = "value";
// public const string valuetype = "valuetype";
// public const string version = "version";
// public const string vlink = "vlink";
public const string Vspace = "vspace";
public const string Width = "width";
public const string Left = "left";
public const string Right = "right";
// public const string top = "top";
public const string Center = "center";
// public const string middle = "middle";
// public const string bottom = "bottom";
public const string Justify = "justify";
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using NUnit.Framework;
using Newtonsoft.Json;
using GlmSharp;
// ReSharper disable InconsistentNaming
namespace GlmSharpTest.Generated.Vec4
{
[TestFixture]
public class UintVec4Test
{
[Test]
public void Constructors()
{
{
var v = new uvec4(1u);
Assert.AreEqual(1u, v.x);
Assert.AreEqual(1u, v.y);
Assert.AreEqual(1u, v.z);
Assert.AreEqual(1u, v.w);
}
{
var v = new uvec4(0u, 2u, 0u, 8u);
Assert.AreEqual(0u, v.x);
Assert.AreEqual(2u, v.y);
Assert.AreEqual(0u, v.z);
Assert.AreEqual(8u, v.w);
}
{
var v = new uvec4(new uvec2(1u, 5u));
Assert.AreEqual(1u, v.x);
Assert.AreEqual(5u, v.y);
Assert.AreEqual(0u, v.z);
Assert.AreEqual(0u, v.w);
}
{
var v = new uvec4(new uvec3(0u, 0u, 1u));
Assert.AreEqual(0u, v.x);
Assert.AreEqual(0u, v.y);
Assert.AreEqual(1u, v.z);
Assert.AreEqual(0u, v.w);
}
{
var v = new uvec4(new uvec4(2u, 6u, 2u, 1u));
Assert.AreEqual(2u, v.x);
Assert.AreEqual(6u, v.y);
Assert.AreEqual(2u, v.z);
Assert.AreEqual(1u, v.w);
}
}
[Test]
public void Indexer()
{
var v = new uvec4(2u, 4u, 8u, 2u);
Assert.AreEqual(2u, v[0]);
Assert.AreEqual(4u, v[1]);
Assert.AreEqual(8u, v[2]);
Assert.AreEqual(2u, v[3]);
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-2147483648]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[-2147483648] = 0u; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-1]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[-1] = 0u; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[4]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[4] = 0u; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[2147483647]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[2147483647] = 0u; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[5]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[5] = 0u; } );
v[3] = 0u;
Assert.AreEqual(0u, v[3]);
v[2] = 1u;
Assert.AreEqual(1u, v[2]);
v[3] = 2u;
Assert.AreEqual(2u, v[3]);
v[0] = 3u;
Assert.AreEqual(3u, v[0]);
v[2] = 4u;
Assert.AreEqual(4u, v[2]);
v[1] = 5u;
Assert.AreEqual(5u, v[1]);
v[2] = 6u;
Assert.AreEqual(6u, v[2]);
v[0] = 7u;
Assert.AreEqual(7u, v[0]);
v[0] = 8u;
Assert.AreEqual(8u, v[0]);
v[3] = 9u;
Assert.AreEqual(9u, v[3]);
}
[Test]
public void PropertyValues()
{
var v = new uvec4(8u, 5u, 6u, 5u);
var vals = v.Values;
Assert.AreEqual(8u, vals[0]);
Assert.AreEqual(5u, vals[1]);
Assert.AreEqual(6u, vals[2]);
Assert.AreEqual(5u, vals[3]);
Assert.That(vals.SequenceEqual(v.ToArray()));
}
[Test]
public void StaticProperties()
{
Assert.AreEqual(0u, uvec4.Zero.x);
Assert.AreEqual(0u, uvec4.Zero.y);
Assert.AreEqual(0u, uvec4.Zero.z);
Assert.AreEqual(0u, uvec4.Zero.w);
Assert.AreEqual(1u, uvec4.Ones.x);
Assert.AreEqual(1u, uvec4.Ones.y);
Assert.AreEqual(1u, uvec4.Ones.z);
Assert.AreEqual(1u, uvec4.Ones.w);
Assert.AreEqual(1u, uvec4.UnitX.x);
Assert.AreEqual(0u, uvec4.UnitX.y);
Assert.AreEqual(0u, uvec4.UnitX.z);
Assert.AreEqual(0u, uvec4.UnitX.w);
Assert.AreEqual(0u, uvec4.UnitY.x);
Assert.AreEqual(1u, uvec4.UnitY.y);
Assert.AreEqual(0u, uvec4.UnitY.z);
Assert.AreEqual(0u, uvec4.UnitY.w);
Assert.AreEqual(0u, uvec4.UnitZ.x);
Assert.AreEqual(0u, uvec4.UnitZ.y);
Assert.AreEqual(1u, uvec4.UnitZ.z);
Assert.AreEqual(0u, uvec4.UnitZ.w);
Assert.AreEqual(0u, uvec4.UnitW.x);
Assert.AreEqual(0u, uvec4.UnitW.y);
Assert.AreEqual(0u, uvec4.UnitW.z);
Assert.AreEqual(1u, uvec4.UnitW.w);
Assert.AreEqual(uint.MaxValue, uvec4.MaxValue.x);
Assert.AreEqual(uint.MaxValue, uvec4.MaxValue.y);
Assert.AreEqual(uint.MaxValue, uvec4.MaxValue.z);
Assert.AreEqual(uint.MaxValue, uvec4.MaxValue.w);
Assert.AreEqual(uint.MinValue, uvec4.MinValue.x);
Assert.AreEqual(uint.MinValue, uvec4.MinValue.y);
Assert.AreEqual(uint.MinValue, uvec4.MinValue.z);
Assert.AreEqual(uint.MinValue, uvec4.MinValue.w);
}
[Test]
public void Operators()
{
var v1 = new uvec4(0u, 2u, 9u, 5u);
var v2 = new uvec4(0u, 2u, 9u, 5u);
var v3 = new uvec4(5u, 9u, 2u, 0u);
Assert.That(v1 == new uvec4(v1));
Assert.That(v2 == new uvec4(v2));
Assert.That(v3 == new uvec4(v3));
Assert.That(v1 == v2);
Assert.That(v1 != v3);
Assert.That(v2 != v3);
}
[Test]
public void StringInterop()
{
var v = new uvec4(7u, 7u, 0u, 9u);
var s0 = v.ToString();
var s1 = v.ToString("#");
var v0 = uvec4.Parse(s0);
var v1 = uvec4.Parse(s1, "#");
Assert.AreEqual(v, v0);
Assert.AreEqual(v, v1);
var b0 = uvec4.TryParse(s0, out v0);
var b1 = uvec4.TryParse(s1, "#", out v1);
Assert.That(b0);
Assert.That(b1);
Assert.AreEqual(v, v0);
Assert.AreEqual(v, v1);
b0 = uvec4.TryParse(null, out v0);
Assert.False(b0);
b0 = uvec4.TryParse("", out v0);
Assert.False(b0);
b0 = uvec4.TryParse(s0 + ", 0", out v0);
Assert.False(b0);
Assert.Throws<NullReferenceException>(() => { uvec4.Parse(null); });
Assert.Throws<FormatException>(() => { uvec4.Parse(""); });
Assert.Throws<FormatException>(() => { uvec4.Parse(s0 + ", 0"); });
var s2 = v.ToString(";", CultureInfo.InvariantCulture);
Assert.That(s2.Length > 0);
var s3 = v.ToString("; ", "G");
var s4 = v.ToString("; ", "G", CultureInfo.InvariantCulture);
var v3 = uvec4.Parse(s3, "; ", NumberStyles.Number);
var v4 = uvec4.Parse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture);
Assert.AreEqual(v, v3);
Assert.AreEqual(v, v4);
var b4 = uvec4.TryParse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture, out v4);
Assert.That(b4);
Assert.AreEqual(v, v4);
}
[Test]
public void SerializationJson()
{
var v0 = new uvec4(8u, 7u, 0u, 6u);
var s0 = JsonConvert.SerializeObject(v0);
var v1 = JsonConvert.DeserializeObject<uvec4>(s0);
var s1 = JsonConvert.SerializeObject(v1);
Assert.AreEqual(v0, v1);
Assert.AreEqual(s0, s1);
}
[Test]
public void InvariantId()
{
{
var v0 = new uvec4(6u, 8u, 0u, 8u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec4(9u, 9u, 3u, 6u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec4(7u, 7u, 1u, 1u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec4(9u, 6u, 7u, 5u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec4(9u, 6u, 4u, 9u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec4(1u, 8u, 2u, 7u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec4(8u, 0u, 1u, 5u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec4(0u, 5u, 8u, 4u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec4(7u, 0u, 2u, 2u);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new uvec4(5u, 1u, 8u, 0u);
Assert.AreEqual(v0, +v0);
}
}
[Test]
public void InvariantDouble()
{
{
var v0 = new uvec4(1u, 9u, 9u, 6u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec4(5u, 0u, 9u, 3u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec4(5u, 1u, 7u, 7u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec4(7u, 6u, 8u, 2u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec4(7u, 8u, 9u, 0u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec4(0u, 9u, 1u, 6u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec4(8u, 7u, 2u, 2u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec4(6u, 3u, 0u, 4u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec4(6u, 7u, 1u, 9u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new uvec4(3u, 1u, 2u, 3u);
Assert.AreEqual(v0 + v0, 2 * v0);
}
}
[Test]
public void InvariantTriple()
{
{
var v0 = new uvec4(5u, 9u, 5u, 1u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec4(1u, 0u, 1u, 8u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec4(8u, 6u, 6u, 5u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec4(9u, 0u, 7u, 3u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec4(7u, 7u, 0u, 6u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec4(5u, 4u, 2u, 4u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec4(9u, 7u, 5u, 7u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec4(7u, 3u, 6u, 7u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec4(3u, 6u, 0u, 9u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new uvec4(9u, 9u, 5u, 8u);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
}
[Test]
public void InvariantCommutative()
{
{
var v0 = new uvec4(2u, 3u, 8u, 6u);
var v1 = new uvec4(2u, 0u, 3u, 5u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec4(0u, 5u, 5u, 5u);
var v1 = new uvec4(9u, 6u, 1u, 0u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec4(7u, 4u, 1u, 1u);
var v1 = new uvec4(7u, 4u, 0u, 7u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec4(6u, 1u, 0u, 6u);
var v1 = new uvec4(7u, 6u, 2u, 6u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec4(1u, 9u, 9u, 9u);
var v1 = new uvec4(8u, 0u, 8u, 3u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec4(9u, 4u, 4u, 0u);
var v1 = new uvec4(4u, 2u, 5u, 6u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec4(9u, 4u, 8u, 2u);
var v1 = new uvec4(4u, 6u, 9u, 7u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec4(3u, 1u, 0u, 1u);
var v1 = new uvec4(9u, 6u, 7u, 3u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec4(2u, 9u, 3u, 0u);
var v1 = new uvec4(6u, 2u, 1u, 6u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new uvec4(5u, 7u, 1u, 3u);
var v1 = new uvec4(0u, 9u, 2u, 3u);
Assert.AreEqual(v0 * v1, v1 * v0);
}
}
[Test]
public void InvariantAssociative()
{
{
var v0 = new uvec4(3u, 2u, 8u, 8u);
var v1 = new uvec4(8u, 4u, 3u, 6u);
var v2 = new uvec4(9u, 7u, 1u, 4u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec4(8u, 7u, 9u, 6u);
var v1 = new uvec4(9u, 7u, 9u, 6u);
var v2 = new uvec4(0u, 5u, 3u, 4u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec4(1u, 5u, 2u, 9u);
var v1 = new uvec4(3u, 0u, 6u, 0u);
var v2 = new uvec4(5u, 2u, 9u, 3u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec4(6u, 0u, 1u, 8u);
var v1 = new uvec4(7u, 1u, 8u, 4u);
var v2 = new uvec4(6u, 4u, 5u, 7u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec4(8u, 8u, 9u, 5u);
var v1 = new uvec4(3u, 0u, 2u, 7u);
var v2 = new uvec4(8u, 4u, 7u, 3u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec4(2u, 3u, 2u, 8u);
var v1 = new uvec4(0u, 1u, 8u, 6u);
var v2 = new uvec4(7u, 6u, 9u, 8u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec4(6u, 1u, 8u, 9u);
var v1 = new uvec4(7u, 8u, 8u, 7u);
var v2 = new uvec4(9u, 5u, 1u, 5u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec4(1u, 0u, 6u, 4u);
var v1 = new uvec4(0u, 1u, 4u, 2u);
var v2 = new uvec4(3u, 7u, 5u, 3u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec4(8u, 9u, 4u, 4u);
var v1 = new uvec4(5u, 9u, 9u, 1u);
var v2 = new uvec4(8u, 0u, 9u, 2u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new uvec4(2u, 2u, 9u, 9u);
var v1 = new uvec4(6u, 9u, 3u, 7u);
var v2 = new uvec4(1u, 6u, 7u, 9u);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
}
[Test]
public void TriangleInequality()
{
{
var v0 = new uvec4(0u, 6u, 5u, 2u);
var v1 = new uvec4(0u, 8u, 8u, 0u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec4(6u, 8u, 8u, 9u);
var v1 = new uvec4(7u, 3u, 6u, 7u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec4(4u, 7u, 7u, 2u);
var v1 = new uvec4(0u, 8u, 7u, 3u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec4(6u, 8u, 9u, 9u);
var v1 = new uvec4(3u, 2u, 9u, 2u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec4(9u, 2u, 0u, 4u);
var v1 = new uvec4(9u, 5u, 5u, 8u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec4(1u, 0u, 5u, 6u);
var v1 = new uvec4(9u, 4u, 1u, 4u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec4(3u, 8u, 1u, 1u);
var v1 = new uvec4(2u, 2u, 4u, 1u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec4(9u, 1u, 5u, 2u);
var v1 = new uvec4(9u, 9u, 6u, 4u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec4(9u, 6u, 0u, 4u);
var v1 = new uvec4(3u, 1u, 7u, 9u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new uvec4(1u, 8u, 1u, 9u);
var v1 = new uvec4(3u, 1u, 4u, 1u);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
}
[Test]
public void InvariantNorm()
{
{
var v0 = new uvec4(9u, 9u, 4u, 9u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec4(7u, 6u, 2u, 9u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec4(8u, 9u, 2u, 0u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec4(5u, 5u, 3u, 4u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec4(0u, 5u, 6u, 4u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec4(3u, 5u, 4u, 2u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec4(8u, 4u, 0u, 0u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec4(4u, 2u, 5u, 7u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec4(3u, 0u, 1u, 3u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new uvec4(0u, 9u, 7u, 9u);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
}
[Test]
public void RandomUniform0()
{
var random = new Random(659101511);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec4.Random(random, 2, 5);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 3, 1.0);
Assert.AreEqual(avg.y, 3, 1.0);
Assert.AreEqual(avg.z, 3, 1.0);
Assert.AreEqual(avg.w, 3, 1.0);
Assert.AreEqual(variance.x, 0.666666666666667, 3.0);
Assert.AreEqual(variance.y, 0.666666666666667, 3.0);
Assert.AreEqual(variance.z, 0.666666666666667, 3.0);
Assert.AreEqual(variance.w, 0.666666666666667, 3.0);
}
[Test]
public void RandomUniform1()
{
var random = new Random(2088017156);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec4.RandomUniform(random, 4, 9);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 6, 1.0);
Assert.AreEqual(avg.y, 6, 1.0);
Assert.AreEqual(avg.z, 6, 1.0);
Assert.AreEqual(avg.w, 6, 1.0);
Assert.AreEqual(variance.x, 2, 3.0);
Assert.AreEqual(variance.y, 2, 3.0);
Assert.AreEqual(variance.z, 2, 3.0);
Assert.AreEqual(variance.w, 2, 3.0);
}
[Test]
public void RandomUniform2()
{
var random = new Random(1369449154);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec4.Random(random, 1, 6);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 3, 1.0);
Assert.AreEqual(avg.y, 3, 1.0);
Assert.AreEqual(avg.z, 3, 1.0);
Assert.AreEqual(avg.w, 3, 1.0);
Assert.AreEqual(variance.x, 2, 3.0);
Assert.AreEqual(variance.y, 2, 3.0);
Assert.AreEqual(variance.z, 2, 3.0);
Assert.AreEqual(variance.w, 2, 3.0);
}
[Test]
public void RandomUniform3()
{
var random = new Random(650881152);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec4.RandomUniform(random, 4, 8);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 5.5, 1.0);
Assert.AreEqual(avg.y, 5.5, 1.0);
Assert.AreEqual(avg.z, 5.5, 1.0);
Assert.AreEqual(avg.w, 5.5, 1.0);
Assert.AreEqual(variance.x, 1.25, 3.0);
Assert.AreEqual(variance.y, 1.25, 3.0);
Assert.AreEqual(variance.z, 1.25, 3.0);
Assert.AreEqual(variance.w, 1.25, 3.0);
}
[Test]
public void RandomUniform4()
{
var random = new Random(1385889872);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec4.Random(random, 1, 5);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2.5, 1.0);
Assert.AreEqual(avg.y, 2.5, 1.0);
Assert.AreEqual(avg.z, 2.5, 1.0);
Assert.AreEqual(avg.w, 2.5, 1.0);
Assert.AreEqual(variance.x, 1.25, 3.0);
Assert.AreEqual(variance.y, 1.25, 3.0);
Assert.AreEqual(variance.z, 1.25, 3.0);
Assert.AreEqual(variance.w, 1.25, 3.0);
}
[Test]
public void RandomPoisson0()
{
var random = new Random(1006857680);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec4.RandomPoisson(random, 0.646168329821047);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 0.646168329821047, 1.0);
Assert.AreEqual(avg.y, 0.646168329821047, 1.0);
Assert.AreEqual(avg.z, 0.646168329821047, 1.0);
Assert.AreEqual(avg.w, 0.646168329821047, 1.0);
Assert.AreEqual(variance.x, 0.646168329821047, 3.0);
Assert.AreEqual(variance.y, 0.646168329821047, 3.0);
Assert.AreEqual(variance.z, 0.646168329821047, 3.0);
Assert.AreEqual(variance.w, 0.646168329821047, 3.0);
}
[Test]
public void RandomPoisson1()
{
var random = new Random(288289678);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec4.RandomPoisson(random, 2.16156477325669);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2.16156477325669, 1.0);
Assert.AreEqual(avg.y, 2.16156477325669, 1.0);
Assert.AreEqual(avg.z, 2.16156477325669, 1.0);
Assert.AreEqual(avg.w, 2.16156477325669, 1.0);
Assert.AreEqual(variance.x, 2.16156477325669, 3.0);
Assert.AreEqual(variance.y, 2.16156477325669, 3.0);
Assert.AreEqual(variance.z, 2.16156477325669, 3.0);
Assert.AreEqual(variance.w, 2.16156477325669, 3.0);
}
[Test]
public void RandomPoisson2()
{
var random = new Random(296510037);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec4.RandomPoisson(random, 0.60913191973657);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 0.60913191973657, 1.0);
Assert.AreEqual(avg.y, 0.60913191973657, 1.0);
Assert.AreEqual(avg.z, 0.60913191973657, 1.0);
Assert.AreEqual(avg.w, 0.60913191973657, 1.0);
Assert.AreEqual(variance.x, 0.60913191973657, 3.0);
Assert.AreEqual(variance.y, 0.60913191973657, 3.0);
Assert.AreEqual(variance.z, 0.60913191973657, 3.0);
Assert.AreEqual(variance.w, 0.60913191973657, 3.0);
}
[Test]
public void RandomPoisson3()
{
var random = new Random(1725425682);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec4.RandomPoisson(random, 2.26643048029692);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2.26643048029692, 1.0);
Assert.AreEqual(avg.y, 2.26643048029692, 1.0);
Assert.AreEqual(avg.z, 2.26643048029692, 1.0);
Assert.AreEqual(avg.w, 2.26643048029692, 1.0);
Assert.AreEqual(variance.x, 2.26643048029692, 3.0);
Assert.AreEqual(variance.y, 2.26643048029692, 3.0);
Assert.AreEqual(variance.z, 2.26643048029692, 3.0);
Assert.AreEqual(variance.w, 2.26643048029692, 3.0);
}
[Test]
public void RandomPoisson4()
{
var random = new Random(1733646041);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = uvec4.RandomPoisson(random, 0.713997626776806);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 0.713997626776806, 1.0);
Assert.AreEqual(avg.y, 0.713997626776806, 1.0);
Assert.AreEqual(avg.z, 0.713997626776806, 1.0);
Assert.AreEqual(avg.w, 0.713997626776806, 1.0);
Assert.AreEqual(variance.x, 0.713997626776806, 3.0);
Assert.AreEqual(variance.y, 0.713997626776806, 3.0);
Assert.AreEqual(variance.z, 0.713997626776806, 3.0);
Assert.AreEqual(variance.w, 0.713997626776806, 3.0);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Runtime.CompilerServices;
using System.Linq;
using ICSharpCode.SharpZipLib.Zip;
using Umbraco.Core;
using Umbraco.Core.Logging;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.propertytype;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
using System.Diagnostics;
using umbraco.cms.businesslogic.macro;
using umbraco.cms.businesslogic.template;
using Umbraco.Core.IO;
namespace umbraco.cms.businesslogic.packager
{
/// <summary>
/// The packager is a component which enables sharing of both data and functionality components between different umbraco installations.
///
/// The output is a .umb (a zip compressed file) which contains the exported documents/medias/macroes/documenttypes (etc.)
/// in a Xml document, along with the physical files used (images/usercontrols/xsl documents etc.)
///
/// Partly implemented, import of packages is done, the export is *under construction*.
/// </summary>
/// <remarks>
/// Ruben Verborgh 31/12/2007: I had to change some code, I marked my changes with "DATALAYER".
/// Reason: @@IDENTITY can't be used with the new datalayer.
/// I wasn't able to test the code, since I'm not aware how the code functions.
/// </remarks>
public class Installer
{
private string _name;
private string _version;
private string _url;
private string _license;
private string _licenseUrl;
private int _reqMajor;
private int _reqMinor;
private int _reqPatch;
private string _authorName;
private string _authorUrl;
private string _readme;
private string _control;
private bool _containUnsecureFiles = false;
private List<string> _unsecureFiles = new List<string>();
private bool _containsMacroConflict = false;
private Dictionary<string, string> _conflictingMacroAliases = new Dictionary<string, string>();
private bool _containsTemplateConflict = false;
private Dictionary<string, string> _conflictingTemplateAliases = new Dictionary<string, string>();
private bool _containsStyleSheetConflict = false;
private Dictionary<string, string> _conflictingStyleSheetNames = new Dictionary<string, string>();
private ArrayList _macros = new ArrayList();
private XmlDocument _packageConfig;
public string Name { get { return _name; } }
public string Version { get { return _version; } }
public string Url { get { return _url; } }
public string License { get { return _license; } }
public string LicenseUrl { get { return _licenseUrl; } }
public string Author { get { return _authorName; } }
public string AuthorUrl { get { return _authorUrl; } }
public string ReadMe { get { return _readme; } }
public string Control { get { return _control; } }
public bool ContainsMacroConflict { get { return _containsMacroConflict; } }
public IDictionary<string, string> ConflictingMacroAliases { get { return _conflictingMacroAliases; } }
public bool ContainsUnsecureFiles { get { return _containUnsecureFiles; } }
public List<string> UnsecureFiles { get { return _unsecureFiles; } }
public bool ContainsTemplateConflicts { get { return _containsTemplateConflict; } }
public IDictionary<string, string> ConflictingTemplateAliases { get { return _conflictingTemplateAliases; } }
public bool ContainsStyleSheeConflicts { get { return _containsStyleSheetConflict; } }
public IDictionary<string, string> ConflictingStyleSheetNames { get { return _conflictingStyleSheetNames; } }
public int RequirementsMajor { get { return _reqMajor; } }
public int RequirementsMinor { get { return _reqMinor; } }
public int RequirementsPatch { get { return _reqPatch; } }
/// <summary>
/// The xmldocument, describing the contents of a package.
/// </summary>
public XmlDocument Config
{
get { return _packageConfig; }
}
/// <summary>
/// Constructor
/// </summary>
public Installer()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="Name">The name of the package</param>
/// <param name="Version">The version of the package</param>
/// <param name="Url">The url to a descriptionpage</param>
/// <param name="License">The license under which the package is released (preferably GPL ;))</param>
/// <param name="LicenseUrl">The url to a licensedescription</param>
/// <param name="Author">The original author of the package</param>
/// <param name="AuthorUrl">The url to the Authors website</param>
/// <param name="RequirementsMajor">Umbraco version major</param>
/// <param name="RequirementsMinor">Umbraco version minor</param>
/// <param name="RequirementsPatch">Umbraco version patch</param>
/// <param name="Readme">The readme text</param>
/// <param name="Control">The name of the usercontrol used to configure the package after install</param>
public Installer(string Name, string Version, string Url, string License, string LicenseUrl, string Author, string AuthorUrl, int RequirementsMajor, int RequirementsMinor, int RequirementsPatch, string Readme, string Control)
{
_name = Name;
_version = Version;
_url = Url;
_license = License;
_licenseUrl = LicenseUrl;
_reqMajor = RequirementsMajor;
_reqMinor = RequirementsMinor;
_reqPatch = RequirementsPatch;
_authorName = Author;
_authorUrl = AuthorUrl;
_readme = Readme;
_control = Control;
}
#region Public Methods
/// <summary>
/// Adds the macro to the package
/// </summary>
/// <param name="MacroToAdd">Macro to add</param>
[Obsolete("This method does nothing but add the macro to an ArrayList that is never used, so don't call this method.")]
public void AddMacro(Macro MacroToAdd)
{
_macros.Add(MacroToAdd);
}
/// <summary>
/// Imports the specified package
/// </summary>
/// <param name="InputFile">Filename of the umbracopackage</param>
/// <returns></returns>
public string Import(string InputFile)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Importing package file " + InputFile,
() => "Package file " + InputFile + "imported"))
{
string tempDir = "";
if (File.Exists(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + InputFile)))
{
FileInfo fi = new FileInfo(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + InputFile));
// Check if the file is a valid package
if (fi.Extension.ToLower() == ".umb")
{
try
{
tempDir = UnPack(fi.FullName);
LoadConfig(tempDir);
}
catch (Exception unpackE)
{
throw new Exception("Error unpacking extension...", unpackE);
}
}
else
throw new Exception("Error - file isn't a package (doesn't have a .umb extension). Check if the file automatically got named '.zip' upon download.");
}
else
throw new Exception("Error - file not found. Could find file named '" + IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + InputFile) + "'");
return tempDir;
}
}
public int CreateManifest(string tempDir, string guid, string repoGuid)
{
//This is the new improved install rutine, which chops up the process into 3 steps, creating the manifest, moving files, and finally handling umb objects
string _packName = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/name"));
string _packAuthor = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/name"));
string _packAuthorUrl = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/website"));
string _packVersion = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/version"));
string _packReadme = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/readme"));
string _packLicense = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/license "));
string _packUrl = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/url "));
bool _enableSkins = false;
string _skinRepoGuid = "";
if (_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/enableSkins") != null)
{
XmlNode _skinNode = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/enableSkins");
_enableSkins = bool.Parse(xmlHelper.GetNodeValue(_skinNode));
if (_skinNode.Attributes["repository"] != null && !string.IsNullOrEmpty(_skinNode.Attributes["repository"].Value))
_skinRepoGuid = _skinNode.Attributes["repository"].Value;
}
//Create a new package instance to record all the installed package adds - this is the same format as the created packages has.
//save the package meta data
packager.InstalledPackage insPack = packager.InstalledPackage.MakeNew(_packName);
insPack.Data.Author = _packAuthor;
insPack.Data.AuthorUrl = _packAuthorUrl;
insPack.Data.Version = _packVersion;
insPack.Data.Readme = _packReadme;
insPack.Data.License = _packLicense;
insPack.Data.Url = _packUrl;
//skinning
insPack.Data.EnableSkins = _enableSkins;
insPack.Data.SkinRepoGuid = string.IsNullOrEmpty(_skinRepoGuid) ? Guid.Empty : new Guid(_skinRepoGuid);
insPack.Data.PackageGuid = guid; //the package unique key.
insPack.Data.RepositoryGuid = repoGuid; //the repository unique key, if the package is a file install, the repository will not get logged.
insPack.Save();
return insPack.Data.Id;
}
public void InstallFiles(int packageId, string tempDir)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Installing package files for package id " + packageId + " into temp folder " + tempDir,
() => "Package file installation complete for package id " + packageId))
{
//retrieve the manifest to continue installation
packager.InstalledPackage insPack = packager.InstalledPackage.GetById(packageId);
// Move files
//string virtualBasePath = System.Web.HttpContext.Current.Request.ApplicationPath;
string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//file"))
{
//we enclose the whole file-moving to ensure that the entire installer doesn't crash
try
{
String destPath = GetFileName(basePath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")));
String sourceFile = GetFileName(tempDir, xmlHelper.GetNodeValue(n.SelectSingleNode("guid")));
String destFile = GetFileName(destPath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
// Create the destination directory if it doesn't exist
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
//If a file with this name exists, delete it
else if (File.Exists(destFile))
File.Delete(destFile);
// Move the file
File.Move(sourceFile, destFile);
//PPH log file install
insPack.Data.Files.Add(xmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")) + "/" + xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
}
catch (Exception ex)
{
LogHelper.Error<Installer>("Package install error", ex);
}
}
insPack.Save();
}
}
public void InstallBusinessLogic(int packageId, string tempDir)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Installing business logic for package id " + packageId + " into temp folder " + tempDir,
() => "Package business logic installation complete for package id " + packageId))
{
//retrieve the manifest to continue installation
var insPack = InstalledPackage.GetById(packageId);
//bool saveNeeded = false;
// Get current user, with a fallback
var currentUser = new User(0);
if (string.IsNullOrEmpty(BasePages.UmbracoEnsuredPage.umbracoUserContextID) == false)
{
if (BasePages.UmbracoEnsuredPage.ValidateUserContextID(BasePages.UmbracoEnsuredPage.umbracoUserContextID))
{
currentUser = User.GetCurrent();
}
}
//Xml as XElement which is used with the new PackagingService
var rootElement = _packageConfig.DocumentElement.GetXElement();
var packagingService = ApplicationContext.Current.Services.PackagingService;
#region DataTypes
var dataTypeElement = rootElement.Descendants("DataTypes").FirstOrDefault();
if(dataTypeElement != null)
{
var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement, currentUser.Id);
foreach (var dataTypeDefinition in dataTypeDefinitions)
{
insPack.Data.DataTypes.Add(dataTypeDefinition.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
/*foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//DataType"))
{
cms.businesslogic.datatype.DataTypeDefinition newDtd = cms.businesslogic.datatype.DataTypeDefinition.Import(n);
if (newDtd != null)
{
insPack.Data.DataTypes.Add(newDtd.Id.ToString());
saveNeeded = true;
}
}*/
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Languages
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//Language"))
{
language.Language newLang = language.Language.Import(n);
if (newLang != null)
{
insPack.Data.Languages.Add(newLang.id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Dictionary items
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("./DictionaryItems/DictionaryItem"))
{
Dictionary.DictionaryItem newDi = Dictionary.DictionaryItem.Import(n);
if (newDi != null)
{
insPack.Data.DictionaryItems.Add(newDi.id.ToString());
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Macros
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//macro"))
{
Macro m = Macro.Import(n);
if (m != null)
{
insPack.Data.Macros.Add(m.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Templates
var templateElement = rootElement.Descendants("Templates").FirstOrDefault();
if (templateElement != null)
{
var templates = packagingService.ImportTemplates(templateElement, currentUser.Id);
foreach (var template in templates)
{
insPack.Data.Templates.Add(template.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
/*foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Templates/Template"))
{
var t = Template.Import(n, currentUser);
insPack.Data.Templates.Add(t.Id.ToString());
saveNeeded = true;
}
if (saveNeeded) { insPack.Save(); saveNeeded = false; }
//NOTE: SD: I'm pretty sure the only thing the below script does is ensure that the Master template Id is set
// in the database, but this is also duplicating the saving of the design content since the above Template.Import
// already does this. I've left this for now because I'm not sure the reprocussions of removing it but seems there
// is a lot of excess database calls happening here.
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Templates/Template"))
{
string master = xmlHelper.GetNodeValue(n.SelectSingleNode("Master"));
Template t = Template.GetByAlias(xmlHelper.GetNodeValue(n.SelectSingleNode("Alias")));
if (master.Trim() != "")
{
var masterTemplate = Template.GetByAlias(master);
if (masterTemplate != null)
{
t.MasterTemplate = Template.GetByAlias(master).Id;
//SD: This appears to always just save an empty template because the design isn't set yet
// this fixes an issue now that we have MVC because if there is an empty template and MVC is
// the default, it will create a View not a master page and then the system will try to route via
// MVC which means that the package will not work anymore.
// The code below that imports the templates should suffice because it's actually importing
// template data not just blank data.
//if (UmbracoSettings.UseAspNetMasterPages)
// t.SaveMasterPageFile(t.Design);
}
}
// Master templates can only be generated when their master is known
if (UmbracoSettings.UseAspNetMasterPages)
{
t.ImportDesign(xmlHelper.GetNodeValue(n.SelectSingleNode("Design")));
t.SaveMasterPageFile(t.Design);
}
}*/
#endregion
#region DocumentTypes
//Check whether the root element is a doc type rather then a complete package
var docTypeElement = rootElement.Name.LocalName.Equals("DocumentType") ||
rootElement.Name.LocalName.Equals("DocumentTypes")
? rootElement
: rootElement.Descendants("DocumentTypes").FirstOrDefault();
if (docTypeElement != null)
{
var contentTypes = packagingService.ImportContentTypes(docTypeElement, currentUser.Id);
foreach (var contentType in contentTypes)
{
insPack.Data.Documenttypes.Add(contentType.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
/*foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("DocumentTypes/DocumentType"))
{
ImportDocumentType(n, currentUser, false);
saveNeeded = true;
}
if (saveNeeded) { insPack.Save(); saveNeeded = false; }
// Add documenttype structure
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("DocumentTypes/DocumentType"))
{
DocumentType dt = DocumentType.GetByAlias(xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Alias")));
if (dt != null)
{
ArrayList allowed = new ArrayList();
foreach (XmlNode structure in n.SelectNodes("Structure/DocumentType"))
{
DocumentType dtt = DocumentType.GetByAlias(xmlHelper.GetNodeValue(structure));
if (dtt != null)
allowed.Add(dtt.Id);
}
int[] adt = new int[allowed.Count];
for (int i = 0; i < allowed.Count; i++)
adt[i] = (int)allowed[i];
dt.AllowedChildContentTypeIDs = adt;
dt.Save();
//PPH we log the document type install here.
insPack.Data.Documenttypes.Add(dt.Id.ToString());
saveNeeded = true;
}
}
if (saveNeeded) { insPack.Save(); saveNeeded = false; }*/
#endregion
#region Stylesheets
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Stylesheets/Stylesheet"))
{
StyleSheet s = StyleSheet.Import(n, currentUser);
insPack.Data.Stylesheets.Add(s.Id.ToString());
//saveNeeded = true;
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Documents
var documentElement = rootElement.Descendants("DocumentSet").FirstOrDefault();
if (documentElement != null)
{
var content = packagingService.ImportContent(documentElement, -1, currentUser.Id);
var firstContentItem = content.First();
insPack.Data.ContentNodeId = firstContentItem.Id.ToString(CultureInfo.InvariantCulture);
}
/*foreach (XmlElement n in _packageConfig.DocumentElement.SelectNodes("Documents/DocumentSet [@importMode = 'root']/*"))
{
insPack.Data.ContentNodeId = cms.businesslogic.web.Document.Import(-1, currentUser, n).ToString();
}*/
#endregion
#region Package Actions
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Actions/Action"))
{
if (n.Attributes["undo"] == null || n.Attributes["undo"].Value == "true")
{
insPack.Data.Actions += n.OuterXml;
}
if (n.Attributes["runat"] != null && n.Attributes["runat"].Value == "install")
{
try
{
PackageAction.RunPackageAction(insPack.Data.Name, n.Attributes["alias"].Value, n);
}
catch
{
}
}
}
#endregion
// Trigger update of Apps / Trees config.
// (These are ApplicationStartupHandlers so just instantiating them will trigger them)
new ApplicationRegistrar();
new ApplicationTreeRegistrar();
insPack.Save();
}
}
/// <summary>
/// Remove the temp installation folder
/// </summary>
/// <param name="packageId"></param>
/// <param name="tempDir"></param>
public void InstallCleanUp(int packageId, string tempDir)
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, true);
}
}
/// <summary>
/// Invoking this method installs the entire current package
/// </summary>
/// <param name="tempDir">Temporary folder where the package's content are extracted to</param>
/// <param name="guid"></param>
/// <param name="repoGuid"></param>
public void Install(string tempDir, string guid, string repoGuid)
{
//PPH added logging of installs, this adds all install info in the installedPackages config file.
string packName = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/name"));
string packAuthor = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/name"));
string packAuthorUrl = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/website"));
string packVersion = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/version"));
string packReadme = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/readme"));
string packLicense = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/license "));
//Create a new package instance to record all the installed package adds - this is the same format as the created packages has.
//save the package meta data
var insPack = InstalledPackage.MakeNew(packName);
insPack.Data.Author = packAuthor;
insPack.Data.AuthorUrl = packAuthorUrl;
insPack.Data.Version = packVersion;
insPack.Data.Readme = packReadme;
insPack.Data.License = packLicense;
insPack.Data.PackageGuid = guid; //the package unique key.
insPack.Data.RepositoryGuid = repoGuid; //the repository unique key, if the package is a file install, the repository will not get logged.
// Get current user, with a fallback
var currentUser = new User(0);
if (string.IsNullOrEmpty(BasePages.UmbracoEnsuredPage.umbracoUserContextID) == false)
{
if (BasePages.UmbracoEnsuredPage.ValidateUserContextID(BasePages.UmbracoEnsuredPage.umbracoUserContextID))
{
currentUser = User.GetCurrent();
}
}
//Xml as XElement which is used with the new PackagingService
var rootElement = _packageConfig.DocumentElement.GetXElement();
var packagingService = ApplicationContext.Current.Services.PackagingService;
#region DataTypes
var dataTypeElement = rootElement.Descendants("DataTypes").FirstOrDefault();
if(dataTypeElement != null)
{
var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement, currentUser.Id);
foreach (var dataTypeDefinition in dataTypeDefinitions)
{
insPack.Data.DataTypes.Add(dataTypeDefinition.Id.ToString(CultureInfo.InvariantCulture));
}
}
#endregion
#region Install Languages
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//Language"))
{
language.Language newLang = language.Language.Import(n);
if (newLang != null)
insPack.Data.Languages.Add(newLang.id.ToString());
}
#endregion
#region Install Dictionary Items
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("./DictionaryItems/DictionaryItem"))
{
Dictionary.DictionaryItem newDi = Dictionary.DictionaryItem.Import(n);
if (newDi != null)
insPack.Data.DictionaryItems.Add(newDi.id.ToString());
}
#endregion
#region Install Macros
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//macro"))
{
Macro m = Macro.Import(n);
if (m != null)
insPack.Data.Macros.Add(m.Id.ToString());
}
#endregion
#region Move files
string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//file"))
{
String destPath = GetFileName(basePath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")));
String sourceFile = GetFileName(tempDir, xmlHelper.GetNodeValue(n.SelectSingleNode("guid")));
String destFile = GetFileName(destPath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
// Create the destination directory if it doesn't exist
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
// If a file with this name exists, delete it
else if (File.Exists(destFile))
File.Delete(destFile);
// Move the file
File.Move(sourceFile, destFile);
//PPH log file install
insPack.Data.Files.Add(xmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")) + "/" + xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
}
#endregion
#region Install Templates
var templateElement = rootElement.Descendants("Templates").FirstOrDefault();
if (templateElement != null)
{
var templates = packagingService.ImportTemplates(templateElement, currentUser.Id);
foreach (var template in templates)
{
insPack.Data.Templates.Add(template.Id.ToString(CultureInfo.InvariantCulture));
}
}
/*foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Templates/Template"))
{
Template t = Template.MakeNew(xmlHelper.GetNodeValue(n.SelectSingleNode("Name")), currentUser);
t.Alias = xmlHelper.GetNodeValue(n.SelectSingleNode("Alias"));
t.ImportDesign(xmlHelper.GetNodeValue(n.SelectSingleNode("Design")));
insPack.Data.Templates.Add(t.Id.ToString());
}
// Add master templates
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Templates/Template"))
{
string master = xmlHelper.GetNodeValue(n.SelectSingleNode("Master"));
Template t = Template.GetByAlias(xmlHelper.GetNodeValue(n.SelectSingleNode("Alias")));
if (master.Trim() != "")
{
Template masterTemplate = Template.GetByAlias(master);
if (masterTemplate != null)
{
t.MasterTemplate = Template.GetByAlias(master).Id;
if (UmbracoSettings.UseAspNetMasterPages)
t.SaveMasterPageFile(t.Design);
}
}
// Master templates can only be generated when their master is known
if (UmbracoSettings.UseAspNetMasterPages)
{
t.ImportDesign(xmlHelper.GetNodeValue(n.SelectSingleNode("Design")));
t.SaveMasterPageFile(t.Design);
}
}*/
#endregion
#region Install DocumentTypes
//Check whether the root element is a doc type rather then a complete package
var docTypeElement = rootElement.Name.LocalName.Equals("DocumentType") ||
rootElement.Name.LocalName.Equals("DocumentTypes")
? rootElement
: rootElement.Descendants("DocumentTypes").FirstOrDefault();
if (docTypeElement != null)
{
var contentTypes = packagingService.ImportContentTypes(docTypeElement, currentUser.Id);
foreach (var contentType in contentTypes)
{
insPack.Data.Documenttypes.Add(contentType.Id.ToString(CultureInfo.InvariantCulture));
}
}
/*foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("DocumentTypes/DocumentType"))
{
ImportDocumentType(n, currentUser, false);
}
// Add documenttype structure
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("DocumentTypes/DocumentType"))
{
DocumentType dt = DocumentType.GetByAlias(xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Alias")));
if (dt != null)
{
ArrayList allowed = new ArrayList();
foreach (XmlNode structure in n.SelectNodes("Structure/DocumentType"))
{
DocumentType dtt = DocumentType.GetByAlias(xmlHelper.GetNodeValue(structure));
allowed.Add(dtt.Id);
}
int[] adt = new int[allowed.Count];
for (int i = 0; i < allowed.Count; i++)
adt[i] = (int)allowed[i];
dt.AllowedChildContentTypeIDs = adt;
//PPH we log the document type install here.
insPack.Data.Documenttypes.Add(dt.Id.ToString());
}
}*/
#endregion
#region Install Stylesheets
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Stylesheets/Stylesheet"))
{
StyleSheet s = StyleSheet.MakeNew(
currentUser,
xmlHelper.GetNodeValue(n.SelectSingleNode("Name")),
xmlHelper.GetNodeValue(n.SelectSingleNode("FileName")),
xmlHelper.GetNodeValue(n.SelectSingleNode("Content")));
foreach (XmlNode prop in n.SelectNodes("Properties/Property"))
{
StylesheetProperty sp = StylesheetProperty.MakeNew(
xmlHelper.GetNodeValue(prop.SelectSingleNode("Name")),
s,
currentUser);
sp.Alias = xmlHelper.GetNodeValue(prop.SelectSingleNode("Alias"));
sp.value = xmlHelper.GetNodeValue(prop.SelectSingleNode("Value"));
}
s.saveCssToFile();
s.Save();
insPack.Data.Stylesheets.Add(s.Id.ToString());
}
#endregion
#region Install Documents
var documentElement = rootElement.Descendants("DocumentSet").FirstOrDefault();
if(documentElement != null)
{
var content = packagingService.ImportContent(documentElement, -1, currentUser.Id);
var firstContentItem = content.First();
insPack.Data.ContentNodeId = firstContentItem.Id.ToString(CultureInfo.InvariantCulture);
}
/*foreach (XmlElement n in _packageConfig.DocumentElement.SelectNodes("Documents/DocumentSet [@importMode = 'root']/*"))
{
Document.Import(-1, currentUser, n);
//PPH todo log document install...
}*/
#endregion
#region Install Actions
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Actions/Action [@runat != 'uninstall']"))
{
try
{
PackageAction.RunPackageAction(packName, n.Attributes["alias"].Value, n);
}
catch { }
}
//saving the uninstall actions untill the package is uninstalled.
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Actions/Action [@undo != false()]"))
{
insPack.Data.Actions += n.OuterXml;
}
#endregion
insPack.Save();
}
/// <summary>
/// Reads the configuration of the package from the configuration xmldocument
/// </summary>
/// <param name="tempDir">The folder to which the contents of the package is extracted</param>
public void LoadConfig(string tempDir)
{
_packageConfig = new XmlDocument();
_packageConfig.Load(tempDir + Path.DirectorySeparatorChar + "package.xml");
_name = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/name").FirstChild.Value;
_version = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/version").FirstChild.Value;
_url = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/url").FirstChild.Value;
_license = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").FirstChild.Value;
_licenseUrl = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").Attributes.GetNamedItem("url").Value;
_reqMajor = int.Parse(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/major").FirstChild.Value);
_reqMinor = int.Parse(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/minor").FirstChild.Value);
_reqPatch = int.Parse(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/patch").FirstChild.Value);
_authorName = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/name").FirstChild.Value;
_authorUrl = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/website").FirstChild.Value;
string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//file"))
{
bool badFile = false;
string destPath = GetFileName(basePath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")));
string destFile = GetFileName(destPath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
if (destPath.ToLower().Contains(IOHelper.DirSepChar + "app_code"))
badFile = true;
if (destPath.ToLower().Contains(IOHelper.DirSepChar + "bin"))
badFile = true;
if (destFile.ToLower().EndsWith(".dll"))
badFile = true;
if (badFile)
{
_containUnsecureFiles = true;
_unsecureFiles.Add(xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
}
}
//this will check for existing macros with the same alias
//since we will not overwrite on import it's a good idea to inform the user what will be overwritten
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//macro"))
{
var alias = n.SelectSingleNode("alias").InnerText;
if (!string.IsNullOrEmpty(alias))
{
try
{
var m = new Macro(alias);
this._containsMacroConflict = true;
this._conflictingMacroAliases.Add(m.Name, alias);
}
catch (IndexOutOfRangeException) { } //thrown when the alias doesn't exist in the DB, ie - macro not there
}
}
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Templates/Template"))
{
var alias = n.SelectSingleNode("Alias").InnerText;
if (!string.IsNullOrEmpty(alias))
{
var t = Template.GetByAlias(alias);
if (t != null)
{
this._containsTemplateConflict = true;
this._conflictingTemplateAliases.Add(t.Text, alias);
}
}
}
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Stylesheets/Stylesheet"))
{
var alias = n.SelectSingleNode("Name").InnerText;
if (!string.IsNullOrEmpty(alias))
{
var s = StyleSheet.GetByName(alias);
if (s != null)
{
this._containsStyleSheetConflict = true;
this._conflictingStyleSheetNames.Add(s.Text, alias);
}
}
}
try
{
_readme = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/readme"));
}
catch { }
try
{
_control = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/control"));
}
catch { }
}
/// <summary>
/// This uses the old method of fetching and only supports the packages.umbraco.org repository.
/// </summary>
/// <param name="Package"></param>
/// <returns></returns>
public string Fetch(Guid Package)
{
// Check for package directory
if (!Directory.Exists(IOHelper.MapPath(SystemDirectories.Packages)))
Directory.CreateDirectory(IOHelper.MapPath(SystemDirectories.Packages));
var wc = new System.Net.WebClient();
wc.DownloadFile(
"http://" + UmbracoSettings.PackageServer + "/fetch?package=" + Package.ToString(),
IOHelper.MapPath(SystemDirectories.Packages + "/" + Package.ToString() + ".umb"));
return "packages\\" + Package.ToString() + ".umb";
}
#endregion
#region Public Static Methods
[Obsolete("This method is empty, so calling it will have no effect whatsoever.")]
public static void updatePackageInfo(Guid Package, int VersionMajor, int VersionMinor, int VersionPatch, User User)
{
//Why does this even exist?
}
[Obsolete("Use ApplicationContext.Current.Services.PackagingService.ImportContentTypes instead")]
public static void ImportDocumentType(XmlNode n, User u, bool ImportStructure)
{
var element = n.GetXElement();
var contentTypes = ApplicationContext.Current.Services.PackagingService.ImportContentTypes(element, ImportStructure, u.Id);
}
#endregion
#region Private Methods
/// <summary>
/// Gets the name of the file in the specified path.
/// Corrects possible problems with slashes that would result from a simple concatenation.
/// Can also be used to concatenate paths.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="fileName">Name of the file.</param>
/// <returns>The name of the file in the specified path.</returns>
private static String GetFileName(String path, string fileName)
{
// virtual dir support
fileName = IOHelper.FindFile(fileName);
if (path.Contains("[$"))
{
//this is experimental and undocumented...
path = path.Replace("[$UMBRACO]", SystemDirectories.Umbraco);
path = path.Replace("[$UMBRACOCLIENT]", SystemDirectories.UmbracoClient);
path = path.Replace("[$CONFIG]", SystemDirectories.Config);
path = path.Replace("[$DATA]", SystemDirectories.Data);
}
//to support virtual dirs we try to lookup the file...
path = IOHelper.FindFile(path);
Debug.Assert(path != null && path.Length >= 1);
Debug.Assert(fileName != null && fileName.Length >= 1);
path = path.Replace('/', '\\');
fileName = fileName.Replace('/', '\\');
// Does filename start with a slash? Does path end with one?
bool fileNameStartsWithSlash = (fileName[0] == Path.DirectorySeparatorChar);
bool pathEndsWithSlash = (path[path.Length - 1] == Path.DirectorySeparatorChar);
// Path ends with a slash
if (pathEndsWithSlash)
{
if (!fileNameStartsWithSlash)
// No double slash, just concatenate
return path + fileName;
else
// Double slash, exclude that of the file
return path + fileName.Substring(1);
}
else
{
if (fileNameStartsWithSlash)
// Required slash specified, just concatenate
return path + fileName;
else
// Required slash missing, add it
return path + Path.DirectorySeparatorChar + fileName;
}
}
private static int FindDataTypeDefinitionFromType(ref Guid dtId)
{
int dfId = 0;
foreach (datatype.DataTypeDefinition df in datatype.DataTypeDefinition.GetAll())
if (df.DataType.Id == dtId)
{
dfId = df.Id;
break;
}
return dfId;
}
private static string UnPack(string zipName)
{
// Unzip
string tempDir = IOHelper.MapPath(SystemDirectories.Data) + Path.DirectorySeparatorChar + Guid.NewGuid().ToString();
Directory.CreateDirectory(tempDir);
var s = new ZipInputStream(File.OpenRead(zipName));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string fileName = Path.GetFileName(theEntry.Name);
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(tempDir + Path.DirectorySeparatorChar + fileName);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
// Clean up
s.Close();
File.Delete(zipName);
return tempDir;
}
#endregion
}
public class Package
{
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
public Package()
{
}
/// <summary>
/// Initialize package install status object by specifying the internal id of the installation.
/// The id is specific to the local umbraco installation and cannot be used to identify the package in general.
/// Use the Package(Guid) constructor to check whether a package has been installed
/// </summary>
/// <param name="Id">The internal id.</param>
public Package(int Id)
{
initialize(Id);
}
public Package(Guid Id)
{
int installStatusId = SqlHelper.ExecuteScalar<int>(
"select id from umbracoInstalledPackages where package = @package and upgradeId = 0",
SqlHelper.CreateParameter("@package", Id));
if (installStatusId > 0)
initialize(installStatusId);
else
throw new ArgumentException("Package with id '" + Id.ToString() + "' is not installed");
}
private void initialize(int id)
{
IRecordsReader dr =
SqlHelper.ExecuteReader(
"select id, uninstalled, upgradeId, installDate, userId, package, versionMajor, versionMinor, versionPatch from umbracoInstalledPackages where id = @id",
SqlHelper.CreateParameter("@id", id));
if (dr.Read())
{
Id = id;
Uninstalled = dr.GetBoolean("uninstalled");
UpgradeId = dr.GetInt("upgradeId");
InstallDate = dr.GetDateTime("installDate");
User = User.GetUser(dr.GetInt("userId"));
PackageId = dr.GetGuid("package");
VersionMajor = dr.GetInt("versionMajor");
VersionMinor = dr.GetInt("versionMinor");
VersionPatch = dr.GetInt("versionPatch");
}
dr.Close();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Save()
{
IParameter[] values = {
SqlHelper.CreateParameter("@uninstalled", Uninstalled),
SqlHelper.CreateParameter("@upgradeId", UpgradeId),
SqlHelper.CreateParameter("@installDate", InstallDate),
SqlHelper.CreateParameter("@userId", User.Id),
SqlHelper.CreateParameter("@versionMajor", VersionMajor),
SqlHelper.CreateParameter("@versionMinor", VersionMinor),
SqlHelper.CreateParameter("@versionPatch", VersionPatch),
SqlHelper.CreateParameter("@id", Id)
};
// check if package status exists
if (Id == 0)
{
// The method is synchronized
SqlHelper.ExecuteNonQuery("INSERT INTO umbracoInstalledPackages (uninstalled, upgradeId, installDate, userId, versionMajor, versionMinor, versionPatch) VALUES (@uninstalled, @upgradeId, @installDate, @userId, @versionMajor, @versionMinor, @versionPatch)", values);
Id = SqlHelper.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoInstalledPackages");
}
SqlHelper.ExecuteNonQuery(
"update umbracoInstalledPackages set " +
"uninstalled = @uninstalled, " +
"upgradeId = @upgradeId, " +
"installDate = @installDate, " +
"userId = @userId, " +
"versionMajor = @versionMajor, " +
"versionMinor = @versionMinor, " +
"versionPatch = @versionPatch " +
"where id = @id",
values);
}
private bool _uninstalled;
public bool Uninstalled
{
get { return _uninstalled; }
set { _uninstalled = value; }
}
private User _user;
public User User
{
get { return _user; }
set { _user = value; }
}
private DateTime _installDate;
public DateTime InstallDate
{
get { return _installDate; }
set { _installDate = value; }
}
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private int _upgradeId;
public int UpgradeId
{
get { return _upgradeId; }
set { _upgradeId = value; }
}
private Guid _packageId;
public Guid PackageId
{
get { return _packageId; }
set { _packageId = value; }
}
private int _versionPatch;
public int VersionPatch
{
get { return _versionPatch; }
set { _versionPatch = value; }
}
private int _versionMinor;
public int VersionMinor
{
get { return _versionMinor; }
set { _versionMinor = value; }
}
private int _versionMajor;
public int VersionMajor
{
get { return _versionMajor; }
set { _versionMajor = value; }
}
}
}
| |
//Copyright 2014 Spin Services Limited
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using SS.Integration.Adapter.Interface;
using SportingSolutions.Udapi.Sdk;
using SportingSolutions.Udapi.Sdk.Interfaces;
using log4net;
using System.Threading;
using SportingSolutions.Udapi.Sdk.Exceptions;
namespace SS.Integration.Adapter.UdapiClient
{
public class UdapiServiceFacade : IServiceFacade
{
private readonly ILog _logger = LogManager.GetLogger(typeof(UdapiServiceFacade));
private readonly SessionContainer _sessionContainer;
private readonly ISettings _settings;
private IService _service;
private bool _isClosing;
private readonly IReconnectStrategy _reconnectStrategy;
public UdapiServiceFacade(IReconnectStrategy reconnectStrategy, ISettings settings)
{
_sessionContainer = new SessionContainer(new Credentials
{
UserName = settings.User,
Password = settings.Password
}, new Uri(settings.Url));
_settings = settings;
_isClosing = false;
_reconnectStrategy = reconnectStrategy;
_reconnectStrategy.SetSessionInitialiser(Init);
}
public void Connect()
{
try
{
_isClosing = false;
IsConnected = false;
Init(true);
}
catch (Exception)
{
_logger.Error("Unable to connect to the GTP-UDAPI");
throw;
}
}
public void Disconnect()
{
lock (this)
{
_isClosing = true;
_service = null;
IsConnected = false;
}
_logger.Info("Disconnect from GTP-UDAPI");
}
public bool IsConnected { get; private set; }
public IEnumerable<IFeature> GetSports()
{
return _service == null ? null : _service.GetFeatures();
}
public List<IResourceFacade> GetResources(string featureName)
{
if (_service == null)
return null;
var resourceFacade = new List<IResourceFacade>();
var udapiFeature = _service.GetFeature(featureName);
if (udapiFeature != null)
{
var udapiResources = udapiFeature.GetResources();
resourceFacade.AddRange(udapiResources.Select(udapiResource => new UdapiResourceFacade(udapiResource, featureName, _reconnectStrategy,_settings.EchoDelay,_settings.EchoInterval)));
}
return resourceFacade;
}
public IResourceFacade GetResource(string featureName, string resourceName)
{
if (_service == null)
return null;
IResourceFacade resource = null;
var feature = _service.GetFeature(featureName);
if (feature != null)
{
var udapiResource = feature.GetResource(resourceName);
if (udapiResource != null)
{
resource = new UdapiResourceFacade(udapiResource, featureName, _reconnectStrategy, _settings.EchoDelay, _settings.EchoInterval);
}
}
return resource;
}
// TODO: Refactor!
private void Init(bool connectSession)
{
var counter = 0;
Exception lastException = null;
var retryDelay = _settings.StartingRetryDelay; //ms
while (counter < _settings.MaxRetryAttempts)
{
lock (this)
{
if (_isClosing)
{
_service = null;
IsConnected = false;
return;
}
}
try
{
if (connectSession)
{
_sessionContainer.ReleaseSession();
}
_service = _sessionContainer.Session.GetService("UnifiedDataAPI");
if (_service == null)
{
_logger.Fatal("Udapi Service proxy could not be created");
}
IsConnected = true;
return;
}
catch (NotAuthenticatedException wex)
{
lastException = wex;
counter++;
if (counter == _settings.MaxRetryAttempts)
{
_logger.Error(
String.Format("Failed to successfully execute Sporting Solutions method after all {0} attempts",
_settings.MaxRetryAttempts), wex);
}
else
{
_logger.WarnFormat("Failed to successfully execute Sporting Solutions method on attempt {0}. Stack Trace:{1}", counter, wex.StackTrace);
}
connectSession = true;
}
catch (Exception ex)
{
counter++;
if (counter == _settings.MaxRetryAttempts)
{
_logger.Error(
String.Format("Failed to successfully execute Sporting Solutions method after all {0} attempts",
_settings.MaxRetryAttempts), ex);
}
else
{
_logger.WarnFormat("Failed to successfully execute Sporting Solutions method on attempt {0}. Stack Trace:{1}", counter, ex.StackTrace);
}
}
retryDelay = 2 * retryDelay;
if (retryDelay > _settings.MaxRetryDelay)
{
retryDelay = _settings.MaxRetryDelay;
}
_logger.DebugFormat("Retrying Sporting Solutions API in {0} ms", retryDelay);
Thread.Sleep(retryDelay);
}
throw lastException ?? new Exception();
}
}
}
| |
using System;
using UnityEngine;
namespace UnityStandardAssets.CinematicEffects
{
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Rendering/Screen Space Reflection")]
#if UNITY_5_4_OR_NEWER
[ImageEffectAllowedInSceneView]
#endif
public class ScreenSpaceReflection : MonoBehaviour
{
public enum SSRDebugMode
{
None = 0,
IncomingRadiance = 1,
SSRResult = 2,
FinalGlossyTerm = 3,
SSRMask = 4,
Roughness = 5,
BaseColor = 6,
SpecColor = 7,
Reflectivity = 8,
ReflectionProbeOnly = 9,
ReflectionProbeMinusSSR = 10,
SSRMinusReflectionProbe = 11,
NoGlossy = 12,
NegativeNoGlossy = 13,
MipLevel = 14,
}
public enum SSRResolution
{
FullResolution = 0,
HalfTraceFullResolve = 1,
HalfResolution = 2,
}
[Serializable]
public struct SSRSettings
{
[AttributeUsage(AttributeTargets.Field)]
public class LayoutAttribute : PropertyAttribute
{}
[Layout]
public BasicSettings basicSettings;
[Layout]
public ReflectionSettings reflectionSettings;
[Layout]
public AdvancedSettings advancedSettings;
[Layout]
public DebugSettings debugSettings;
private static readonly SSRSettings s_Performance = new SSRSettings
{
basicSettings = new BasicSettings
{
screenEdgeFading = 0,
maxDistance = 10.0f,
fadeDistance = 10.0f,
reflectionMultiplier = 1.0f,
enableHDR = false,
additiveReflection = false
},
reflectionSettings = new ReflectionSettings
{
maxSteps = 64,
rayStepSize = 4,
widthModifier = 0.5f,
smoothFallbackThreshold = 0.4f,
distanceBlur = 1.0f,
fresnelFade = 0.2f,
fresnelFadePower = 2.0f,
smoothFallbackDistance = 0.05f,
},
advancedSettings = new AdvancedSettings
{
useTemporalConfidence = false,
temporalFilterStrength = 0.0f,
treatBackfaceHitAsMiss = false,
allowBackwardsRays = false,
traceBehindObjects = true,
highQualitySharpReflections = false,
traceEverywhere = false,
resolution = SSRResolution.HalfResolution,
bilateralUpsample = false,
improveCorners = false,
reduceBanding = false,
highlightSuppression = false
},
debugSettings = new DebugSettings
{
debugMode = SSRDebugMode.None
}
};
private static readonly SSRSettings s_Default = new SSRSettings
{
basicSettings = new BasicSettings
{
screenEdgeFading = 0.03f,
maxDistance = 100.0f,
fadeDistance = 100.0f,
reflectionMultiplier = 1.0f,
enableHDR = true,
additiveReflection = false,
},
reflectionSettings = new ReflectionSettings
{
maxSteps = 128,
rayStepSize = 3,
widthModifier = 0.5f,
smoothFallbackThreshold = 0.2f,
distanceBlur = 1.0f,
fresnelFade = 0.2f,
fresnelFadePower = 2.0f,
smoothFallbackDistance = 0.05f,
},
advancedSettings = new AdvancedSettings
{
useTemporalConfidence = true,
temporalFilterStrength = 0.7f,
treatBackfaceHitAsMiss = false,
allowBackwardsRays = false,
traceBehindObjects = true,
highQualitySharpReflections = true,
traceEverywhere = true,
resolution = SSRResolution.HalfTraceFullResolve,
bilateralUpsample = true,
improveCorners = true,
reduceBanding = true,
highlightSuppression = false
},
debugSettings = new DebugSettings
{
debugMode = SSRDebugMode.None
}
};
private static readonly SSRSettings s_HighQuality = new SSRSettings
{
basicSettings = new BasicSettings
{
screenEdgeFading = 0.03f,
maxDistance = 100.0f,
fadeDistance = 100.0f,
reflectionMultiplier = 1.0f,
enableHDR = true,
additiveReflection = false,
},
reflectionSettings = new ReflectionSettings
{
maxSteps = 512,
rayStepSize = 1,
widthModifier = 0.5f,
smoothFallbackThreshold = 0.2f,
distanceBlur = 1.0f,
fresnelFade = 0.2f,
fresnelFadePower = 2.0f,
smoothFallbackDistance = 0.05f,
},
advancedSettings = new AdvancedSettings
{
useTemporalConfidence = true,
temporalFilterStrength = 0.7f,
treatBackfaceHitAsMiss = false,
allowBackwardsRays = false,
traceBehindObjects = true,
highQualitySharpReflections = true,
traceEverywhere = true,
resolution = SSRResolution.HalfTraceFullResolve,
bilateralUpsample = true,
improveCorners = true,
reduceBanding = true,
highlightSuppression = false
},
debugSettings = new DebugSettings
{
debugMode = SSRDebugMode.None
}
};
public static SSRSettings performanceSettings
{
get { return s_Performance; }
}
public static SSRSettings defaultSettings
{
get { return s_Default; }
}
public static SSRSettings highQualitySettings
{
get { return s_HighQuality; }
}
}
[Serializable]
public struct BasicSettings
{
/// BASIC SETTINGS
[Tooltip("Nonphysical multiplier for the SSR reflections. 1.0 is physically based.")]
[Range(0.0f, 2.0f)]
public float reflectionMultiplier;
[Tooltip("Maximum reflection distance in world units.")]
[Range(0.5f, 1000.0f)]
public float maxDistance;
[Tooltip("How far away from the maxDistance to begin fading SSR.")]
[Range(0.0f, 1000.0f)]
public float fadeDistance;
[Tooltip("Higher = fade out SSRR near the edge of the screen so that reflections don't pop under camera motion.")]
[Range(0.0f, 1.0f)]
public float screenEdgeFading;
[Tooltip("Enable for better reflections of very bright objects at a performance cost")]
public bool enableHDR;
// When enabled, we just add our reflections on top of the existing ones. This is physically incorrect, but several
// popular demos and games have taken this approach, and it does hide some artifacts.
[Tooltip("Add reflections on top of existing ones. Not physically correct.")]
public bool additiveReflection;
}
[Serializable]
public struct ReflectionSettings
{
/// REFLECTIONS
[Tooltip("Max raytracing length.")]
[Range(16, 2048)]
public int maxSteps;
[Tooltip("Log base 2 of ray tracing coarse step size. Higher traces farther, lower gives better quality silhouettes.")]
[Range(0, 4)]
public int rayStepSize;
[Tooltip("Typical thickness of columns, walls, furniture, and other objects that reflection rays might pass behind.")]
[Range(0.01f, 10.0f)]
public float widthModifier;
[Tooltip("Increase if reflections flicker on very rough surfaces.")]
[Range(0.0f, 1.0f)]
public float smoothFallbackThreshold;
[Tooltip("Start falling back to non-SSR value solution at smoothFallbackThreshold - smoothFallbackDistance, with full fallback occuring at smoothFallbackThreshold.")]
[Range(0.0f, 0.2f)]
public float smoothFallbackDistance;
[Tooltip("Amplify Fresnel fade out. Increase if floor reflections look good close to the surface and bad farther 'under' the floor.")]
[Range(0.0f, 1.0f)]
public float fresnelFade;
[Tooltip("Higher values correspond to a faster Fresnel fade as the reflection changes from the grazing angle.")]
[Range(0.1f, 10.0f)]
public float fresnelFadePower;
[Tooltip("Controls how blurry reflections get as objects are further from the camera. 0 is constant blur no matter trace distance or distance from camera. 1 fully takes into account both factors.")]
[Range(0.0f, 1.0f)]
public float distanceBlur;
}
[Serializable]
public struct AdvancedSettings
{
/// ADVANCED
[Range(0.0f, 0.99f)]
[Tooltip("Increase to decrease flicker in scenes; decrease to prevent ghosting (especially in dynamic scenes). 0 gives maximum performance.")]
public float temporalFilterStrength;
[Tooltip("Enable to limit ghosting from applying the temporal filter.")]
public bool useTemporalConfidence;
[Tooltip("Enable to allow rays to pass behind objects. This can lead to more screen-space reflections, but the reflections are more likely to be wrong.")]
public bool traceBehindObjects;
[Tooltip("Enable to increase quality of the sharpest reflections (through filtering), at a performance cost.")]
public bool highQualitySharpReflections;
[Tooltip("Improves quality in scenes with varying smoothness, at a potential performance cost.")]
public bool traceEverywhere;
[Tooltip("Enable to force more surfaces to use reflection probes if you see streaks on the sides of objects or bad reflections of their backs.")]
public bool treatBackfaceHitAsMiss;
[Tooltip("Enable for a performance gain in scenes where most glossy objects are horizontal, like floors, water, and tables. Leave on for scenes with glossy vertical objects.")]
public bool allowBackwardsRays;
[Tooltip("Improve visual fidelity of reflections on rough surfaces near corners in the scene, at the cost of a small amount of performance.")]
public bool improveCorners;
[Tooltip("Half resolution SSRR is much faster, but less accurate. Quality can be reclaimed for some performance by doing the resolve at full resolution.")]
public SSRResolution resolution;
[Tooltip("Drastically improves reflection reconstruction quality at the expense of some performance.")]
public bool bilateralUpsample;
[Tooltip("Improve visual fidelity of mirror reflections at the cost of a small amount of performance.")]
public bool reduceBanding;
[Tooltip("Enable to limit the effect a few bright pixels can have on rougher surfaces")]
public bool highlightSuppression;
}
[Serializable]
public struct DebugSettings
{
/// DEBUG
[Tooltip("Various Debug Visualizations")]
public SSRDebugMode debugMode;
}
[SerializeField]
public SSRSettings settings = SSRSettings.defaultSettings;
///////////// Unexposed Variables //////////////////
// Perf optimization we still need to test across platforms
[Tooltip("Enable to try and bypass expensive bilateral upsampling away from edges. There is a slight performance hit for generating the edge buffers, but a potentially high performance savings from bypassing bilateral upsampling where it is unneeded. Test on your target platforms to see if performance improves.")]
private bool useEdgeDetector = false;
// Debug variable, useful for forcing all surfaces in a scene to reflection with arbitrary sharpness/roughness
[Range(-4.0f, 4.0f)]
private float mipBias = 0.0f;
// Flag for whether to knock down the reflection term by occlusion stored in the gbuffer. Currently consistently gives
// better results when true, so this flag is private for now.
private bool useOcclusion = true;
// When enabled, all filtering is performed at the highest resolution. This is extraordinarily slow, and should only be used during development.
private bool fullResolutionFiltering = false;
// Crude sky fallback, feature-gated until next revision
private bool fallbackToSky = false;
// For next release; will improve quality at the expense of performance
private bool computeAverageRayDistance = false;
// Internal values for temporal filtering
private bool m_HasInformationFromPreviousFrame;
private Matrix4x4 m_PreviousWorldToCameraMatrix;
private RenderTexture m_PreviousDepthBuffer;
private RenderTexture m_PreviousHitBuffer;
private RenderTexture m_PreviousReflectionBuffer;
[NonSerialized]
private RenderTextureUtility m_RTU = new RenderTextureUtility();
[SerializeField]
private Shader m_Shader;
public Shader shader
{
get
{
if (m_Shader == null)
m_Shader = Shader.Find("Hidden/ScreenSpaceReflection");
return m_Shader;
}
}
private Material m_Material;
public Material material
{
get
{
if (m_Material == null)
m_Material = ImageEffectHelper.CheckShaderAndCreateMaterial(shader);
return m_Material;
}
}
// Shader pass indices used by the effect
private enum PassIndex
{
RayTraceStep1 = 0,
RayTraceStep2 = 1,
RayTraceStep4 = 2,
RayTraceStep8 = 3,
RayTraceStep16 = 4,
CompositeFinal = 5,
Blur = 6,
CompositeSSR = 7,
Blit = 8,
EdgeGeneration = 9,
MinMipGeneration = 10,
HitPointToReflections = 11,
BilateralKeyPack = 12,
BlitDepthAsCSZ = 13,
TemporalFilter = 14,
AverageRayDistanceGeneration = 15,
PoissonBlur = 16,
}
private void OnEnable()
{
if (!ImageEffectHelper.IsSupported(shader, false, true, this))
{
enabled = false;
return;
}
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
}
void OnDisable()
{
if (m_Material)
DestroyImmediate(m_Material);
if (m_PreviousDepthBuffer)
DestroyImmediate(m_PreviousDepthBuffer);
if (m_PreviousHitBuffer)
DestroyImmediate(m_PreviousHitBuffer);
if (m_PreviousReflectionBuffer)
DestroyImmediate(m_PreviousReflectionBuffer);
m_Material = null;
m_PreviousDepthBuffer = null;
m_PreviousHitBuffer = null;
m_PreviousReflectionBuffer = null;
}
private void PreparePreviousBuffers(int w, int h)
{
if (m_PreviousDepthBuffer != null)
{
if ((m_PreviousDepthBuffer.width != w) || (m_PreviousDepthBuffer.height != h))
{
DestroyImmediate(m_PreviousDepthBuffer);
DestroyImmediate(m_PreviousHitBuffer);
DestroyImmediate(m_PreviousReflectionBuffer);
m_PreviousDepthBuffer = null;
m_PreviousHitBuffer = null;
m_PreviousReflectionBuffer = null;
}
}
if (m_PreviousDepthBuffer == null)
{
m_PreviousDepthBuffer = new RenderTexture(w, h, 0, RenderTextureFormat.RFloat);
m_PreviousHitBuffer = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf);
m_PreviousReflectionBuffer = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf);
}
}
[ImageEffectOpaque]
public void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (material == null)
{
Graphics.Blit(source, destination);
return;
}
if (m_HasInformationFromPreviousFrame)
{
m_HasInformationFromPreviousFrame = (m_PreviousDepthBuffer != null) &&
(source.width == m_PreviousDepthBuffer.width) &&
(source.height == m_PreviousDepthBuffer.height);
}
bool doTemporalFilterThisFrame = m_HasInformationFromPreviousFrame && settings.advancedSettings.temporalFilterStrength > 0.0;
m_HasInformationFromPreviousFrame = false;
// Not using deferred shading? Just blit source to destination.
if (Camera.current.actualRenderingPath != RenderingPath.DeferredShading)
{
Graphics.Blit(source, destination);
return;
}
var rtW = source.width;
var rtH = source.height;
// RGB: Normals, A: Roughness.
// Has the nice benefit of allowing us to control the filtering mode as well.
RenderTexture bilateralKeyTexture = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.ARGB32);
bilateralKeyTexture.filterMode = FilterMode.Point;
Graphics.Blit(source, bilateralKeyTexture, material, (int)PassIndex.BilateralKeyPack);
material.SetTexture("_NormalAndRoughnessTexture", bilateralKeyTexture);
float sWidth = source.width;
float sHeight = source.height;
Vector2 sourceToTempUV = new Vector2(sWidth / rtW, sHeight / rtH);
int downsampleAmount = (settings.advancedSettings.resolution == SSRResolution.FullResolution) ? 1 : 2;
rtW = rtW / downsampleAmount;
rtH = rtH / downsampleAmount;
material.SetVector("_SourceToTempUV", new Vector4(sourceToTempUV.x, sourceToTempUV.y, 1.0f / sourceToTempUV.x, 1.0f / sourceToTempUV.y));
Matrix4x4 P = GetComponent<Camera>().projectionMatrix;
Vector4 projInfo = new Vector4
((-2.0f / (sWidth * P[0])),
(-2.0f / (sHeight * P[5])),
((1.0f - P[2]) / P[0]),
((1.0f + P[6]) / P[5]));
/** The height in pixels of a 1m object if viewed from 1m away. */
float pixelsPerMeterAtOneMeter = sWidth / (-2.0f * (float)(Math.Tan(GetComponent<Camera>().fieldOfView / 180.0 * Math.PI * 0.5)));
material.SetFloat("_PixelsPerMeterAtOneMeter", pixelsPerMeterAtOneMeter);
float sx = sWidth / 2.0f;
float sy = sHeight / 2.0f;
Matrix4x4 warpToScreenSpaceMatrix = new Matrix4x4();
warpToScreenSpaceMatrix.SetRow(0, new Vector4(sx, 0.0f, 0.0f, sx));
warpToScreenSpaceMatrix.SetRow(1, new Vector4(0.0f, sy, 0.0f, sy));
warpToScreenSpaceMatrix.SetRow(2, new Vector4(0.0f, 0.0f, 1.0f, 0.0f));
warpToScreenSpaceMatrix.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
Matrix4x4 projectToPixelMatrix = warpToScreenSpaceMatrix * P;
material.SetVector("_ScreenSize", new Vector2(sWidth, sHeight));
material.SetVector("_ReflectionBufferSize", new Vector2(rtW, rtH));
Vector2 invScreenSize = new Vector2((float)(1.0 / sWidth), (float)(1.0 / sHeight));
Matrix4x4 worldToCameraMatrix = GetComponent<Camera>().worldToCameraMatrix;
Matrix4x4 cameraToWorldMatrix = GetComponent<Camera>().worldToCameraMatrix.inverse;
material.SetVector("_InvScreenSize", invScreenSize);
material.SetVector("_ProjInfo", projInfo); // used for unprojection
material.SetMatrix("_ProjectToPixelMatrix", projectToPixelMatrix);
material.SetMatrix("_WorldToCameraMatrix", worldToCameraMatrix);
material.SetMatrix("_CameraToWorldMatrix", cameraToWorldMatrix);
material.SetInt("_EnableRefine", settings.advancedSettings.reduceBanding ? 1 : 0);
material.SetInt("_AdditiveReflection", settings.basicSettings.additiveReflection ? 1 : 0);
material.SetInt("_ImproveCorners", settings.advancedSettings.improveCorners ? 1 : 0);
material.SetFloat("_ScreenEdgeFading", settings.basicSettings.screenEdgeFading);
material.SetFloat("_MipBias", mipBias);
material.SetInt("_UseOcclusion", useOcclusion ? 1 : 0);
material.SetInt("_BilateralUpsampling", settings.advancedSettings.bilateralUpsample ? 1 : 0);
material.SetInt("_FallbackToSky", fallbackToSky ? 1 : 0);
material.SetInt("_TreatBackfaceHitAsMiss", settings.advancedSettings.treatBackfaceHitAsMiss ? 1 : 0);
material.SetInt("_AllowBackwardsRays", settings.advancedSettings.allowBackwardsRays ? 1 : 0);
material.SetInt("_TraceEverywhere", settings.advancedSettings.traceEverywhere ? 1 : 0);
float z_f = GetComponent<Camera>().farClipPlane;
float z_n = GetComponent<Camera>().nearClipPlane;
Vector3 cameraClipInfo = (float.IsPositiveInfinity(z_f)) ?
new Vector3(z_n, -1.0f, 1.0f) :
new Vector3(z_n * z_f, z_n - z_f, z_f);
material.SetVector("_CameraClipInfo", cameraClipInfo);
material.SetFloat("_MaxRayTraceDistance", settings.basicSettings.maxDistance);
material.SetFloat("_FadeDistance", settings.basicSettings.fadeDistance);
material.SetFloat("_LayerThickness", settings.reflectionSettings.widthModifier);
const int maxMip = 5;
RenderTexture[] reflectionBuffers;
RenderTextureFormat intermediateFormat = settings.basicSettings.enableHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
reflectionBuffers = new RenderTexture[maxMip];
for (int i = 0; i < maxMip; ++i)
{
if (fullResolutionFiltering)
reflectionBuffers[i] = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, intermediateFormat);
else
reflectionBuffers[i] = m_RTU.GetTemporaryRenderTexture(rtW >> i, rtH >> i, 0, intermediateFormat);
// We explicitly interpolate during bilateral upsampling.
reflectionBuffers[i].filterMode = settings.advancedSettings.bilateralUpsample ? FilterMode.Point : FilterMode.Bilinear;
}
material.SetInt("_EnableSSR", 1);
material.SetInt("_DebugMode", (int)settings.debugSettings.debugMode);
material.SetInt("_TraceBehindObjects", settings.advancedSettings.traceBehindObjects ? 1 : 0);
material.SetInt("_MaxSteps", settings.reflectionSettings.maxSteps);
RenderTexture rayHitTexture = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
// We have 5 passes for different step sizes
int tracePass = Mathf.Clamp(settings.reflectionSettings.rayStepSize, 0, 4);
Graphics.Blit(source, rayHitTexture, material, tracePass);
material.SetTexture("_HitPointTexture", rayHitTexture);
// Resolve the hitpoints into the mirror reflection buffer
Graphics.Blit(source, reflectionBuffers[0], material, (int)PassIndex.HitPointToReflections);
material.SetTexture("_ReflectionTexture0", reflectionBuffers[0]);
material.SetInt("_FullResolutionFiltering", fullResolutionFiltering ? 1 : 0);
material.SetFloat("_MaxRoughness", 1.0f - settings.reflectionSettings.smoothFallbackThreshold);
material.SetFloat("_RoughnessFalloffRange", settings.reflectionSettings.smoothFallbackDistance);
material.SetFloat("_SSRMultiplier", settings.basicSettings.reflectionMultiplier);
RenderTexture[] edgeTextures = new RenderTexture[maxMip];
if (settings.advancedSettings.bilateralUpsample && useEdgeDetector)
{
edgeTextures[0] = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
Graphics.Blit(source, edgeTextures[0], material, (int)PassIndex.EdgeGeneration);
for (int i = 1; i < maxMip; ++i)
{
edgeTextures[i] = m_RTU.GetTemporaryRenderTexture(rtW >> i, rtH >> i);
material.SetInt("_LastMip", i - 1);
Graphics.Blit(edgeTextures[i - 1], edgeTextures[i], material, (int)PassIndex.MinMipGeneration);
}
}
if (settings.advancedSettings.highQualitySharpReflections)
{
RenderTexture filteredReflections = m_RTU.GetTemporaryRenderTexture(reflectionBuffers[0].width, reflectionBuffers[0].height, 0, reflectionBuffers[0].format);
filteredReflections.filterMode = reflectionBuffers[0].filterMode;
reflectionBuffers[0].filterMode = FilterMode.Bilinear;
Graphics.Blit(reflectionBuffers[0], filteredReflections, material, (int)PassIndex.PoissonBlur);
// Replace the unfiltered buffer with the newly filtered one.
m_RTU.ReleaseTemporaryRenderTexture(reflectionBuffers[0]);
reflectionBuffers[0] = filteredReflections;
material.SetTexture("_ReflectionTexture0", reflectionBuffers[0]);
}
// Generate the blurred low-resolution buffers
for (int i = 1; i < maxMip; ++i)
{
RenderTexture inputTex = reflectionBuffers[i - 1];
RenderTexture hBlur;
if (fullResolutionFiltering)
hBlur = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, intermediateFormat);
else
{
int lowMip = i;
hBlur = m_RTU.GetTemporaryRenderTexture(rtW >> lowMip, rtH >> (i - 1), 0, intermediateFormat);
}
for (int j = 0; j < (fullResolutionFiltering ? (i * i) : 1); ++j)
{
// Currently we blur at the resolution of the previous mip level, we could save bandwidth by blurring directly to the lower resolution.
material.SetVector("_Axis", new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
material.SetFloat("_CurrentMipLevel", i - 1.0f);
Graphics.Blit(inputTex, hBlur, material, (int)PassIndex.Blur);
material.SetVector("_Axis", new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
inputTex = reflectionBuffers[i];
Graphics.Blit(hBlur, inputTex, material, (int)PassIndex.Blur);
}
material.SetTexture("_ReflectionTexture" + i, reflectionBuffers[i]);
m_RTU.ReleaseTemporaryRenderTexture(hBlur);
}
if (settings.advancedSettings.bilateralUpsample && useEdgeDetector)
{
for (int i = 0; i < maxMip; ++i)
material.SetTexture("_EdgeTexture" + i, edgeTextures[i]);
}
material.SetInt("_UseEdgeDetector", useEdgeDetector ? 1 : 0);
RenderTexture averageRayDistanceBuffer = m_RTU.GetTemporaryRenderTexture(source.width, source.height, 0, RenderTextureFormat.RHalf);
if (computeAverageRayDistance)
{
Graphics.Blit(source, averageRayDistanceBuffer, material, (int)PassIndex.AverageRayDistanceGeneration);
}
material.SetInt("_UseAverageRayDistance", computeAverageRayDistance ? 1 : 0);
material.SetTexture("_AverageRayDistanceBuffer", averageRayDistanceBuffer);
bool resolveDiffersFromTraceRes = (settings.advancedSettings.resolution == SSRResolution.HalfTraceFullResolve);
RenderTexture finalReflectionBuffer = m_RTU.GetTemporaryRenderTexture(resolveDiffersFromTraceRes ? source.width : rtW, resolveDiffersFromTraceRes ? source.height : rtH, 0, intermediateFormat);
material.SetFloat("_FresnelFade", settings.reflectionSettings.fresnelFade);
material.SetFloat("_FresnelFadePower", settings.reflectionSettings.fresnelFadePower);
material.SetFloat("_DistanceBlur", settings.reflectionSettings.distanceBlur);
material.SetInt("_HalfResolution", (settings.advancedSettings.resolution != SSRResolution.FullResolution) ? 1 : 0);
material.SetInt("_HighlightSuppression", settings.advancedSettings.highlightSuppression ? 1 : 0);
Graphics.Blit(reflectionBuffers[0], finalReflectionBuffer, material, (int)PassIndex.CompositeSSR);
material.SetTexture("_FinalReflectionTexture", finalReflectionBuffer);
RenderTexture temporallyFilteredBuffer = m_RTU.GetTemporaryRenderTexture(resolveDiffersFromTraceRes ? source.width : rtW, resolveDiffersFromTraceRes ? source.height : rtH, 0, intermediateFormat);
if (doTemporalFilterThisFrame)
{
material.SetInt("_UseTemporalConfidence", settings.advancedSettings.useTemporalConfidence ? 1 : 0);
material.SetFloat("_TemporalAlpha", settings.advancedSettings.temporalFilterStrength);
material.SetMatrix("_CurrentCameraToPreviousCamera", m_PreviousWorldToCameraMatrix * cameraToWorldMatrix);
material.SetTexture("_PreviousReflectionTexture", m_PreviousReflectionBuffer);
material.SetTexture("_PreviousCSZBuffer", m_PreviousDepthBuffer);
Graphics.Blit(source, temporallyFilteredBuffer, material, (int)PassIndex.TemporalFilter);
material.SetTexture("_FinalReflectionTexture", temporallyFilteredBuffer);
}
if (settings.advancedSettings.temporalFilterStrength > 0.0)
{
m_PreviousWorldToCameraMatrix = worldToCameraMatrix;
PreparePreviousBuffers(source.width, source.height);
Graphics.Blit(source, m_PreviousDepthBuffer, material, (int)PassIndex.BlitDepthAsCSZ);
Graphics.Blit(rayHitTexture, m_PreviousHitBuffer);
Graphics.Blit(doTemporalFilterThisFrame ? temporallyFilteredBuffer : finalReflectionBuffer, m_PreviousReflectionBuffer);
m_HasInformationFromPreviousFrame = true;
}
Graphics.Blit(source, destination, material, (int)PassIndex.CompositeFinal);
m_RTU.ReleaseAllTemporaryRenderTextures();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using FitbitProxyASPNetCoreFxTest.Models;
namespace FitbitProxyASPNetCoreFxTest.Migrations
{
[ContextType(typeof(ApplicationDbContext))]
partial class CreateIdentitySchema
{
public override string Id
{
get { return "00000000000000_CreateIdentitySchema"; }
}
public override string ProductVersion
{
get { return "7.0.0-beta5"; }
}
public override void BuildTargetModel(ModelBuilder builder)
{
builder
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderKey")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("FitbitProxyASPNetCoreFxTest.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 3);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 10);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 12);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 13);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 14);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Reference("FitbitProxyASPNetCoreFxTest.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Reference("FitbitProxyASPNetCoreFxTest.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
b.Reference("FitbitProxyASPNetCoreFxTest.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
}
}
}
| |
/* **********************************************************************************
* Copyright (c) Robert Nees (https://github.com/sushihangover/Irony)
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
using System;
using System.Xml;
using System.Linq;
using System.Resources;
using System.Reflection;
using System.Collections.Generic;
using Mono.TextEditor.Highlighting;
using Mono.TextEditor;
using Irony.Parsing;
using Irony.Ast;
namespace Irony.GrammarExplorer
{
public class IronySyntaxMode : SyntaxMode
{
public IronySyntaxMode (TextDocument doc) : base (doc)
{
ResourceStreamProvider provider = new ResourceStreamProvider (Assembly.GetExecutingAssembly(), "Irony.SyntaxMode");
using (var stream = provider.Open ()) {
SyntaxMode baseMode = SyntaxMode.Read (stream);
this.rules = new List<Rule> (baseMode.Rules);
this.keywords = new List<Keywords> (baseMode.Keywords);
this.spans = new List<Span> (baseMode.Spans).ToArray ();
this.matches = baseMode.Matches;
this.prevMarker = baseMode.PrevMarker;
this.SemanticRules = new List<SemanticRule> (baseMode.SemanticRules);
this.keywordTable = baseMode.keywordTable;
this.keywordTableIgnoreCase = baseMode.keywordTableIgnoreCase;
this.properties = baseMode.Properties;
}
}
public void AddTerminals (List<string> terms)
{
var keys = new Mono.TextEditor.Highlighting.Keywords ();
keys.Words = terms;
keys.Color = "Keyword(Declaration)";
this.keywords.Add (keys);
foreach (var t in terms) {
this.keywordTable.Add (t, keys);
}
}
public void AddNonTerminals (List<string> nonterms)
{
var keys = new Mono.TextEditor.Highlighting.Keywords ();
keys.Words = nonterms;
keys.Color = "Keyword(Property)";
this.keywords.Add (keys);
foreach (var t in nonterms) {
this.keywordTable.Add (t, keys);
}
}
public override SpanParser CreateSpanParser (DocumentLine line, CloneableStack<Span> spanStack)
{
return new IronySpanParser (this, spanStack ?? line.StartSpan.Clone ());
}
class IronyBlockSpan : Span
{
public int Offset {
get;
set;
}
public IronyBlockSpan (int offset)
{
this.Offset = offset;
this.Rule = "mode:text/x-csharp";
this.Begin = new Regex ("}");
this.End = new Regex ("}");
this.TagColor = "Keyword(Access)";
}
public override string ToString ()
{
return string.Format ("[IronyBlockSpan: Offset={0}]", Offset);
}
}
class ForcedIronyBlockSpan : Span
{
public ForcedIronyBlockSpan ()
{
this.Rule = "mode:text/x-csharp";
this.Begin = new Regex ("%{");
this.End = new Regex ("%}");
this.TagColor = "Keyword(Access)";
}
}
class IronyDefinitionSpan : Span
{
public IronyDefinitionSpan ()
{
this.Rule = "token";
this.Begin = this.End = new Regex ("%%");
this.TagColor = "Keyword(Access)";
}
}
protected class IronySpanParser : SpanParser
{
public IronySpanParser (SyntaxMode mode, CloneableStack<Span> spanStack) : base (mode, spanStack)
{
}
protected override bool ScanSpan (ref int i)
{
bool hasIronyDefinitonSpan = spanStack.Any (s => s is IronyDefinitionSpan);
int textOffset = i - StartOffset;
if (textOffset + 1 < CurText.Length && CurText[textOffset] == '%') {
char next = CurText[textOffset + 1];
if (next == '{') {
FoundSpanBegin (new ForcedIronyBlockSpan (), i, 2);
i++;
return true;
}
if (!hasIronyDefinitonSpan && next == '%') {
FoundSpanBegin (new IronyDefinitionSpan (), i, 2);
return true;
}
if (next == '}' && spanStack.Any (s => s is ForcedIronyBlockSpan)) {
foreach (Span span in spanStack.Clone ()) {
FoundSpanEnd (span, i, span.End.Pattern.Length);
if (span is ForcedIronyBlockSpan)
break;
}
return false;
}
}
if (CurSpan is IronyDefinitionSpan && CurText[textOffset] == '{' && hasIronyDefinitonSpan && !spanStack.Any (s => s is IronyBlockSpan)) {
FoundSpanBegin (new IronyBlockSpan (i), i, 1);
return true;
}
return base.ScanSpan (ref i);
}
protected override bool ScanSpanEnd (Mono.TextEditor.Highlighting.Span cur, ref int i)
{
IronyBlockSpan jbs = cur as IronyBlockSpan;
int textOffset = i - StartOffset;
if (jbs != null) {
if (CurText[textOffset] == '}') {
int brackets = 0;
bool isInString = false, isInChar = false, isVerbatimString = false;
bool isInLineComment = false, isInBlockComment = false;
for (int j = jbs.Offset; j <= i; j++) {
char ch = doc.GetCharAt (j);
switch (ch) {
case '\n':
case '\r':
isInLineComment = false;
if (!isVerbatimString)
isInString = false;
break;
case '/':
if (isInBlockComment) {
if (j > 0 && doc.GetCharAt (j - 1) == '*')
isInBlockComment = false;
} else if (!isInString && !isInChar && j + 1 < doc.TextLength) {
char nextChar = doc.GetCharAt (j + 1);
if (nextChar == '/')
isInLineComment = true;
if (!isInLineComment && nextChar == '*')
isInBlockComment = true;
}
break;
case '\\':
if (isInChar || (isInString && !isVerbatimString))
j++;
break;
case '@':
if (!(isInString || isInChar || isInLineComment || isInBlockComment) && j + 1 < doc.TextLength && doc.GetCharAt (j + 1) == '"') {
isInString = true;
isVerbatimString = true;
j++;
}
break;
case '"':
if (!(isInChar || isInLineComment || isInBlockComment)) {
if (isInString && isVerbatimString && j + 1 < doc.TextLength && doc.GetCharAt (j + 1) == '"') {
j++;
} else {
isInString = !isInString;
isVerbatimString = false;
}
}
break;
case '\'':
if (!(isInString || isInLineComment || isInBlockComment))
isInChar = !isInChar;
break;
case '{':
if (!(isInString || isInChar || isInLineComment || isInBlockComment))
brackets++;
break;
case '}':
if (!(isInString || isInChar || isInLineComment || isInBlockComment))
brackets--;
break;
}
}
if (brackets == 0) {
FoundSpanEnd (cur, i, 1);
return true;
}
return false;
}
}
if (cur is ForcedIronyBlockSpan) {
if (textOffset + 1 < CurText.Length && CurText[textOffset] == '%' && CurText[textOffset + 1] == '}') {
FoundSpanEnd (cur, i, 2);
return true;
}
}
if (cur is IronyDefinitionSpan) {
if (textOffset + 1 < CurText.Length && CurText[textOffset] == '%' && CurText[textOffset + 1] == '%') {
FoundSpanEnd (cur, i, 2);
return true;
}
}
return base.ScanSpanEnd (cur, ref i);
}
}
}
}
| |
// <copyright file=HydraRNG company=Hydra>
// Copyright (c) 2015 All Rights Reserved
// </copyright>
// <author>Christopher Cameron</author>
using System;
using Hydra.HydraCommon.Utils.Shapes._3d;
using UnityEngine;
namespace Hydra.HydraCommon.Utils.RNG
{
/// <summary>
/// HydraRNG is an alternative to UnityEngine.Random to
/// avoid sharing seeds across the application.
/// </summary>
[Serializable]
public class HydraRNG
{
[SerializeField] private SimpleRNG m_RNG;
[SerializeField] private readonly uint m_PrimarySeed;
/// <summary>
/// Lazy loads the random number generator.
/// </summary>
/// <value>The random number generator.</value>
private SimpleRNG lazyRng { get { return m_RNG ?? (m_RNG = new SimpleRNG()); } }
#region Properties
/// <summary>
/// Gets a random value between 0.0f and 1.0f.
/// </summary>
/// <value>The value.</value>
public float value { get { return (float)lazyRng.GetUniform(); } }
/// <summary>
/// Returns a position on the circumference of a unit circle.
/// </summary>
/// <value>The position on unit circle.</value>
public Vector2 onUnitCircle
{
get
{
float angle = value * 2.0f * Mathf.PI;
return new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
}
}
/// <summary>
/// Returns a position inside of a unit circle.
/// </summary>
/// <value>The position in unit circle.</value>
public Vector2 insideUnitCircle { get { return onUnitCircle * value; } }
/// <summary>
/// Returns a random position on a unit sphere.
/// </summary>
/// <value>The position on unit sphere.</value>
public Vector3 onUnitSphere
{
get
{
float u = value * 2.0f * Mathf.PI;
float v = Mathf.Acos(2.0f * value - 1.0f);
float sinV = Mathf.Sin(v);
float x = Mathf.Cos(u) * sinV;
float y = Mathf.Sin(u) * sinV;
float z = Mathf.Cos(v);
return new Vector3(x, y, z);
}
}
/// <summary>
/// Gets a random position inside a unit sphere.
/// </summary>
/// <value>The position inside unit sphere.</value>
public Vector3 insideUnitSphere { get { return onUnitSphere * value; } }
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="Hydra.HydraCommon.Utils.RNG.HydraRNG"/> class.
/// </summary>
public HydraRNG()
{
m_PrimarySeed = CycleToUint(GetHashCode());
}
#region Methods
/// <summary>
/// Sets the seed.
/// </summary>
/// <param name="seed">Seed.</param>
public void SetSeed(uint seed)
{
lazyRng.SetSeed(m_PrimarySeed, seed);
}
/// <summary>
/// Generates a random seed.
/// </summary>
/// <returns>The random seed.</returns>
public uint GetRandomSeed()
{
int random = Range(1, int.MaxValue);
return CycleToUint(random);
}
/// <summary>
/// Returns an int in the min-max range, min inclusive.
/// </summary>
/// <param name="min">Minimum.</param>
/// <param name="max">Maximum.</param>
public int Range(int min, int max)
{
float range = Range((float)min, (float)max);
return HydraMathUtils.FloorToInt(range);
}
/// <summary>
/// Returns a float in the range min-max.
/// </summary>
/// <param name="min">Minimum.</param>
/// <param name="max">Maximum.</param>
public float Range(float min, float max)
{
return HydraMathUtils.MapRange(0.0f, 1.0f, min, max, value);
}
/// <summary>
/// Returns a Vector3 in the range min-max.
/// </summary>
/// <param name="min">Minimum.</param>
/// <param name="max">Maximum.</param>
public Vector3 Range(Vector3 min, Vector3 max)
{
return Range(min, max, true);
}
/// <summary>
/// Returns a Vector3 in the range min-max.
/// </summary>
/// <param name="min">Minimum.</param>
/// <param name="max">Maximum.</param>
/// <param name="linear">If set to <c>true</c> linear.</param>
public Vector3 Range(Vector3 min, Vector3 max, bool linear)
{
if (linear)
return Vector3.Lerp(min, max, value);
return new Vector3(Range(min.x, max.x), Range(min.y, max.y), Range(min.z, max.z));
}
/// <summary>
/// Returns a random item from from the collection.
/// </summary>
/// <param name="collection">Collection.</param>
/// <typeparam name="T">The contents type.</typeparam>
public T Range<T>(T[] collection)
{
return collection[Range(0, collection.Length)];
}
/// <summary>
/// Returns a random color in the specified range.
/// </summary>
/// <returns>The random color in range.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Maximum.</param>
public Color Range(Color min, Color max)
{
return Range(min, max, true);
}
/// <summary>
/// Returns a random color in the specified range.
/// </summary>
/// <returns>The random color in range.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Maximum.</param>
/// <param name="linear">If set to <c>true</c> linear.</param>
public Color Range(Color min, Color max, bool linear)
{
if (linear)
return Color.Lerp(min, max, value);
return new Color(Range(min.r, max.r), Range(min.g, max.g), Range(min.b, max.b), Range(min.a, max.a));
}
/// <summary>
/// Returns a random color in the specified range, using HSL for blending.
/// </summary>
/// <returns>The random color in hsl range.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Maximum.</param>
public Color RangeHsl(Color min, Color max)
{
return RangeHsl(min, max, true);
}
/// <summary>
/// Returns a random color in the specified range, using HSL for blending.
/// </summary>
/// <returns>The random color in hsl range.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Maximum.</param>
/// <param name="linear">If set to <c>true</c> linear.</param>
public Color RangeHsl(Color min, Color max, bool linear)
{
Vector4 hslA = ColorUtils.RgbToHsl(min);
Vector4 hslB = ColorUtils.RgbToHsl(max);
if (linear)
{
Vector4 lerp = Vector4.Lerp(hslA, hslB, value);
return ColorUtils.HslToRgb(lerp);
}
Vector4 random = new Vector4(Range(hslA.x, hslB.x), Range(hslA.y, hslB.y), Range(hslA.z, hslB.z),
Range(hslA.w, hslB.w));
return ColorUtils.HslToRgb(random);
}
/// <summary>
/// Returns a random point in the given triangle.
/// </summary>
/// <returns>The random point.</returns>
/// <param name="point1">Point1.</param>
/// <param name="point2">Point2.</param>
/// <param name="point3">Point3.</param>
public Vector3 PointInTriangle(Vector3 point1, Vector3 point2, Vector3 point3)
{
return PointInTriangle(new Triangle3d(point1, point2, point3));
}
/// <summary>
/// Returns a random point in the given triangle.
/// </summary>
/// <returns>The random point.</returns>
/// <param name="triangle">Triangle.</param>
public Vector3 PointInTriangle(Triangle3d triangle)
{
Vector3 vector1 = triangle.pointB - triangle.pointA;
Vector3 vector2 = triangle.pointC - triangle.pointA;
float variant1 = value;
float variant2 = value;
Vector3 randomInQuad = variant1 * vector1 + variant2 * vector2;
randomInQuad += triangle.pointA;
if (!triangle.Contains(randomInQuad))
{
randomInQuad = variant1 * (-1.0f * vector1) + variant2 * (-1.0f * vector2);
randomInQuad += triangle.pointA + vector1 + vector2;
}
return randomInQuad;
}
#endregion
/// <summary>
/// Cycles the input integer to an unsigned integer.
///
/// For example, -1 would return uint.MaxValue - 1.
/// </summary>
/// <returns>The to uint.</returns>
/// <param name="value">Value.</param>
public static uint CycleToUint(int value)
{
if (value > 0)
return (uint)value;
uint negative = (uint)HydraMathUtils.Abs(value);
return uint.MaxValue - negative;
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 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.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using IntranetWebApplication.Filters;
using IntranetWebApplication.Models;
namespace IntranetWebApplication.Controllers
{
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
WebSecurity.Logout();
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/Disassociate
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Disassociate(string provider, string providerUserId)
{
string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
ManageMessageId? message = null;
// Only disassociate the account if the currently logged in user is the owner
if (ownerAccount == User.Identity.Name)
{
// Use a transaction to prevent the user from deleting their last login credential
using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
{
OAuthWebSecurity.DeleteAccount(provider, providerUserId);
scope.Complete();
message = ManageMessageId.RemoveLoginSuccess;
}
}
}
return RedirectToAction("Manage", new { Message = message });
}
//
// GET: /Account/Manage
public ActionResult Manage(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: "";
ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.ReturnUrl = Url.Action("Manage");
return View();
}
//
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(LocalPasswordModel model)
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.HasLocalPassword = hasLocalAccount;
ViewBag.ReturnUrl = Url.Action("Manage");
if (hasLocalAccount)
{
if (ModelState.IsValid)
{
// ChangePassword will throw an exception rather than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
}
else
{
// User does not have a local password so remove any validation errors caused by a missing
// OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
try
{
WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
}
catch (Exception)
{
ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name \"{0}\" may already exist.", User.Identity.Name));
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return RedirectToLocal(returnUrl);
}
if (User.Identity.IsAuthenticated)
{
// If the current user is logged in add the new account
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
return RedirectToLocal(returnUrl);
}
else
{
// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
{
string provider = null;
string providerUserId = null;
if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
{
return RedirectToAction("Manage");
}
if (ModelState.IsValid)
{
// Insert a new user into the database
using (UsersContext db = new UsersContext())
{
UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
// Check if user already exists
if (user == null)
{
// Insert name into the profile table
db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
db.SaveChanges();
OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
}
}
}
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
[AllowAnonymous]
[ChildActionOnly]
public ActionResult ExternalLoginsList(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
}
[ChildActionOnly]
public ActionResult RemoveExternalLogins()
{
ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
List<ExternalLogin> externalLogins = new List<ExternalLogin>();
foreach (OAuthAccount account in accounts)
{
AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);
externalLogins.Add(new ExternalLogin
{
Provider = account.Provider,
ProviderDisplayName = clientData.DisplayName,
ProviderUserId = account.ProviderUserId,
});
}
ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
return PartialView("_RemoveExternalLoginsPartial", externalLogins);
}
#region Helpers
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
public enum ManageMessageId
{
ChangePasswordSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
}
internal class ExternalLoginResult : ActionResult
{
public ExternalLoginResult(string provider, string returnUrl)
{
Provider = provider;
ReturnUrl = returnUrl;
}
public string Provider { get; private set; }
public string ReturnUrl { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
}
}
private static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "User name already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Xunit;
using System.Threading.Tasks;
using Proto.Remote.Tests.Messages;
namespace Proto.Remote.Tests
{
[Collection("RemoteTests"), Trait("Category", "Remote")]
public class RemoteTests
{
private readonly RemoteManager _remoteManager;
public RemoteTests(RemoteManager remoteManager)
{
_remoteManager = remoteManager;
}
[Fact, DisplayTestMethodName]
public void CanSerializeAndDeserializeJsonPID()
{
var typeName = "actor.PID";
var json = new JsonMessage(typeName, "{ \"Address\":\"123\", \"Id\":\"456\"}");
var bytes = Serialization.Serialize(json, 1);
var deserialized = Serialization.Deserialize(typeName, bytes, 1) as PID;
Assert.Equal("123", deserialized.Address);
Assert.Equal("456", deserialized.Id);
}
[Fact, DisplayTestMethodName]
public void CanSerializeAndDeserializeJson()
{
var typeName = "remote_test_messages.Ping";
var json = new JsonMessage(typeName, "{ \"message\":\"Hello\"}");
var bytes = Serialization.Serialize(json, 1);
var deserialized = Serialization.Deserialize(typeName, bytes, 1) as Ping;
Assert.Equal("Hello",deserialized.Message);
}
[Fact, DisplayTestMethodName]
public async void CanSendJsonAndReceiveToExistingRemote()
{
var remoteActor = new PID(_remoteManager.DefaultNode.Address, "EchoActorInstance");
var ct = new CancellationTokenSource(3000);
var tcs = new TaskCompletionSource<bool>();
ct.Token.Register(() =>
{
tcs.TrySetCanceled();
});
var localActor = Actor.Spawn(Actor.FromFunc(ctx =>
{
if (ctx.Message is Pong)
{
tcs.SetResult(true);
ctx.Self.Stop();
}
return Actor.Done;
}));
var json = new JsonMessage("remote_test_messages.Ping", "{ \"message\":\"Hello\"}");
var envelope = new Proto.MessageEnvelope(json, localActor, Proto.MessageHeader.EmptyHeader);
Remote.SendMessage(remoteActor, envelope, 1);
await tcs.Task;
}
[Fact, DisplayTestMethodName]
public async void CanSendAndReceiveToExistingRemote()
{
var remoteActor = new PID(_remoteManager.DefaultNode.Address, "EchoActorInstance");
var pong = await remoteActor.RequestAsync<Pong>(new Ping { Message = "Hello" }, TimeSpan.FromMilliseconds(5000));
Assert.Equal($"{_remoteManager.DefaultNode.Address} Hello", pong.Message);
}
[Fact, DisplayTestMethodName]
public async void WhenRemoteActorNotFound_RequestAsyncTimesout()
{
var unknownRemoteActor = new PID(_remoteManager.DefaultNode.Address, "doesn't exist");
await Assert.ThrowsAsync<TimeoutException>(async () =>
{
await unknownRemoteActor.RequestAsync<Pong>(new Ping { Message = "Hello" }, TimeSpan.FromMilliseconds(2000));
});
}
[Fact, DisplayTestMethodName]
public async void CanSpawnRemoteActor()
{
var remoteActorName = Guid.NewGuid().ToString();
var remoteActorResp = await Remote.SpawnNamedAsync(_remoteManager.DefaultNode.Address, remoteActorName, "EchoActor", TimeSpan.FromSeconds(5));
var remoteActor = remoteActorResp.Pid;
var pong = await remoteActor.RequestAsync<Pong>(new Ping{Message="Hello"}, TimeSpan.FromMilliseconds(5000));
Assert.Equal($"{_remoteManager.DefaultNode.Address} Hello", pong.Message);
}
[Fact, DisplayTestMethodName]
public async void CanWatchRemoteActor()
{
var remoteActor = await SpawnRemoteActor(_remoteManager.DefaultNode.Address);
var localActor = await SpawnLocalActorAndWatch(remoteActor);
remoteActor.Stop();
Assert.True(await PollUntilTrue(() =>
localActor.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))),
"Watching actor did not receive Termination message");
}
[Fact, DisplayTestMethodName]
public async void CanWatchMultipleRemoteActors()
{
var remoteActor1 = await SpawnRemoteActor(_remoteManager.DefaultNode.Address);
var remoteActor2 = await SpawnRemoteActor(_remoteManager.DefaultNode.Address);
var localActor = await SpawnLocalActorAndWatch(remoteActor1, remoteActor2);
remoteActor1.Stop();
remoteActor2.Stop();
Assert.True(await PollUntilTrue(() =>
localActor.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor1.Id), TimeSpan.FromSeconds(5))),
"Watching actor did not receive Termination message");
Assert.True(await PollUntilTrue(() =>
localActor.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor2.Id), TimeSpan.FromSeconds(5))),
"Watching actor did not receive Termination message");
}
[Fact, DisplayTestMethodName]
public async void MultipleLocalActorsCanWatchRemoteActor()
{
var remoteActor = await SpawnRemoteActor(_remoteManager.DefaultNode.Address);
var localActor1 = await SpawnLocalActorAndWatch(remoteActor);
var localActor2 = await SpawnLocalActorAndWatch(remoteActor);
remoteActor.Stop();
Assert.True(await PollUntilTrue(() =>
localActor1.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))),
"Watching actor did not receive Termination message");
Assert.True(await PollUntilTrue(() =>
localActor2.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))),
"Watching actor did not receive Termination message");
}
[Fact, DisplayTestMethodName]
public async void CanUnwatchRemoteActor()
{
var remoteActor = await SpawnRemoteActor(_remoteManager.DefaultNode.Address);
var localActor1 = await SpawnLocalActorAndWatch(remoteActor);
var localActor2 = await SpawnLocalActorAndWatch(remoteActor);
localActor2.Tell(new Unwatch(remoteActor));
await Task.Delay(TimeSpan.FromSeconds(3)); // wait for unwatch to propagate...
remoteActor.Stop();
// localActor1 is still watching so should get notified
Assert.True(await PollUntilTrue(() =>
localActor1.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))),
"Watching actor did not receive Termination message");
// localActor2 is NOT watching so should not get notified
Assert.False(await localActor2.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5)),
"Unwatch did not succeed.");
}
[Fact, DisplayTestMethodName]
public async void WhenRemoteTerminated_LocalWatcherReceivesNotification()
{
var (address, process) = _remoteManager.ProvisionNode("127.0.0.1", 12002);
var remoteActor = await SpawnRemoteActor(address);
var localActor = await SpawnLocalActorAndWatch(remoteActor);
Console.WriteLine($"Killing remote process {address}!");
process.Kill();
Assert.True(await PollUntilTrue(() =>
localActor.RequestAsync<bool>(new TerminatedMessageReceived(address, remoteActor.Id), TimeSpan.FromSeconds(5))),
"Watching actor did not receive Termination message");
Assert.Equal(1, await localActor.RequestAsync<int>(new GetTerminatedMessagesCount(), TimeSpan.FromSeconds(5)));
}
private static async Task<PID> SpawnRemoteActor(string address)
{
var remoteActorName = Guid.NewGuid().ToString();
var remoteActorResp = await Remote.SpawnNamedAsync(address, remoteActorName, "EchoActor", TimeSpan.FromSeconds(5));
return remoteActorResp.Pid;
}
private async Task<PID> SpawnLocalActorAndWatch(params PID[] remoteActors)
{
var props = Actor.FromProducer(() => new LocalActor(remoteActors));
var actor = Actor.Spawn(props);
// The local actor watches the remote one - we wait here for the RemoteWatch
// message to propagate to the remote actor
Console.WriteLine("Waiting for RemoteWatch to propagate...");
await Task.Delay(2000);
return actor;
}
private Task<bool> PollUntilTrue(Func<Task<bool>> predicate)
{
return PollUntilTrue(predicate, 10, TimeSpan.FromMilliseconds(500));
}
private async Task<bool> PollUntilTrue(Func<Task<bool>> predicate, int attempts, TimeSpan interval)
{
var attempt = 1;
while (attempt <= attempts)
{
Console.WriteLine($"Attempting assertion (attempt {attempt} of {attempts})");
if (await predicate())
{
Console.WriteLine($"Passed!");
return true;
}
attempt++;
await Task.Delay(interval);
}
return false;
}
}
public class TerminatedMessageReceived
{
public TerminatedMessageReceived(string address, string actorId)
{
Address = address;
ActorId = actorId;
}
public string Address { get; }
public string ActorId { get; }
}
public class GetTerminatedMessagesCount { }
public class LocalActor : IActor
{
private readonly List<PID> _remoteActors = new List<PID>();
private readonly List<Terminated> _terminatedMessages = new List<Terminated>();
public LocalActor(params PID[] remoteActors)
{
_remoteActors.AddRange(remoteActors);
}
public Task ReceiveAsync(IContext context)
{
switch (context.Message)
{
case Started _:
HandleStarted(context);
break;
case Unwatch msg:
HandleUnwatch(context, msg);
break;
case TerminatedMessageReceived msg:
HandleTerminatedMessageReceived(context, msg);
break;
case GetTerminatedMessagesCount _:
HandleCountOfMessagesReceived(context);
break;
case Terminated msg:
HandleTerminated(msg);
break;
}
return Actor.Done;
}
private void HandleCountOfMessagesReceived(IContext context)
{
context.Sender.Tell(_terminatedMessages.Count);
}
private void HandleTerminatedMessageReceived(IContext context, TerminatedMessageReceived msg)
{
var messageReceived = _terminatedMessages.Any(tm => tm.Who.Address == msg.Address &&
tm.Who.Id == msg.ActorId);
context.Sender.Tell(messageReceived);
}
private void HandleTerminated(Terminated msg)
{
Console.WriteLine($"Received Terminated message for {msg.Who.Address}: {msg.Who.Id}. Address terminated? {msg.AddressTerminated}");
_terminatedMessages.Add(msg);
}
private void HandleUnwatch(IContext context, Unwatch msg)
{
var remoteActor =_remoteActors.Single(ra => ra.Id == msg.Watcher.Id &&
ra.Address == msg.Watcher.Address);
context.Unwatch(remoteActor);
}
private void HandleStarted(IContext context)
{
foreach (var remoteActor in _remoteActors)
{
context.Watch(remoteActor);
}
}
}
}
| |
#region License
/*
* WsStream.cs
*
* The MIT License
*
* Copyright (c) 2010-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using WebSocketSharp.Net.Security;
namespace WebSocketSharp
{
internal class WsStream : IDisposable
{
#region Private Const Fields
private const int _handshakeHeadersLimitLen = 8192;
#endregion
#region Private Fields
private object _forWrite;
private Stream _innerStream;
private bool _secure;
#endregion
#region Private Constructors
private WsStream (Stream innerStream, bool secure)
{
_innerStream = innerStream;
_secure = secure;
_forWrite = new object ();
}
#endregion
#region Internal Constructors
internal WsStream (NetworkStream innerStream)
: this (innerStream, false)
{
}
internal WsStream (SslStream innerStream)
: this (innerStream, true)
{
}
#endregion
#region Public Properties
public bool DataAvailable {
get {
return _secure
? ((SslStream) _innerStream).DataAvailable
: ((NetworkStream) _innerStream).DataAvailable;
}
}
public bool IsSecure {
get {
return _secure;
}
}
#endregion
#region Private Methods
private static byte [] readHandshakeEntityBody (Stream stream, string length)
{
var len = Int64.Parse (length);
return len > 1024
? stream.ReadBytes (len, 1024)
: stream.ReadBytes ((int) len);
}
private static string [] readHandshakeHeaders (Stream stream)
{
var buffer = new List<byte> ();
var count = 0;
Action<int> add = i => {
buffer.Add ((byte) i);
count++;
};
var read = false;
while (count < _handshakeHeadersLimitLen) {
if (stream.ReadByte ().EqualsWith ('\r', add) &&
stream.ReadByte ().EqualsWith ('\n', add) &&
stream.ReadByte ().EqualsWith ('\r', add) &&
stream.ReadByte ().EqualsWith ('\n', add)) {
read = true;
break;
}
}
if (!read)
throw new WebSocketException (
"The header part of a handshake is greater than the limit length.");
var crlf = "\r\n";
return Encoding.UTF8.GetString (buffer.ToArray ())
.Replace (crlf + " ", " ")
.Replace (crlf + "\t", " ")
.Split (new string [] { crlf }, StringSplitOptions.RemoveEmptyEntries);
}
#endregion
#region Internal Methods
internal static WsStream CreateClientStream (
TcpClient client,
bool secure,
string host,
System.Net.Security.RemoteCertificateValidationCallback validationCallback)
{
var netStream = client.GetStream ();
if (secure) {
if (validationCallback == null)
validationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
var sslStream = new SslStream (netStream, false, validationCallback);
sslStream.AuthenticateAsClient (host);
return new WsStream (sslStream);
}
return new WsStream (netStream);
}
internal static WsStream CreateServerStream (
TcpClient client, X509Certificate cert, bool secure)
{
var netStream = client.GetStream ();
if (secure) {
var sslStream = new SslStream (netStream, false);
sslStream.AuthenticateAsServer (cert);
return new WsStream (sslStream);
}
return new WsStream (netStream);
}
internal T ReadHandshake<T> (
Func<string [], T> parser, int millisecondsTimeout)
where T : HandshakeBase
{
var timeout = false;
var timer = new Timer (
state => {
timeout = true;
_innerStream.Close ();
},
null,
millisecondsTimeout,
-1);
T handshake = null;
Exception exception = null;
try {
handshake = parser (readHandshakeHeaders (_innerStream));
var contentLen = handshake.Headers ["Content-Length"];
if (contentLen != null && contentLen.Length > 0)
handshake.EntityBodyData = readHandshakeEntityBody (
_innerStream, contentLen);
}
catch (Exception ex) {
exception = ex;
}
finally {
timer.Change (-1, -1);
timer.Dispose ();
}
var reason = timeout
? "A timeout has occurred while receiving a handshake."
: exception != null
? "An exception has occurred while receiving a handshake."
: null;
if (reason != null)
throw new WebSocketException (reason, exception);
return handshake;
}
internal bool Write (byte [] data)
{
lock (_forWrite) {
try {
_innerStream.Write (data, 0, data.Length);
return true;
}
catch {
return false;
}
}
}
#endregion
#region Public Methods
public void Close ()
{
_innerStream.Close ();
}
public void Dispose ()
{
_innerStream.Dispose ();
}
public WsFrame ReadFrame ()
{
return WsFrame.Parse (_innerStream, true);
}
public void ReadFrameAsync (
Action<WsFrame> completed, Action<Exception> error)
{
WsFrame.ParseAsync (_innerStream, true, completed, error);
}
public HandshakeRequest ReadHandshakeRequest ()
{
return ReadHandshake<HandshakeRequest> (HandshakeRequest.Parse, 90000);
}
public HandshakeResponse ReadHandshakeResponse ()
{
return ReadHandshake<HandshakeResponse> (HandshakeResponse.Parse, 90000);
}
public bool WriteFrame (WsFrame frame)
{
return Write (frame.ToByteArray ());
}
public bool WriteHandshake (HandshakeBase handshake)
{
return Write (handshake.ToByteArray ());
}
#endregion
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type NotebookSectionsCollectionRequest.
/// </summary>
public partial class NotebookSectionsCollectionRequest : BaseRequest, INotebookSectionsCollectionRequest
{
/// <summary>
/// Constructs a new NotebookSectionsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public NotebookSectionsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified OnenoteSection to the collection via POST.
/// </summary>
/// <param name="onenoteSection">The OnenoteSection to add.</param>
/// <returns>The created OnenoteSection.</returns>
public System.Threading.Tasks.Task<OnenoteSection> AddAsync(OnenoteSection onenoteSection)
{
return this.AddAsync(onenoteSection, CancellationToken.None);
}
/// <summary>
/// Adds the specified OnenoteSection to the collection via POST.
/// </summary>
/// <param name="onenoteSection">The OnenoteSection to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created OnenoteSection.</returns>
public System.Threading.Tasks.Task<OnenoteSection> AddAsync(OnenoteSection onenoteSection, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<OnenoteSection>(onenoteSection, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<INotebookSectionsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<INotebookSectionsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<NotebookSectionsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public INotebookSectionsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public INotebookSectionsCollectionRequest Expand(Expression<Func<OnenoteSection, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public INotebookSectionsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public INotebookSectionsCollectionRequest Select(Expression<Func<OnenoteSection, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public INotebookSectionsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public INotebookSectionsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public INotebookSectionsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public INotebookSectionsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using PAL_TlsHandshakeState = Interop.AppleCrypto.PAL_TlsHandshakeState;
using PAL_TlsIo = Interop.AppleCrypto.PAL_TlsIo;
namespace System.Net.Security
{
internal static class SslStreamPal
{
public static Exception GetException(SecurityStatusPal status)
{
return status.Exception ?? new Win32Exception((int)status.ErrorCode);
}
internal const bool StartMutualAuthAsAnonymous = false;
// SecureTransport is okay with a 0 byte input, but it produces a 0 byte output.
// Since ST is not producing the framed empty message just call this false and avoid the
// special case of an empty array being passed to the `fixed` statement.
internal const bool CanEncryptEmptyMessage = false;
public static void VerifyPackageInfo()
{
}
public static SecurityStatusPal AcceptSecurityContext(
ref SafeFreeCredentials credential,
ref SafeDeleteContext context,
ArraySegment<byte> inputBuffer,
ref byte[] outputBuffer,
SslAuthenticationOptions sslAuthenticationOptions)
{
return HandshakeInternal(credential, ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions);
}
public static SecurityStatusPal InitializeSecurityContext(
ref SafeFreeCredentials credential,
ref SafeDeleteContext context,
string targetName,
ArraySegment<byte> inputBuffer,
ref byte[] outputBuffer,
SslAuthenticationOptions sslAuthenticationOptions)
{
return HandshakeInternal(credential, ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions);
}
public static SafeFreeCredentials AcquireCredentialsHandle(
X509Certificate certificate,
SslProtocols protocols,
EncryptionPolicy policy,
bool isServer)
{
return new SafeFreeSslCredentials(certificate, protocols, policy);
}
internal static byte[] GetNegotiatedApplicationProtocol(SafeDeleteContext context)
{
if (context == null)
return null;
return Interop.AppleCrypto.SslGetAlpnSelected(((SafeDeleteSslContext)context).SslContext);
}
public static SecurityStatusPal EncryptMessage(
SafeDeleteContext securityContext,
ReadOnlyMemory<byte> input,
int headerSize,
int trailerSize,
ref byte[] output,
out int resultSize)
{
resultSize = 0;
Debug.Assert(input.Length > 0, $"{nameof(input.Length)} > 0 since {nameof(CanEncryptEmptyMessage)} is false");
try
{
SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext;
SafeSslHandle sslHandle = sslContext.SslContext;
unsafe
{
MemoryHandle memHandle = input.Pin();
try
{
PAL_TlsIo status;
lock (sslHandle)
{
status = Interop.AppleCrypto.SslWrite(
sslHandle,
(byte*)memHandle.Pointer,
input.Length,
out int written);
}
if (status < 0)
{
return new SecurityStatusPal(
SecurityStatusPalErrorCode.InternalError,
Interop.AppleCrypto.CreateExceptionForOSStatus((int)status));
}
if (sslContext.BytesReadyForConnection <= output?.Length)
{
resultSize = sslContext.ReadPendingWrites(output, 0, output.Length);
}
else
{
output = sslContext.ReadPendingWrites();
resultSize = output.Length;
}
switch (status)
{
case PAL_TlsIo.Success:
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
case PAL_TlsIo.WouldBlock:
return new SecurityStatusPal(SecurityStatusPalErrorCode.ContinueNeeded);
default:
Debug.Fail($"Unknown status value: {status}");
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError);
}
}
finally
{
memHandle.Dispose();
}
}
}
catch (Exception e)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, e);
}
}
public static SecurityStatusPal DecryptMessage(
SafeDeleteContext securityContext,
byte[] buffer,
ref int offset,
ref int count)
{
try
{
SafeDeleteSslContext sslContext = (SafeDeleteSslContext)securityContext;
SafeSslHandle sslHandle = sslContext.SslContext;
sslContext.Write(buffer, offset, count);
unsafe
{
fixed (byte* offsetInput = &buffer[offset])
{
int written;
PAL_TlsIo status;
lock (sslHandle)
{
status = Interop.AppleCrypto.SslRead(sslHandle, offsetInput, count, out written);
}
if (status < 0)
{
return new SecurityStatusPal(
SecurityStatusPalErrorCode.InternalError,
Interop.AppleCrypto.CreateExceptionForOSStatus((int)status));
}
count = written;
switch (status)
{
case PAL_TlsIo.Success:
case PAL_TlsIo.WouldBlock:
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
case PAL_TlsIo.ClosedGracefully:
return new SecurityStatusPal(SecurityStatusPalErrorCode.ContextExpired);
case PAL_TlsIo.Renegotiate:
return new SecurityStatusPal(SecurityStatusPalErrorCode.Renegotiate);
default:
Debug.Fail($"Unknown status value: {status}");
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError);
}
}
}
}
catch (Exception e)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, e);
}
}
public static ChannelBinding QueryContextChannelBinding(
SafeDeleteContext securityContext,
ChannelBindingKind attribute)
{
switch (attribute)
{
case ChannelBindingKind.Endpoint:
return EndpointChannelBindingToken.Build(securityContext);
}
// SecureTransport doesn't expose the Finished messages, so a Unique binding token
// cannot be built.
//
// Windows/netfx compat says to return null for not supported kinds (including unmapped enum values).
return null;
}
public static void QueryContextStreamSizes(
SafeDeleteContext securityContext,
out StreamSizes streamSizes)
{
streamSizes = StreamSizes.Default;
}
public static void QueryContextConnectionInfo(
SafeDeleteContext securityContext,
out SslConnectionInfo connectionInfo)
{
connectionInfo = new SslConnectionInfo(((SafeDeleteSslContext)securityContext).SslContext);
}
private static SecurityStatusPal HandshakeInternal(
SafeFreeCredentials credential,
ref SafeDeleteContext context,
ArraySegment<byte> inputBuffer,
ref byte[] outputBuffer,
SslAuthenticationOptions sslAuthenticationOptions)
{
Debug.Assert(!credential.IsInvalid);
try
{
SafeDeleteSslContext sslContext = ((SafeDeleteSslContext)context);
if ((null == context) || context.IsInvalid)
{
sslContext = new SafeDeleteSslContext(credential as SafeFreeSslCredentials, sslAuthenticationOptions);
context = sslContext;
if (!string.IsNullOrEmpty(sslAuthenticationOptions.TargetHost))
{
Debug.Assert(!sslAuthenticationOptions.IsServer, "targetName should not be set for server-side handshakes");
Interop.AppleCrypto.SslSetTargetName(sslContext.SslContext, sslAuthenticationOptions.TargetHost);
}
if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired)
{
Interop.AppleCrypto.SslSetAcceptClientCert(sslContext.SslContext);
}
}
if (inputBuffer.Array != null && inputBuffer.Count > 0)
{
sslContext.Write(inputBuffer.Array, inputBuffer.Offset, inputBuffer.Count);
}
SafeSslHandle sslHandle = sslContext.SslContext;
SecurityStatusPal status;
lock (sslHandle)
{
status = PerformHandshake(sslHandle);
}
outputBuffer = sslContext.ReadPendingWrites();
return status;
}
catch (Exception exc)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, exc);
}
}
private static SecurityStatusPal PerformHandshake(SafeSslHandle sslHandle)
{
while (true)
{
PAL_TlsHandshakeState handshakeState = Interop.AppleCrypto.SslHandshake(sslHandle);
switch (handshakeState)
{
case PAL_TlsHandshakeState.Complete:
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
case PAL_TlsHandshakeState.WouldBlock:
return new SecurityStatusPal(SecurityStatusPalErrorCode.ContinueNeeded);
case PAL_TlsHandshakeState.ServerAuthCompleted:
case PAL_TlsHandshakeState.ClientAuthCompleted:
// The standard flow would be to call the verification callback now, and
// possibly abort. But the library is set up to call this "success" and
// do verification between "handshake complete" and "first send/receive".
//
// So, call SslHandshake again to indicate to Secure Transport that we've
// accepted this handshake and it should go into the ready state.
break;
default:
return new SecurityStatusPal(
SecurityStatusPalErrorCode.InternalError,
Interop.AppleCrypto.CreateExceptionForOSStatus((int)handshakeState));
}
}
}
public static SecurityStatusPal ApplyAlertToken(
ref SafeFreeCredentials credentialsHandle,
SafeDeleteContext securityContext,
TlsAlertType alertType,
TlsAlertMessage alertMessage)
{
// There doesn't seem to be an exposed API for writing an alert,
// the API seems to assume that all alerts are generated internally by
// SSLHandshake.
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
public static SecurityStatusPal ApplyShutdownToken(
ref SafeFreeCredentials credentialsHandle,
SafeDeleteContext securityContext)
{
SafeDeleteSslContext sslContext = ((SafeDeleteSslContext)securityContext);
SafeSslHandle sslHandle = sslContext.SslContext;
int osStatus;
lock (sslHandle)
{
osStatus = Interop.AppleCrypto.SslShutdown(sslHandle);
}
if (osStatus == 0)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
return new SecurityStatusPal(
SecurityStatusPalErrorCode.InternalError,
Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus));
}
}
}
| |
#region Copyright (c) Roni Schuetz - All Rights Reserved
// * --------------------------------------------------------------------- *
// * Roni Schuetz *
// * Copyright (c) 2008 All Rights reserved *
// * *
// * Shared Cache high-performance, distributed caching and *
// * replicated caching system, generic in nature, but intended to *
// * speeding up dynamic web and / or win applications by alleviating *
// * database load. *
// * *
// * This Software is written by Roni Schuetz (schuetz AT gmail DOT com) *
// * *
// * This library is free software; you can redistribute it and/or *
// * modify it under the terms of the GNU Lesser General Public License *
// * as published by the Free Software Foundation; either version 2.1 *
// * of the License, or (at your option) any later version. *
// * *
// * This library is distributed in the hope that it will be useful, *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
// * Lesser General Public License for more details. *
// * *
// * You should have received a copy of the GNU Lesser General Public *
// * License along with this library; if not, write to the Free *
// * Software Foundation, Inc., 59 Temple Place, Suite 330, *
// * Boston, MA 02111-1307 USA *
// * *
// * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. *
// * --------------------------------------------------------------------- *
#endregion
// *************************************************************************
//
// Name: Common.cs
//
// Created: 18-07-2007 SharedCache.com, rschuetz
// Modified: 18-07-2007 SharedCache.com, rschuetz : Creation
// Modified: 24-02-2008 SharedCache.com, rschuetz : added config method since its not available anymore in SharedCache.WinServiceCommon
// *************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using COM = SharedCache.WinServiceCommon;
namespace SharedCache.Notify
{
/// <summary>
/// <b>common library</b>
/// </summary>
public class Common
{
public class ComboBoxItem
{
public string Name;
public int Value;
public ComboBoxItem(string Name, int Value)
{
this.Name = Name;
this.Value = Value;
}
public override string ToString()
{
return this.Name;
}
}
/// <summary>
/// Restarts the service.
/// </summary>
/// <param name="service">The service.</param>
public static void RestartService(string service)
{
if(string.IsNullOrEmpty(service))
{
MessageBox.Show("Service IP address is missing!!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace(@"file:\", "");
string vars = " " + service;
Process proc = new Process();
proc.StartInfo.FileName = @"RestartService.cmd";
proc.StartInfo.Arguments = vars;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
proc.StartInfo.ErrorDialog = false;
proc.StartInfo.WorkingDirectory = path;
proc.Start();
proc.WaitForExit();
if (proc.ExitCode != 0)
MessageBox.Show("Error executing", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public static string VersionCheck()
{
version.Version wsVersion;
string result = string.Empty;
bool getWsInfo = false;
try
{
wsVersion = new version.Version();
wsVersion.Timeout = 5000;
wsVersion.Url = Config.GetStringValueFromConfigByKey(@"VersionUrl");
result = wsVersion.GetVersion();
getWsInfo = true;
}
catch (Exception ex)
{
COM.Handler.LogHandler.Error("Could not get online version number", ex);
}
if (!string.IsNullOrEmpty(result) && !result.Equals(Config.GetStringValueFromConfigByKey(@"SharedCacheVersionNumber")))
{
if (getWsInfo)
{
return result;
}
}
return result;
}
}
/// <summary>
/// Summary description for ConfigHandler.
/// </summary>
public class Config
{
/// <summary>
/// Initializes a new instance of the <see cref="Config"/> class.
/// </summary>
public Config()
{ }
#region Methods
/// <summary>
/// Get the value based on the key from the app.config
/// </summary>
/// <param name="key"><see cref="string"/> Key-Name</param>
/// <returns>string value of a applied key</returns>
[System.Diagnostics.DebuggerStepThrough]
public static string GetStringValueFromConfigByKey(string key)
{
try
{
if (ConfigurationManager.AppSettings[key] != null)
return ConfigurationManager.AppSettings[key];
}
catch (FormatException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (ArgumentException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (Exception e)
{
// Todo: RSC: add Logging
System.Diagnostics.Debug.WriteLine(e);
}
return string.Empty;
}
/// <summary>
/// Get the value based on the key from the app.config
/// </summary>
/// <param name="key"><see cref="string"/> Key-Name</param>
/// <returns>int value of a applied key</returns>
[System.Diagnostics.DebuggerStepThrough]
public static int GetIntValueFromConfigByKey(string key)
{
try
{
if (ConfigurationManager.AppSettings[key] != null)
return int.Parse(ConfigurationManager.AppSettings[key]);
}
catch (FormatException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (ArgumentException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (Exception e)
{
// Todo: RSC: add Logging
System.Diagnostics.Debug.WriteLine(e);
}
return -1;
}
/// <summary>
/// Get the value based on the key from the app.config
/// </summary>
/// <param name="key"><see cref="string"/> Key-Name</param>
/// <returns>int value of a applied key</returns>
[System.Diagnostics.DebuggerStepThrough]
public static double GetDoubleValueFromConfigByKey(string key)
{
try
{
if (ConfigurationManager.AppSettings[key] != null)
return double.Parse(ConfigurationManager.AppSettings[key]);
}
catch (FormatException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (ArgumentException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (Exception e)
{
// Todo: RSC: add Logging
System.Diagnostics.Debug.WriteLine(e);
}
return -1;
}
/// <summary>
/// Gets the num of defined app settings.
/// </summary>
/// <returns>A <see cref="T:System.Int32"/> Object.</returns>
[System.Diagnostics.DebuggerStepThrough]
public static int GetNumOfDefinedAppSettings()
{
return ConfigurationManager.AppSettings.Count;
}
/// <summary>
/// Displays the app.config settings.
/// </summary>
/// <returns></returns>
public static string DisplayAppSettings()
{
StringBuilder sb = new StringBuilder();
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string[] keys = appSettings.AllKeys;
sb.Append(string.Empty + Environment.NewLine);
sb.Append("Application appSettings:" + Environment.NewLine);
sb.Append(string.Empty + Environment.NewLine);
// Loop to get key/value pairs.
for (int i = 0; i < appSettings.Count; i++)
{
sb.AppendFormat("#{0} Name: {1} - Value: {2}" + Environment.NewLine, i, keys[i], appSettings[i]);
}
return sb.ToString();
}
#endregion
}
}
| |
//
// 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 Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet("Set", "AzureRmVmssStorageProfile")]
[OutputType(typeof(VirtualMachineScaleSet))]
public class SetAzureRmVmssStorageProfileCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
public VirtualMachineScaleSet VirtualMachineScaleSet { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
public string ImageReferencePublisher { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public string ImageReferenceOffer { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
public string ImageReferenceSku { get; set; }
[Parameter(
Mandatory = false,
Position = 4,
ValueFromPipelineByPropertyName = true)]
public string ImageReferenceVersion { get; set; }
[Parameter(
Mandatory = false,
Position = 5,
ValueFromPipelineByPropertyName = true)]
public string Name { get; set; }
[Parameter(
Mandatory = false,
Position = 6,
ValueFromPipelineByPropertyName = true)]
public CachingTypes? OsDiskCaching { get; set; }
[Parameter(
Mandatory = false,
Position = 7,
ValueFromPipelineByPropertyName = true)]
public DiskCreateOptionTypes? OsDiskCreateOption { get; set; }
[Parameter(
Mandatory = false,
Position = 8,
ValueFromPipelineByPropertyName = true)]
public OperatingSystemTypes? OsDiskOsType { get; set; }
[Parameter(
Mandatory = false,
Position = 9,
ValueFromPipelineByPropertyName = true)]
public string Image { get; set; }
[Parameter(
Mandatory = false,
Position = 10,
ValueFromPipelineByPropertyName = true)]
public string[] VhdContainer { get; set; }
protected override void ProcessRecord()
{
if (this.ImageReferencePublisher != null)
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
// ImageReference
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Publisher = this.ImageReferencePublisher;
}
if (this.ImageReferenceOffer != null)
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
// ImageReference
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Offer = this.ImageReferenceOffer;
}
if (this.ImageReferenceSku != null)
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
// ImageReference
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Sku = this.ImageReferenceSku;
}
if (this.ImageReferenceVersion != null)
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
// ImageReference
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference = new Microsoft.Azure.Management.Compute.Models.ImageReference();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.ImageReference.Version = this.ImageReferenceVersion;
}
if (this.Name != null)
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Name = this.Name;
}
if (this.OsDiskCaching != null)
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Caching = this.OsDiskCaching;
}
if (this.OsDiskCreateOption != null)
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.CreateOption = this.OsDiskCreateOption;
}
if (this.OsDiskOsType != null)
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.OsType = this.OsDiskOsType;
}
if (this.Image != null)
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
// Image
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image = new Microsoft.Azure.Management.Compute.Models.VirtualHardDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.Image.Uri = this.Image;
}
if (this.VhdContainer != null)
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// StorageProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetStorageProfile();
}
// OsDisk
if (this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSDisk();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers = this.VhdContainer;
}
WriteObject(this.VirtualMachineScaleSet);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Runtime.Serialization;
using System.Threading;
using System.Xml;
using NUnit.Framework;
using ServiceStack.Common.Extensions;
using ServiceStack.Text.Jsv;
namespace ServiceStack.Text.Tests
{
[TestFixture]
public class AdhocModelTests
: TestBase
{
public enum FlowPostType
{
Content,
Text,
Promo,
}
public class FlowPostTransient
{
public FlowPostTransient()
{
this.TrackUrns = new List<string>();
}
public long Id { get; set; }
public string Urn { get; set; }
public Guid UserId { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateModified { get; set; }
public Guid? TargetUserId { get; set; }
public long? ForwardedPostId { get; set; }
public Guid OriginUserId { get; set; }
public string OriginUserName { get; set; }
public Guid SourceUserId { get; set; }
public string SourceUserName { get; set; }
public string SubjectUrn { get; set; }
public string ContentUrn { get; set; }
public IList<string> TrackUrns { get; set; }
public string Caption { get; set; }
public Guid CaptionUserId { get; set; }
public string CaptionSourceName { get; set; }
public string ForwardedPostUrn { get; set; }
public FlowPostType PostType { get; set; }
public Guid? OnBehalfOfUserId { get; set; }
public static FlowPostTransient Create()
{
return new FlowPostTransient
{
Caption = "Caption",
CaptionSourceName = "CaptionSourceName",
CaptionUserId = Guid.NewGuid(),
ContentUrn = "ContentUrn",
DateAdded = DateTime.Now,
DateModified = DateTime.Now,
ForwardedPostId = 1,
ForwardedPostUrn = "ForwardedPostUrn",
Id = 1,
OnBehalfOfUserId = Guid.NewGuid(),
OriginUserId = Guid.NewGuid(),
OriginUserName = "OriginUserName",
PostType = FlowPostType.Content,
SourceUserId = Guid.NewGuid(),
SourceUserName = "SourceUserName",
SubjectUrn = "SubjectUrn ",
TargetUserId = Guid.NewGuid(),
TrackUrns = new List<string> { "track1", "track2" },
Urn = "Urn ",
UserId = Guid.NewGuid(),
};
}
public bool Equals(FlowPostTransient other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Id == Id && Equals(other.Urn, Urn) && other.UserId.Equals(UserId) && other.DateAdded.RoundToMs().Equals(DateAdded.RoundToMs()) && other.DateModified.RoundToMs().Equals(DateModified.RoundToMs()) && other.TargetUserId.Equals(TargetUserId) && other.ForwardedPostId.Equals(ForwardedPostId) && other.OriginUserId.Equals(OriginUserId) && Equals(other.OriginUserName, OriginUserName) && other.SourceUserId.Equals(SourceUserId) && Equals(other.SourceUserName, SourceUserName) && Equals(other.SubjectUrn, SubjectUrn) && Equals(other.ContentUrn, ContentUrn) && TrackUrns.EquivalentTo(other.TrackUrns) && Equals(other.Caption, Caption) && other.CaptionUserId.Equals(CaptionUserId) && Equals(other.CaptionSourceName, CaptionSourceName) && Equals(other.ForwardedPostUrn, ForwardedPostUrn) && Equals(other.PostType, PostType) && other.OnBehalfOfUserId.Equals(OnBehalfOfUserId);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(FlowPostTransient)) return false;
return Equals((FlowPostTransient)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = Id.GetHashCode();
result = (result * 397) ^ (Urn != null ? Urn.GetHashCode() : 0);
result = (result * 397) ^ UserId.GetHashCode();
result = (result * 397) ^ DateAdded.GetHashCode();
result = (result * 397) ^ DateModified.GetHashCode();
result = (result * 397) ^ (TargetUserId.HasValue ? TargetUserId.Value.GetHashCode() : 0);
result = (result * 397) ^ (ForwardedPostId.HasValue ? ForwardedPostId.Value.GetHashCode() : 0);
result = (result * 397) ^ OriginUserId.GetHashCode();
result = (result * 397) ^ (OriginUserName != null ? OriginUserName.GetHashCode() : 0);
result = (result * 397) ^ SourceUserId.GetHashCode();
result = (result * 397) ^ (SourceUserName != null ? SourceUserName.GetHashCode() : 0);
result = (result * 397) ^ (SubjectUrn != null ? SubjectUrn.GetHashCode() : 0);
result = (result * 397) ^ (ContentUrn != null ? ContentUrn.GetHashCode() : 0);
result = (result * 397) ^ (TrackUrns != null ? TrackUrns.GetHashCode() : 0);
result = (result * 397) ^ (Caption != null ? Caption.GetHashCode() : 0);
result = (result * 397) ^ CaptionUserId.GetHashCode();
result = (result * 397) ^ (CaptionSourceName != null ? CaptionSourceName.GetHashCode() : 0);
result = (result * 397) ^ (ForwardedPostUrn != null ? ForwardedPostUrn.GetHashCode() : 0);
result = (result * 397) ^ PostType.GetHashCode();
result = (result * 397) ^ (OnBehalfOfUserId.HasValue ? OnBehalfOfUserId.Value.GetHashCode() : 0);
return result;
}
}
}
[SetUp]
public void SetUp()
{
JsConfig.Reset();
}
[Test]
public void Can_Deserialize_text()
{
var dtoString = "[{Id:1,Urn:urn:post:3a944f18-920c-498a-832d-cf38fed3d0d7/1,UserId:3a944f18920c498a832dcf38fed3d0d7,DateAdded:2010-02-17T12:04:45.2845615Z,DateModified:2010-02-17T12:04:45.2845615Z,OriginUserId:3a944f18920c498a832dcf38fed3d0d7,OriginUserName:testuser1,SourceUserId:3a944f18920c498a832dcf38fed3d0d7,SourceUserName:testuser1,SubjectUrn:urn:track:1,ContentUrn:urn:track:1,TrackUrns:[],CaptionUserId:3a944f18920c498a832dcf38fed3d0d7,CaptionSourceName:testuser1,PostType:Content}]";
var fromString = TypeSerializer.DeserializeFromString<List<FlowPostTransient>>(dtoString);
}
[Test]
public void Can_Serialize_single_FlowPostTransient()
{
var dto = FlowPostTransient.Create();
SerializeAndCompare(dto);
}
[Test]
public void Can_serialize_jsv_dates()
{
var now = DateTime.Now;
var jsvDate = TypeSerializer.SerializeToString(now);
var fromJsvDate = TypeSerializer.DeserializeFromString<DateTime>(jsvDate);
Assert.That(fromJsvDate, Is.EqualTo(now));
}
[Test]
public void Can_serialize_json_dates()
{
var now = DateTime.Now;
var jsonDate = JsonSerializer.SerializeToString(now);
var fromJsonDate = JsonSerializer.DeserializeFromString<DateTime>(jsonDate);
Assert.That(fromJsonDate.RoundToMs(), Is.EqualTo(now.RoundToMs()));
}
[Test]
public void Can_Serialize_multiple_FlowPostTransient()
{
var dtos = new List<FlowPostTransient> {
FlowPostTransient.Create(),
FlowPostTransient.Create()
};
Serialize(dtos);
}
[DataContract]
public class TestObject
{
[DataMember]
public string Value { get; set; }
public TranslatedString ValueNoMember { get; set; }
public bool Equals(TestObject other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Value, Value);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(TestObject)) return false;
return Equals((TestObject)obj);
}
public override int GetHashCode()
{
return (Value != null ? Value.GetHashCode() : 0);
}
}
public class Test
{
public string Val { get; set; }
}
public class TestResponse
{
public TestObject Result { get; set; }
}
public class TranslatedString : ListDictionary
{
public string CurrentLanguage { get; set; }
public string Value
{
get
{
if (this.Contains(CurrentLanguage))
return this[CurrentLanguage] as string;
return null;
}
set
{
if (this.Contains(CurrentLanguage))
this[CurrentLanguage] = value;
else
Add(CurrentLanguage, value);
}
}
public TranslatedString()
{
CurrentLanguage = "en";
}
public static void SetLanguageOnStrings(string lang, params TranslatedString[] strings)
{
foreach (TranslatedString str in strings)
str.CurrentLanguage = lang;
}
}
[Test]
public void Should_ignore_non_DataMember_TranslatedString()
{
var dto = new TestObject
{
Value = "value",
ValueNoMember = new TranslatedString
{
{"key1", "val1"},
{"key2", "val2"},
}
};
SerializeAndCompare(dto);
}
public interface IParent
{
int Id { get; set; }
string ParentName { get; set; }
}
public class Parent : IParent
{
public int Id { get; set; }
public string ParentName { get; set; }
public Child Child { get; set; }
}
public class Child
{
public int Id { get; set; }
public string ChildName { get; set; }
public IParent Parent { get; set; }
}
[Test]
public void Can_Serialize_Cyclical_Dependency_via_interface()
{
JsConfig.PreferInterfaces = true;
var dto = new Parent
{
Id = 1,
ParentName = "Parent",
Child = new Child { Id = 2, ChildName = "Child" }
};
dto.Child.Parent = dto;
var fromDto = Serialize(dto, includeXml: false);
var parent = (IParent)fromDto.Child.Parent;
Assert.That(parent.Id, Is.EqualTo(dto.Id));
Assert.That(parent.ParentName, Is.EqualTo(dto.ParentName));
}
public class Exclude
{
public int Id { get; set; }
public string Key { get; set; }
}
[Test]
public void Can_exclude_properties()
{
JsConfig<Exclude>.ExcludePropertyNames = new[] { "Id" };
var dto = new Exclude { Id = 1, Key = "Value" };
Assert.That(dto.ToJson(), Is.EqualTo("{\"Key\":\"Value\"}"));
Assert.That(dto.ToJsv(), Is.EqualTo("{Key:Value}"));
}
[Test]
public void Can_exclude_properties_scoped() {
var dto = new Exclude {Id = 1, Key = "Value"};
using (var config = JsConfig.BeginScope()) {
config.ExcludePropertyReferences = new[] {"Exclude.Id"};
Assert.That(dto.ToJson(), Is.EqualTo("{\"Key\":\"Value\"}"));
Assert.That(dto.ToJsv(), Is.EqualTo("{Key:Value}"));
}
}
public class IncludeExclude {
public int Id { get; set; }
public string Name { get; set; }
public Exclude Obj { get; set; }
}
[Test]
public void Can_include_nested_only() {
var dto = new IncludeExclude {
Id = 1234,
Name = "TEST",
Obj = new Exclude {
Id = 1,
Key = "Value"
}
};
using (var config = JsConfig.BeginScope()) {
config.ExcludePropertyReferences = new[] { "Exclude.Id", "IncludeExclude.Id", "IncludeExclude.Name" };
Assert.That(dto.ToJson(), Is.EqualTo("{\"Obj\":{\"Key\":\"Value\"}}"));
Assert.That(dto.ToJsv(), Is.EqualTo("{Obj:{Key:Value}}"));
}
Assert.That(JsConfig.ExcludePropertyReferences, Is.EqualTo(null));
}
[Test]
public void Exclude_all_nested()
{
var dto = new IncludeExclude
{
Id = 1234,
Name = "TEST",
Obj = new Exclude
{
Id = 1,
Key = "Value"
}
};
using (var config = JsConfig.BeginScope())
{
config.ExcludePropertyReferences = new[] { "Exclude.Id", "Exclude.Key" };
Assert.AreEqual(2, config.ExcludePropertyReferences.Length);
var actual = dto.ToJson();
Assert.That(actual, Is.EqualTo("{\"Id\":1234,\"Name\":\"TEST\",\"Obj\":{}}"));
Assert.That(dto.ToJsv(), Is.EqualTo("{Id:1234,Name:TEST,Obj:{}}"));
}
}
public class ExcludeList {
public int Id { get; set; }
public List<Exclude> Excludes { get; set; }
}
[Test]
public void Exclude_List_Scope() {
var dto = new ExcludeList {
Id = 1234,
Excludes = new List<Exclude>() {
new Exclude {
Id = 2345,
Key = "Value"
},
new Exclude {
Id = 3456,
Key = "Value"
}
}
};
using (var config = JsConfig.BeginScope())
{
config.ExcludePropertyReferences = new[] { "ExcludeList.Id", "Exclude.Id" };
Assert.That(dto.ToJson(), Is.EqualTo("{\"Excludes\":[{\"Key\":\"Value\"},{\"Key\":\"Value\"}]}"));
Assert.That(dto.ToJsv(), Is.EqualTo("{Excludes:[{Key:Value},{Key:Value}]}"));
}
}
public class HasIndex
{
public int Id { get; set; }
public int this[int id]
{
get { return Id; }
set { Id = value; }
}
}
[Test]
public void Can_serialize_type_with_indexer()
{
var dto = new HasIndex { Id = 1 };
Serialize(dto);
}
public struct Size
{
public Size(string value)
{
var parts = value.Split(',');
this.Width = parts[0];
this.Height = parts[1];
}
public Size(string width, string height)
{
Width = width;
Height = height;
}
public string Width;
public string Height;
public override string ToString()
{
return this.Width + "," + this.Height;
}
}
[Test]
public void Can_serialize_struct_in_list()
{
var structs = new[] {
new Size("10px", "10px"),
new Size("20px", "20px"),
};
Serialize(structs);
}
[Test]
public void Can_serialize_list_of_bools()
{
Serialize(new List<bool> { true, false, true });
Serialize(new[] { true, false, true });
}
public class PolarValues
{
public int Int { get; set; }
public long Long { get; set; }
public float Float { get; set; }
public double Double { get; set; }
public decimal Decimal { get; set; }
public bool Equals(PolarValues other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Int == Int
&& other.Long == Long
&& other.Float.Equals(Float)
&& other.Double.Equals(Double)
&& other.Decimal == Decimal;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(PolarValues)) return false;
return Equals((PolarValues)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = Int;
result = (result * 397) ^ Long.GetHashCode();
result = (result * 397) ^ Float.GetHashCode();
result = (result * 397) ^ Double.GetHashCode();
result = (result * 397) ^ Decimal.GetHashCode();
return result;
}
}
}
[Test]
public void Can_serialize_max_values()
{
var dto = new PolarValues
{
Int = int.MaxValue,
Long = long.MaxValue,
Float = float.MaxValue,
Double = double.MaxValue,
Decimal = decimal.MaxValue,
};
var to = Serialize(dto);
Assert.That(to, Is.EqualTo(dto));
}
[Test]
public void Can_serialize_max_values_less_1()
{
var dto = new PolarValues
{
Int = int.MaxValue - 1,
Long = long.MaxValue - 1,
Float = float.MaxValue - 1,
Double = double.MaxValue - 1,
Decimal = decimal.MaxValue - 1,
};
var to = Serialize(dto);
Assert.That(to, Is.EqualTo(dto));
}
[Test]
public void Can_serialize_min_values()
{
var dto = new PolarValues
{
Int = int.MinValue,
Long = long.MinValue,
Float = float.MinValue,
Double = double.MinValue,
Decimal = decimal.MinValue,
};
var to = Serialize(dto);
Assert.That(to, Is.EqualTo(dto));
}
public class TestClass
{
public string Description { get; set; }
public TestClass Inner { get; set; }
}
[Test]
public void Can_serialize_1_level_cyclical_dto()
{
var dto = new TestClass
{
Description = "desc",
Inner = new TestClass { Description = "inner" }
};
var from = Serialize(dto, includeXml: false);
Assert.That(from.Description, Is.EqualTo(dto.Description));
Assert.That(from.Inner.Description, Is.EqualTo(dto.Inner.Description));
Console.WriteLine(from.Dump());
}
public enum EnumValues
{
Enum1,
Enum2,
Enum3,
}
[Test]
public void Can_Deserialize()
{
var items = TypeSerializer.DeserializeFromString<List<string>>(
"/CustomPath35/api,/CustomPath40/api,/RootPath35,/RootPath40,:82,:83,:5001/api,:5002/api,:5003,:5004");
Console.WriteLine(items.Dump());
}
[Test]
public void Can_Serialize_Array_of_enums()
{
var enumArr = new[] { EnumValues.Enum1, EnumValues.Enum2, EnumValues.Enum3, };
var json = JsonSerializer.SerializeToString(enumArr);
Assert.That(json, Is.EqualTo("[\"Enum1\",\"Enum2\",\"Enum3\"]"));
}
public class DictionaryEnumType
{
public Dictionary<EnumValues, Test> DictEnumType { get; set; }
}
[Test]
public void Can_Serialize_Dictionary_With_Enums()
{
Dictionary<EnumValues, Test> dictEnumType =
new Dictionary<EnumValues, Test>
{
{
EnumValues.Enum1, new Test { Val = "A Value" }
}
};
var item = new DictionaryEnumType
{
DictEnumType = dictEnumType
};
const string expected = "{\"DictEnumType\":{\"Enum1\":{\"Val\":\"A Value\"}}}";
var jsonItem = JsonSerializer.SerializeToString(item);
//Log(jsonItem);
Assert.That(jsonItem, Is.EqualTo(expected));
var deserializedItem = JsonSerializer.DeserializeFromString<DictionaryEnumType>(jsonItem);
Assert.That(deserializedItem, Is.TypeOf<DictionaryEnumType>());
}
[Test]
public void Can_Serialize_Array_of_chars()
{
var enumArr = new[] { 'A', 'B', 'C', };
var json = JsonSerializer.SerializeToString(enumArr);
Assert.That(json, Is.EqualTo("[\"A\",\"B\",\"C\"]"));
}
[Test]
public void Can_Serialize_Array_with_nulls()
{
var t = new
{
Name = "MyName",
Number = (int?)null,
Data = new object[] { 5, null, "text" }
};
ServiceStack.Text.JsConfig.IncludeNullValues = true;
var json = ServiceStack.Text.JsonSerializer.SerializeToString(t);
Assert.That(json, Is.EqualTo("{\"Name\":\"MyName\",\"Number\":null,\"Data\":[5,null,\"text\"]}"));
JsConfig.Reset();
}
class A
{
public string Value { get; set; }
}
[Test]
public void DumpFail()
{
var arrayOfA = new[] { new A { Value = "a" }, null, new A { Value = "b" } };
Console.WriteLine(arrayOfA.Dump());
}
[Test]
public void Deserialize_array_with_null_elements()
{
var json = "[{\"Value\": \"a\"},null,{\"Value\": \"b\"}]";
var o = JsonSerializer.DeserializeFromString<A[]>(json);
}
[Test]
public void Can_serialize_StringCollection()
{
var sc = new StringCollection { "one", "two", "three" };
var from = Serialize(sc, includeXml: false);
Console.WriteLine(from.Dump());
}
public class Breaker
{
public IEnumerable Blah { get; set; }
}
[Test]
public void Can_serialize_IEnumerable()
{
var dto = new Breaker
{
Blah = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
};
var from = Serialize(dto, includeXml: false);
Assert.IsNotNull(from.Blah);
from.PrintDump();
}
public class BreakerCollection
{
public ICollection Blah { get; set; }
}
[Test]
public void Can_serialize_ICollection()
{
var dto = new BreakerCollection
{
Blah = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
};
var from = Serialize(dto, includeXml: false);
Assert.IsNotNull(from.Blah);
Assert.AreEqual(dto.Blah.Count, from.Blah.Count);
from.PrintDump();
}
public class XmlAny
{
public XmlElement[] Any { get; set; }
}
[Test]
public void Can_serialize_Specialized_IEnumerable()
{
var getParseFn = JsvReader.GetParseFn(typeof (XmlAny));
Assert.IsNotNull(getParseFn);
}
}
}
| |
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 PhoneBook.Core.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlReaderSettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System.IO;
using System.Diagnostics;
using System.Security.Permissions;
#if !SILVERLIGHT
using Microsoft.Win32;
using System.Globalization;
using System.Security;
using System.Xml.Schema;
using System.Xml.XmlConfiguration;
#endif
using System.Runtime.Versioning;
namespace System.Xml {
// XmlReaderSettings class specifies basic features of an XmlReader.
#if !SILVERLIGHT && !MOBILE
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#endif
public sealed class XmlReaderSettings {
//
// Fields
//
#if ASYNC || FEATURE_NETCORE
bool useAsync;
#endif
// Nametable
XmlNameTable nameTable;
// XmlResolver
XmlResolver xmlResolver;
// Text settings
int lineNumberOffset;
int linePositionOffset;
// Conformance settings
ConformanceLevel conformanceLevel;
bool checkCharacters;
long maxCharactersInDocument;
long maxCharactersFromEntities;
// Filtering settings
bool ignoreWhitespace;
bool ignorePIs;
bool ignoreComments;
// security settings
DtdProcessing dtdProcessing;
#if !SILVERLIGHT
//Validation settings
ValidationType validationType;
XmlSchemaValidationFlags validationFlags;
XmlSchemaSet schemas;
ValidationEventHandler valEventHandler;
#endif
// other settings
bool closeInput;
// read-only flag
bool isReadOnly;
//
// Constructor
//
public XmlReaderSettings() {
Initialize();
}
#if !FEATURE_LEGACYNETCF
// introduced for supporting design-time loading of phone assemblies
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
#endif
public XmlReaderSettings(XmlResolver resolver) {
Initialize(resolver);
}
//
// Properties
//
#if ASYNC || FEATURE_NETCORE
public bool Async {
get {
return useAsync;
}
set {
CheckReadOnly("Async");
useAsync = value;
}
}
#endif
// Nametable
public XmlNameTable NameTable {
get {
return nameTable;
}
set {
CheckReadOnly("NameTable");
nameTable = value;
}
}
#if !SILVERLIGHT
// XmlResolver
internal bool IsXmlResolverSet {
get;
set; // keep set internal as we need to call it from the schema validation code
}
#endif
public XmlResolver XmlResolver {
set {
CheckReadOnly("XmlResolver");
xmlResolver = value;
#if !SILVERLIGHT
IsXmlResolverSet = true;
#endif
}
}
internal XmlResolver GetXmlResolver() {
return xmlResolver;
}
#if !SILVERLIGHT
//This is used by get XmlResolver in Xsd.
//Check if the config set to prohibit default resovler
//notice we must keep GetXmlResolver() to avoid dead lock when init System.Config.ConfigurationManager
internal XmlResolver GetXmlResolver_CheckConfig() {
if (System.Xml.XmlConfiguration.XmlReaderSection.ProhibitDefaultUrlResolver && !IsXmlResolverSet)
return null;
else
return xmlResolver;
}
#endif
// Text settings
public int LineNumberOffset {
get {
return lineNumberOffset;
}
set {
CheckReadOnly("LineNumberOffset");
lineNumberOffset = value;
}
}
public int LinePositionOffset {
get {
return linePositionOffset;
}
set {
CheckReadOnly("LinePositionOffset");
linePositionOffset = value;
}
}
// Conformance settings
public ConformanceLevel ConformanceLevel {
get {
return conformanceLevel;
}
set {
CheckReadOnly("ConformanceLevel");
if ((uint)value > (uint)ConformanceLevel.Document) {
throw new ArgumentOutOfRangeException("value");
}
conformanceLevel = value;
}
}
public bool CheckCharacters {
get {
return checkCharacters;
}
set {
CheckReadOnly("CheckCharacters");
checkCharacters = value;
}
}
public long MaxCharactersInDocument {
get {
return maxCharactersInDocument;
}
set {
CheckReadOnly("MaxCharactersInDocument");
if (value < 0) {
throw new ArgumentOutOfRangeException("value");
}
maxCharactersInDocument = value;
}
}
public long MaxCharactersFromEntities {
get {
return maxCharactersFromEntities;
}
set {
CheckReadOnly("MaxCharactersFromEntities");
if (value < 0) {
throw new ArgumentOutOfRangeException("value");
}
maxCharactersFromEntities = value;
}
}
// Filtering settings
public bool IgnoreWhitespace {
get {
return ignoreWhitespace;
}
set {
CheckReadOnly("IgnoreWhitespace");
ignoreWhitespace = value;
}
}
public bool IgnoreProcessingInstructions {
get {
return ignorePIs;
}
set {
CheckReadOnly("IgnoreProcessingInstructions");
ignorePIs = value;
}
}
public bool IgnoreComments {
get {
return ignoreComments;
}
set {
CheckReadOnly("IgnoreComments");
ignoreComments = value;
}
}
#if !SILVERLIGHT
[Obsolete("Use XmlReaderSettings.DtdProcessing property instead.")]
public bool ProhibitDtd {
get {
return dtdProcessing == DtdProcessing.Prohibit;
}
set {
CheckReadOnly("ProhibitDtd");
dtdProcessing = value ? DtdProcessing.Prohibit : DtdProcessing.Parse;
}
}
#endif
public DtdProcessing DtdProcessing {
get {
return dtdProcessing;
}
set {
CheckReadOnly("DtdProcessing");
if ((uint)value > (uint)DtdProcessing.Parse) {
throw new ArgumentOutOfRangeException("value");
}
dtdProcessing = value;
}
}
public bool CloseInput {
get {
return closeInput;
}
set {
CheckReadOnly("CloseInput");
closeInput = value;
}
}
#if !SILVERLIGHT
public ValidationType ValidationType {
get {
return validationType;
}
set {
CheckReadOnly("ValidationType");
if ((uint)value > (uint)ValidationType.Schema) {
throw new ArgumentOutOfRangeException("value");
}
validationType = value;
}
}
public XmlSchemaValidationFlags ValidationFlags {
get {
return validationFlags;
}
set {
CheckReadOnly("ValidationFlags");
if ((uint)value > (uint)(XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.AllowXmlAttributes)) {
throw new ArgumentOutOfRangeException("value");
}
validationFlags = value;
}
}
public XmlSchemaSet Schemas {
get {
if (schemas == null) {
schemas = new XmlSchemaSet();
}
return schemas;
}
set {
CheckReadOnly("Schemas");
schemas = value;
}
}
public event ValidationEventHandler ValidationEventHandler {
add {
CheckReadOnly("ValidationEventHandler");
valEventHandler += value;
}
remove {
CheckReadOnly("ValidationEventHandler");
valEventHandler -= value;
}
}
#endif
//
// Public methods
//
public void Reset() {
CheckReadOnly("Reset");
Initialize();
}
public XmlReaderSettings Clone() {
XmlReaderSettings clonedSettings = this.MemberwiseClone() as XmlReaderSettings;
clonedSettings.ReadOnly = false;
return clonedSettings;
}
//
// Internal methods
//
#if !SILVERLIGHT
internal ValidationEventHandler GetEventHandler() {
return valEventHandler;
}
#endif
#if !SILVERLIGHT
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
#endif
internal XmlReader CreateReader(String inputUri, XmlParserContext inputContext) {
if (inputUri == null) {
throw new ArgumentNullException("inputUri");
}
if (inputUri.Length == 0) {
throw new ArgumentException(Res.GetString(Res.XmlConvert_BadUri), "inputUri");
}
// resolve and open the url
XmlResolver tmpResolver = this.GetXmlResolver();
if (tmpResolver == null) {
tmpResolver = CreateDefaultResolver();
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(inputUri, this, inputContext, tmpResolver);
#if !SILVERLIGHT
// wrap with validating reader
if (this.ValidationType != ValidationType.None) {
reader = AddValidation(reader);
}
#endif
#if ASYNC
if (useAsync) {
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
#endif
return reader;
}
internal XmlReader CreateReader(Stream input, Uri baseUri, string baseUriString, XmlParserContext inputContext) {
if (input == null) {
throw new ArgumentNullException("input");
}
if (baseUriString == null) {
if (baseUri == null) {
baseUriString = string.Empty;
}
else {
baseUriString = baseUri.ToString();
}
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(input, null, 0, this, baseUri, baseUriString, inputContext, closeInput);
#if !SILVERLIGHT
// wrap with validating reader
if (this.ValidationType != ValidationType.None) {
reader = AddValidation(reader);
}
#endif
#if ASYNC
if (useAsync) {
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
#endif
return reader;
}
internal XmlReader CreateReader(TextReader input, string baseUriString, XmlParserContext inputContext) {
if (input == null) {
throw new ArgumentNullException("input");
}
if (baseUriString == null) {
baseUriString = string.Empty;
}
// create xml text reader
XmlReader reader = new XmlTextReaderImpl(input, this, baseUriString, inputContext);
#if !SILVERLIGHT
// wrap with validating reader
if (this.ValidationType != ValidationType.None) {
reader = AddValidation(reader);
}
#endif
#if ASYNC
if (useAsync) {
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
#endif
return reader;
}
internal XmlReader CreateReader(XmlReader reader) {
if (reader == null) {
throw new ArgumentNullException("reader");
}
#if !ASYNC || SILVERLIGHT || FEATURE_NETCORE
// wrap with conformance layer (if needed)
return AddConformanceWrapper(reader);
#else
return AddValidationAndConformanceWrapper(reader);
#endif // !ASYNC || SILVERLIGHT || FEATURE_NETCORE
}
internal bool ReadOnly {
get {
return isReadOnly;
}
set {
isReadOnly = value;
}
}
void CheckReadOnly(string propertyName) {
if (isReadOnly) {
throw new XmlException(Res.Xml_ReadOnlyProperty, this.GetType().Name + '.' + propertyName);
}
}
//
// Private methods
//
void Initialize() {
Initialize(null);
}
void Initialize(XmlResolver resolver) {
nameTable = null;
#if !SILVERLIGHT && !MOBILE
if (!EnableLegacyXmlSettings())
{
xmlResolver = resolver;
// limit the entity resolving to 10 million character. the caller can still
// override it to any other value or set it to zero for unlimiting it
maxCharactersFromEntities = (long) 1e7;
}
else
#endif
{
xmlResolver = (resolver == null ? CreateDefaultResolver() : resolver);
maxCharactersFromEntities = 0;
}
lineNumberOffset = 0;
linePositionOffset = 0;
checkCharacters = true;
conformanceLevel = ConformanceLevel.Document;
ignoreWhitespace = false;
ignorePIs = false;
ignoreComments = false;
dtdProcessing = DtdProcessing.Prohibit;
closeInput = false;
maxCharactersInDocument = 0;
#if !SILVERLIGHT
schemas = null;
validationType = ValidationType.None;
validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints;
validationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes;
#endif
#if ASYNC || FEATURE_NETCORE
useAsync = false;
#endif
isReadOnly = false;
#if !SILVERLIGHT
IsXmlResolverSet = false;
#endif
}
static XmlResolver CreateDefaultResolver() {
#if SILVERLIGHT
return new XmlXapResolver();
#else
return new XmlUrlResolver();
#endif
}
#if !SILVERLIGHT
internal XmlReader AddValidation(XmlReader reader) {
if (this.validationType == ValidationType.Schema) {
XmlResolver resolver = GetXmlResolver_CheckConfig();
if (resolver == null &&
!this.IsXmlResolverSet &&
!EnableLegacyXmlSettings())
{
resolver = new XmlUrlResolver();
}
reader = new XsdValidatingReader(reader, resolver, this);
}
else if (this.validationType == ValidationType.DTD) {
reader = CreateDtdValidatingReader(reader);
}
return reader;
}
private XmlReader AddValidationAndConformanceWrapper(XmlReader reader) {
// wrap with DTD validating reader
if (this.validationType == ValidationType.DTD) {
reader = CreateDtdValidatingReader(reader);
}
// add conformance checking (must go after DTD validation because XmlValidatingReader works only on XmlTextReader),
// but before XSD validation because of typed value access
reader = AddConformanceWrapper(reader);
if (this.validationType == ValidationType.Schema) {
reader = new XsdValidatingReader(reader, GetXmlResolver_CheckConfig(), this);
}
return reader;
}
private XmlValidatingReaderImpl CreateDtdValidatingReader(XmlReader baseReader) {
return new XmlValidatingReaderImpl(baseReader, this.GetEventHandler(), (this.ValidationFlags & XmlSchemaValidationFlags.ProcessIdentityConstraints) != 0);
}
#endif // !SILVERLIGHT
internal XmlReader AddConformanceWrapper(XmlReader baseReader) {
XmlReaderSettings baseReaderSettings = baseReader.Settings;
bool checkChars = false;
bool noWhitespace = false;
bool noComments = false;
bool noPIs = false;
DtdProcessing dtdProc = (DtdProcessing)(-1);
bool needWrap = false;
if (baseReaderSettings == null) {
#pragma warning disable 618
#if SILVERLIGHT
if (this.conformanceLevel != ConformanceLevel.Auto) {
throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString()));
}
#else
if (this.conformanceLevel != ConformanceLevel.Auto && this.conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader)) {
throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString()));
}
#endif
#if !SILVERLIGHT
// get the V1 XmlTextReader ref
XmlTextReader v1XmlTextReader = baseReader as XmlTextReader;
if (v1XmlTextReader == null) {
XmlValidatingReader vr = baseReader as XmlValidatingReader;
if (vr != null) {
v1XmlTextReader = (XmlTextReader)vr.Reader;
}
}
#endif
// assume the V1 readers already do all conformance checking;
// wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true;
if (this.ignoreWhitespace) {
WhitespaceHandling wh = WhitespaceHandling.All;
#if !SILVERLIGHT
// special-case our V1 readers to see if whey already filter whitespaces
if (v1XmlTextReader != null) {
wh = v1XmlTextReader.WhitespaceHandling;
}
#endif
if (wh == WhitespaceHandling.All) {
noWhitespace = true;
needWrap = true;
}
}
if (this.ignoreComments) {
noComments = true;
needWrap = true;
}
if (this.ignorePIs) {
noPIs = true;
needWrap = true;
}
// DTD processing
DtdProcessing baseDtdProcessing = DtdProcessing.Parse;
#if !SILVERLIGHT
if (v1XmlTextReader != null) {
baseDtdProcessing = v1XmlTextReader.DtdProcessing;
}
#endif
if ((this.dtdProcessing == DtdProcessing.Prohibit && baseDtdProcessing != DtdProcessing.Prohibit) ||
(this.dtdProcessing == DtdProcessing.Ignore && baseDtdProcessing == DtdProcessing.Parse)) {
dtdProc = this.dtdProcessing;
needWrap = true;
}
#pragma warning restore 618
}
else {
if (this.conformanceLevel != baseReaderSettings.ConformanceLevel && this.conformanceLevel != ConformanceLevel.Auto) {
throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString()));
}
if (this.checkCharacters && !baseReaderSettings.CheckCharacters) {
checkChars = true;
needWrap = true;
}
if (this.ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace) {
noWhitespace = true;
needWrap = true;
}
if (this.ignoreComments && !baseReaderSettings.IgnoreComments) {
noComments = true;
needWrap = true;
}
if (this.ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions) {
noPIs = true;
needWrap = true;
}
if ((this.dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit) ||
(this.dtdProcessing == DtdProcessing.Ignore && baseReaderSettings.DtdProcessing == DtdProcessing.Parse)) {
dtdProc = this.dtdProcessing;
needWrap = true;
}
}
if (needWrap) {
IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;
if (readerAsNSResolver != null) {
return new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
else {
return new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
}
else {
return baseReader;
}
}
#if !SILVERLIGHT
private static bool? s_enableLegacyXmlSettings = null;
static internal bool EnableLegacyXmlSettings()
{
if (s_enableLegacyXmlSettings.HasValue)
{
return s_enableLegacyXmlSettings.Value;
}
if (!System.Xml.BinaryCompatibility.TargetsAtLeast_Desktop_V4_5_2)
{
s_enableLegacyXmlSettings = true;
return s_enableLegacyXmlSettings.Value;
}
bool enableSettings = false; // default value
#if !MOBILE
if (!ReadSettingsFromRegistry(Registry.LocalMachine, ref enableSettings))
{
// still ok if this call return false too as we'll use the default value which is false
ReadSettingsFromRegistry(Registry.CurrentUser, ref enableSettings);
}
#endif
s_enableLegacyXmlSettings = enableSettings;
return s_enableLegacyXmlSettings.Value;
}
#if !MOBILE
[RegistryPermission(SecurityAction.Assert, Unrestricted = true)]
[SecuritySafeCritical]
private static bool ReadSettingsFromRegistry(RegistryKey hive, ref bool value)
{
const string regValueName = "EnableLegacyXmlSettings";
const string regValuePath = @"SOFTWARE\Microsoft\.NETFramework\XML";
try
{
using (RegistryKey xmlRegKey = hive.OpenSubKey(regValuePath, false))
{
if (xmlRegKey != null)
{
if (xmlRegKey.GetValueKind(regValueName) == RegistryValueKind.DWord)
{
value = ((int)xmlRegKey.GetValue(regValueName)) == 1;
return true;
}
}
}
}
catch { /* use the default if we couldn't read the key */ }
return false;
}
#endif // MOBILE
#endif // SILVERLIGHT
}
}
| |
/*
* 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.Data;
using System.Reflection;
using System.Collections.Generic;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A PGSQL Interface for the Asset server
/// </summary>
public class PGSQLAssetData : AssetDataBase
{
private const string _migrationStore = "AssetStore";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private long m_ticksToEpoch;
/// <summary>
/// Database manager
/// </summary>
private PGSQLManager m_database;
private string m_connectionString;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
#region IPlugin Members
override public void Dispose() { }
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
// [Obsolete("Cannot be default-initialized!")]
override public void Initialise()
{
m_log.Info("[PGSQLAssetData]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// Initialises asset interface
/// </summary>
/// <para>
/// a string instead of file, if someone writes the support
/// </para>
/// <param name="connectionString">connect string</param>
override public void Initialise(string connectionString)
{
m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks;
m_database = new PGSQLManager(connectionString);
m_connectionString = connectionString;
//New migration to check for DB changes
m_database.CheckMigration(_migrationStore);
}
/// <summary>
/// Database provider version.
/// </summary>
override public string Version
{
get { return m_database.getVersion(); }
}
/// <summary>
/// The name of this DB provider.
/// </summary>
override public string Name
{
get { return "PGSQL Asset storage engine"; }
}
#endregion
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset from m_database
/// </summary>
/// <param name="assetID">the asset UUID</param>
/// <returns></returns>
override public AssetBase GetAsset(UUID assetID)
{
string sql = "SELECT * FROM assets WHERE id = :id";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("id", assetID));
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
AssetBase asset = new AssetBase(
DBGuid.FromDB(reader["id"]),
(string)reader["name"],
Convert.ToSByte(reader["assetType"]),
reader["creatorid"].ToString()
);
// Region Main
asset.Description = (string)reader["description"];
asset.Local = Convert.ToBoolean(reader["local"]);
asset.Temporary = Convert.ToBoolean(reader["temporary"]);
asset.Flags = (AssetFlags)(Convert.ToInt32(reader["asset_flags"]));
asset.Data = (byte[])reader["data"];
return asset;
}
return null; // throw new Exception("No rows to return");
}
}
}
/// <summary>
/// Create asset in m_database
/// </summary>
/// <param name="asset">the asset</param>
override public void StoreAsset(AssetBase asset)
{
string sql =
@"UPDATE assets set name = :name, description = :description, " + "\"assetType\" " + @" = :assetType,
local = :local, temporary = :temporary, creatorid = :creatorid, data = :data
WHERE id=:id;
INSERT INTO assets
(id, name, description, " + "\"assetType\" " + @", local,
temporary, create_time, access_time, creatorid, asset_flags, data)
Select :id, :name, :description, :assetType, :local,
:temporary, :create_time, :access_time, :creatorid, :asset_flags, :data
Where not EXISTS(SELECT * FROM assets WHERE id=:id)
";
string assetName = asset.Name;
if (asset.Name.Length > 64)
{
assetName = asset.Name.Substring(0, 64);
m_log.WarnFormat(
"[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Name, asset.ID, asset.Name.Length, assetName.Length);
}
string assetDescription = asset.Description;
if (asset.Description.Length > 64)
{
assetDescription = asset.Description.Substring(0, 64);
m_log.WarnFormat(
"[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand command = new NpgsqlCommand(sql, conn))
{
int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
command.Parameters.Add(m_database.CreateParameter("name", assetName));
command.Parameters.Add(m_database.CreateParameter("description", assetDescription));
command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type));
command.Parameters.Add(m_database.CreateParameter("local", asset.Local));
command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary));
command.Parameters.Add(m_database.CreateParameter("access_time", now));
command.Parameters.Add(m_database.CreateParameter("create_time", now));
command.Parameters.Add(m_database.CreateParameter("asset_flags", (int)asset.Flags));
command.Parameters.Add(m_database.CreateParameter("creatorid", asset.Metadata.CreatorID));
command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
conn.Open();
try
{
command.ExecuteNonQuery();
}
catch(Exception e)
{
m_log.Error("[ASSET DB]: Error storing item :" + e.Message + " sql "+sql);
}
}
}
// Commented out since currently unused - this probably should be called in GetAsset()
// private void UpdateAccessTime(AssetBase asset)
// {
// using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = :access_time WHERE id=:id"))
// {
// int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
// cmd.Parameters.AddWithValue(":id", asset.FullID.ToString());
// cmd.Parameters.AddWithValue(":access_time", now);
// try
// {
// cmd.ExecuteNonQuery();
// }
// catch (Exception e)
// {
// m_log.Error(e.ToString());
// }
// }
// }
/// <summary>
/// Check if asset exist in m_database
/// </summary>
/// <param name="uuid"></param>
/// <returns>true if exist.</returns>
override public bool ExistsAsset(UUID uuid)
{
if (GetAsset(uuid) != null)
{
return true;
}
return false;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
string sql = @" SELECT id, name, description, " + "\"assetType\"" + @", temporary, creatorid
FROM assets
order by id
limit :stop
offset :start;";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("start", start));
cmd.Parameters.Add(m_database.CreateParameter("stop", start + count - 1));
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
AssetMetadata metadata = new AssetMetadata();
metadata.FullID = DBGuid.FromDB(reader["id"]);
metadata.Name = (string)reader["name"];
metadata.Description = (string)reader["description"];
metadata.Type = Convert.ToSByte(reader["assetType"]);
metadata.Temporary = Convert.ToBoolean(reader["temporary"]);
metadata.CreatorID = (string)reader["creatorid"];
retList.Add(metadata);
}
}
}
return retList;
}
public override bool Delete(string id)
{
return false;
}
#endregion
}
}
| |
//
// 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 Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing Products.
/// </summary>
internal partial class ProductsOperations : IServiceOperations<ApiManagementClient>, IProductsOperations
{
/// <summary>
/// Initializes a new instance of the ProductsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ProductsOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create new product.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='parameters'>
/// Required. Create or update parameters.
/// </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> CreateAsync(string resourceGroupName, string serviceName, string pid, ProductCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.ProductContract == null)
{
throw new ArgumentNullException("parameters.ProductContract");
}
if (parameters.ProductContract.Name == null)
{
throw new ArgumentNullException("parameters.ProductContract.Name");
}
if (parameters.ProductContract.Name.Length > 300)
{
throw new ArgumentOutOfRangeException("parameters.ProductContract.Name");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject productCreateParametersValue = new JObject();
requestDoc = productCreateParametersValue;
if (parameters.ProductContract.IdPath != null)
{
productCreateParametersValue["id"] = parameters.ProductContract.IdPath;
}
productCreateParametersValue["name"] = parameters.ProductContract.Name;
if (parameters.ProductContract.Description != null)
{
productCreateParametersValue["description"] = parameters.ProductContract.Description;
}
if (parameters.ProductContract.Terms != null)
{
productCreateParametersValue["terms"] = parameters.ProductContract.Terms;
}
if (parameters.ProductContract.SubscriptionRequired != null)
{
productCreateParametersValue["subscriptionRequired"] = parameters.ProductContract.SubscriptionRequired.Value;
}
if (parameters.ProductContract.ApprovalRequired != null)
{
productCreateParametersValue["approvalRequired"] = parameters.ProductContract.ApprovalRequired.Value;
}
if (parameters.ProductContract.SubscriptionsLimit != null)
{
productCreateParametersValue["subscriptionsLimit"] = parameters.ProductContract.SubscriptionsLimit.Value;
}
productCreateParametersValue["state"] = parameters.ProductContract.State.ToString();
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// 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.Created && statusCode != HttpStatusCode.NoContent)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
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 product.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <param name='deleteSubscriptions'>
/// Required. Delete existing subscriptions to the product ot not.
/// </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 resourceGroupName, string serviceName, string pid, string etag, bool deleteSubscriptions, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("etag", etag);
tracingParameters.Add("deleteSubscriptions", deleteSubscriptions);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
queryParameters.Add("deleteSubscriptions=" + Uri.EscapeDataString(deleteSubscriptions.ToString().ToLower()));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
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>
/// Get specific product.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Get Product operation response details.
/// </returns>
public async Task<ProductGetResponse> GetAsync(string resourceGroupName, string serviceName, string pid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProductGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProductGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ProductContract valueInstance = new ProductContract();
result.Value = valueInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
valueInstance.IdPath = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
valueInstance.Name = nameInstance;
}
JToken descriptionValue = responseDoc["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
valueInstance.Description = descriptionInstance;
}
JToken termsValue = responseDoc["terms"];
if (termsValue != null && termsValue.Type != JTokenType.Null)
{
string termsInstance = ((string)termsValue);
valueInstance.Terms = termsInstance;
}
JToken subscriptionRequiredValue = responseDoc["subscriptionRequired"];
if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null)
{
bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue);
valueInstance.SubscriptionRequired = subscriptionRequiredInstance;
}
JToken approvalRequiredValue = responseDoc["approvalRequired"];
if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null)
{
bool approvalRequiredInstance = ((bool)approvalRequiredValue);
valueInstance.ApprovalRequired = approvalRequiredInstance;
}
JToken subscriptionsLimitValue = responseDoc["subscriptionsLimit"];
if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null)
{
int subscriptionsLimitInstance = ((int)subscriptionsLimitValue);
valueInstance.SubscriptionsLimit = subscriptionsLimitInstance;
}
JToken stateValue = responseDoc["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true));
valueInstance.State = stateInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
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>
/// List all products.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Products operation response details.
/// </returns>
public async Task<ProductListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProductListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProductListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ProductPaged resultInstance = new ProductPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ProductContract productContractInstance = new ProductContract();
resultInstance.Values.Add(productContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
productContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
productContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
productContractInstance.Description = descriptionInstance;
}
JToken termsValue = valueValue["terms"];
if (termsValue != null && termsValue.Type != JTokenType.Null)
{
string termsInstance = ((string)termsValue);
productContractInstance.Terms = termsInstance;
}
JToken subscriptionRequiredValue = valueValue["subscriptionRequired"];
if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null)
{
bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue);
productContractInstance.SubscriptionRequired = subscriptionRequiredInstance;
}
JToken approvalRequiredValue = valueValue["approvalRequired"];
if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null)
{
bool approvalRequiredInstance = ((bool)approvalRequiredValue);
productContractInstance.ApprovalRequired = approvalRequiredInstance;
}
JToken subscriptionsLimitValue = valueValue["subscriptionsLimit"];
if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null)
{
int subscriptionsLimitInstance = ((int)subscriptionsLimitValue);
productContractInstance.SubscriptionsLimit = subscriptionsLimitInstance;
}
JToken stateValue = valueValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true));
productContractInstance.State = stateInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
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>
/// List all products.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Products operation response details.
/// </returns>
public async Task<ProductListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ProductListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ProductListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ProductPaged resultInstance = new ProductPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ProductContract productContractInstance = new ProductContract();
resultInstance.Values.Add(productContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
productContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
productContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
productContractInstance.Description = descriptionInstance;
}
JToken termsValue = valueValue["terms"];
if (termsValue != null && termsValue.Type != JTokenType.Null)
{
string termsInstance = ((string)termsValue);
productContractInstance.Terms = termsInstance;
}
JToken subscriptionRequiredValue = valueValue["subscriptionRequired"];
if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null)
{
bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue);
productContractInstance.SubscriptionRequired = subscriptionRequiredInstance;
}
JToken approvalRequiredValue = valueValue["approvalRequired"];
if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null)
{
bool approvalRequiredInstance = ((bool)approvalRequiredValue);
productContractInstance.ApprovalRequired = approvalRequiredInstance;
}
JToken subscriptionsLimitValue = valueValue["subscriptionsLimit"];
if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null)
{
int subscriptionsLimitInstance = ((int)subscriptionsLimitValue);
productContractInstance.SubscriptionsLimit = subscriptionsLimitInstance;
}
JToken stateValue = valueValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true));
productContractInstance.State = stateInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
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>
/// Update product.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='parameters'>
/// Required. Update parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </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> UpdateAsync(string resourceGroupName, string serviceName, string pid, ProductUpdateParameters parameters, string etag, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name != null && parameters.Name.Length > 300)
{
throw new ArgumentOutOfRangeException("parameters.Name");
}
if (etag == null)
{
throw new ArgumentNullException("etag");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("etag", etag);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject productUpdateParametersValue = new JObject();
requestDoc = productUpdateParametersValue;
if (parameters.Name != null)
{
productUpdateParametersValue["name"] = parameters.Name;
}
if (parameters.Description != null)
{
productUpdateParametersValue["description"] = parameters.Description;
}
if (parameters.Terms != null)
{
productUpdateParametersValue["terms"] = parameters.Terms;
}
if (parameters.SubscriptionRequired != null)
{
productUpdateParametersValue["subscriptionRequired"] = parameters.SubscriptionRequired.Value;
}
if (parameters.ApprovalRequired != null)
{
productUpdateParametersValue["approvalRequired"] = parameters.ApprovalRequired.Value;
}
if (parameters.SubscriptionsLimit != null)
{
productUpdateParametersValue["subscriptionsLimit"] = parameters.SubscriptionsLimit.Value;
}
if (parameters.State != null)
{
productUpdateParametersValue["state"] = parameters.State.Value.ToString();
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
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();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
//
// This class implements the Julian calendar. In 48 B.C. Julius Caesar ordered a calendar reform, and this calendar
// is called Julian calendar. It consisted of a solar year of twelve months and of 365 days with an extra day
// every fourth year.
//*
//* Calendar support range:
//* Calendar Minimum Maximum
//* ========== ========== ==========
//* Gregorian 0001/01/01 9999/12/31
//* Julia 0001/01/03 9999/10/19
[System.Runtime.InteropServices.ComVisible(true)]
public class JulianCalendar : Calendar
{
public static readonly int JulianEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
// Number of days in a non-leap year
private const int JulianDaysPerYear = 365;
// Number of days in 4 years
private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
//internal static Calendar m_defaultInstance;
private static readonly int[] s_daysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
private static readonly int[] s_daysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
// Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19
// keep it as variable field for serialization compat.
internal int MaxYear = 9999;
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
// Return the type of the Julian calendar.
//
//[System.Runtime.InteropServices.ComVisible(false)]
//public override CalendarAlgorithmType AlgorithmType
//{
// get
// {
// return CalendarAlgorithmType.SolarCalendar;
// }
//}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of JulianCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance() {
if (m_defaultInstance == null) {
m_defaultInstance = new JulianCalendar();
}
return (m_defaultInstance);
}
*/
// Construct an instance of gregorian calendar.
public JulianCalendar()
{
// There is no system setting of TwoDigitYear max, so set the value here.
twoDigitYearMax = 2029;
}
internal override CalendarId ID
{
get
{
return CalendarId.JULIAN;
}
}
static internal void CheckEraRange(int era)
{
if (era != CurrentEra && era != JulianEra)
{
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal void CheckYearEraRange(int year, int era)
{
CheckEraRange(era);
if (year <= 0 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
}
static internal void CheckMonthRange(int month)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
}
/*=================================GetDefaultInstance==========================
**Action: Check for if the day value is valid.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make
** sure year/month values are correct.
============================================================================*/
static internal void CheckDayRange(int year, int month, int day)
{
if (year == 1 && month == 1)
{
// The mimimum supported Julia date is Julian 0001/01/03.
if (day < 3)
{
throw new ArgumentOutOfRangeException(null,
SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
bool isLeapYear = (year % 4) == 0;
int[] days = isLeapYear ? s_daysToMonth366 : s_daysToMonth365;
int monthDays = days[month] - days[month - 1];
if (day < 1 || day > monthDays)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
monthDays));
}
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
static internal int GetDatePart(long ticks, int part)
{
// Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001.
// The following line convert Gregorian ticks to Julian ticks.
long julianTicks = ticks + TicksPerDay * 2;
// n = number of days since 1/1/0001
int n = (int)(julianTicks / TicksPerDay);
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / JulianDaysPer4Years;
// n = day number within 4-year period
n -= y4 * JulianDaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / JulianDaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * JulianDaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3);
int[] days = leapYear ? s_daysToMonth366 : s_daysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = n >> 5 + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
// Returns the tick count corresponding to the given year, month, and day.
static internal long DateToTicks(int year, int month, int day)
{
int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365;
int y = year - 1;
int n = y * 365 + y / 4 + days[month - 1] + day - 1;
// Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar.
// Therefore, we subtract two days in the following to convert the ticks in JulianCalendar
// to ticks in Gregorian calendar.
return ((n - 2) * TicksPerDay);
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? s_daysToMonth366 : s_daysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365;
return (days[month] - days[month - 1]);
}
public override int GetDaysInYear(int year, int era)
{
// Year/Era range is done in IsLeapYear().
return (IsLeapYear(year, era) ? 366 : 365);
}
public override int GetEra(DateTime time)
{
return (JulianEra);
}
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
public override int[] Eras
{
get
{
return (new int[] { JulianEra });
}
}
public override int GetMonthsInYear(int year, int era)
{
CheckYearEraRange(year, era);
return (12);
}
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
CheckMonthRange(month);
// Year/Era range check is done in IsLeapYear().
if (IsLeapYear(year, era))
{
CheckDayRange(year, month, day);
return (month == 2 && day == 29);
}
CheckDayRange(year, month, day);
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
CheckYearEraRange(year, era);
return (0);
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearEraRange(year, era);
return (year % 4 == 0);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
CheckDayRange(year, month, day);
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
"millisecond",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
MillisPerSecond - 1));
}
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks);
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
}
public override int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year > MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
1,
MaxYear));
}
return (base.ToFourDigitYear(year));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Security;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
internal sealed class DynamicWinsockMethods
{
// In practice there will never be more than four of these, so its not worth a complicated
// hash table structure. Store them in a list and search through it.
private static List<DynamicWinsockMethods> s_methodTable = new List<DynamicWinsockMethods>();
public static DynamicWinsockMethods GetMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
lock (s_methodTable)
{
DynamicWinsockMethods methods;
for (int i = 0; i < s_methodTable.Count; i++)
{
methods = s_methodTable[i];
if (methods._addressFamily == addressFamily && methods._socketType == socketType && methods._protocolType == protocolType)
{
return methods;
}
}
methods = new DynamicWinsockMethods(addressFamily, socketType, protocolType);
s_methodTable.Add(methods);
return methods;
}
}
private AddressFamily _addressFamily;
private SocketType _socketType;
private ProtocolType _protocolType;
private object _lockObject;
private AcceptExDelegate _acceptEx;
private GetAcceptExSockaddrsDelegate _getAcceptExSockaddrs;
private ConnectExDelegate _connectEx;
private TransmitPacketsDelegate _transmitPackets;
private DisconnectExDelegate _disconnectEx;
private DisconnectExDelegateBlocking _disconnectExBlocking;
private WSARecvMsgDelegate _recvMsg;
private WSARecvMsgDelegateBlocking _recvMsgBlocking;
private DynamicWinsockMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
_addressFamily = addressFamily;
_socketType = socketType;
_protocolType = protocolType;
_lockObject = new object();
}
public T GetDelegate<T>(SafeCloseSocket socketHandle)
where T : class
{
if (typeof(T) == typeof(AcceptExDelegate))
{
EnsureAcceptEx(socketHandle);
Debug.Assert(_acceptEx != null);
return (T)(object)_acceptEx;
}
else if (typeof(T) == typeof(GetAcceptExSockaddrsDelegate))
{
EnsureGetAcceptExSockaddrs(socketHandle);
Debug.Assert(_getAcceptExSockaddrs != null);
return (T)(object)_getAcceptExSockaddrs;
}
else if (typeof(T) == typeof(ConnectExDelegate))
{
EnsureConnectEx(socketHandle);
Debug.Assert(_connectEx != null);
return (T)(object)_connectEx;
}
else if (typeof(T) == typeof(DisconnectExDelegate))
{
EnsureDisconnectEx(socketHandle);
return (T)(object)_disconnectEx;
}
else if (typeof(T) == typeof(DisconnectExDelegateBlocking))
{
EnsureDisconnectEx(socketHandle);
return (T)(object)_disconnectExBlocking;
}
else if (typeof(T) == typeof(WSARecvMsgDelegate))
{
EnsureWSARecvMsg(socketHandle);
Debug.Assert(_recvMsg != null);
return (T)(object)_recvMsg;
}
else if (typeof(T) == typeof(WSARecvMsgDelegateBlocking))
{
EnsureWSARecvMsgBlocking(socketHandle);
Debug.Assert(_recvMsgBlocking != null);
return (T)(object)_recvMsgBlocking;
}
else if (typeof(T) == typeof(TransmitPacketsDelegate))
{
EnsureTransmitPackets(socketHandle);
Debug.Assert(_transmitPackets != null);
return (T)(object)_transmitPackets;
}
System.Diagnostics.Debug.Assert(false, "Invalid type passed to DynamicWinsockMethods.GetDelegate");
return null;
}
// Private methods that actually load the function pointers.
private IntPtr LoadDynamicFunctionPointer(SafeCloseSocket socketHandle, ref Guid guid)
{
IntPtr ptr = IntPtr.Zero;
int length;
SocketError errorCode;
unsafe
{
errorCode = Interop.Winsock.WSAIoctl(
socketHandle,
Interop.Winsock.IoctlSocketConstants.SIOGETEXTENSIONFUNCTIONPOINTER,
ref guid,
sizeof(Guid),
out ptr,
sizeof(IntPtr),
out length,
IntPtr.Zero,
IntPtr.Zero);
}
if (errorCode != SocketError.Success)
{
throw new SocketException();
}
return ptr;
}
// NOTE: the volatile writes in the functions below are necessary to ensure that all writes
// to the fields of the delegate instances are visible before the write to the field
// that holds the reference to the delegate instance.
private void EnsureAcceptEx(SafeCloseSocket socketHandle)
{
if (_acceptEx == null)
{
lock (_lockObject)
{
if (_acceptEx == null)
{
Guid guid = new Guid("{0xb5367df1,0xcbac,0x11cf,{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}");
IntPtr ptrAcceptEx = LoadDynamicFunctionPointer(socketHandle, ref guid);
Volatile.Write(ref _acceptEx, Marshal.GetDelegateForFunctionPointer<AcceptExDelegate>(ptrAcceptEx));
}
}
}
}
private void EnsureGetAcceptExSockaddrs(SafeCloseSocket socketHandle)
{
if (_getAcceptExSockaddrs == null)
{
lock (_lockObject)
{
if (_getAcceptExSockaddrs == null)
{
Guid guid = new Guid("{0xb5367df2,0xcbac,0x11cf,{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}");
IntPtr ptrGetAcceptExSockaddrs = LoadDynamicFunctionPointer(socketHandle, ref guid);
Volatile.Write(ref _getAcceptExSockaddrs, Marshal.GetDelegateForFunctionPointer<GetAcceptExSockaddrsDelegate>(ptrGetAcceptExSockaddrs));
}
}
}
}
private void EnsureConnectEx(SafeCloseSocket socketHandle)
{
if (_connectEx == null)
{
lock (_lockObject)
{
if (_connectEx == null)
{
Guid guid = new Guid("{0x25a207b9,0x0ddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}}");
IntPtr ptrConnectEx = LoadDynamicFunctionPointer(socketHandle, ref guid);
Volatile.Write(ref _connectEx, Marshal.GetDelegateForFunctionPointer<ConnectExDelegate>(ptrConnectEx));
}
}
}
}
private void EnsureDisconnectEx(SafeCloseSocket socketHandle)
{
if (_disconnectEx == null)
{
lock (_lockObject)
{
if (_disconnectEx == null)
{
Guid guid = new Guid("{0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}");
IntPtr ptrDisconnectEx = LoadDynamicFunctionPointer(socketHandle, ref guid);
_disconnectExBlocking = Marshal.GetDelegateForFunctionPointer<DisconnectExDelegateBlocking>(ptrDisconnectEx);
Volatile.Write(ref _disconnectEx, Marshal.GetDelegateForFunctionPointer<DisconnectExDelegate>(ptrDisconnectEx));
}
}
}
}
private void EnsureWSARecvMsg(SafeCloseSocket socketHandle)
{
if (_recvMsg == null)
{
lock (_lockObject)
{
if (_recvMsg == null)
{
Guid guid = new Guid("{0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}");
IntPtr ptrWSARecvMsg = LoadDynamicFunctionPointer(socketHandle, ref guid);
_recvMsgBlocking = Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegateBlocking>(ptrWSARecvMsg);
Volatile.Write(ref _recvMsg, Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegate>(ptrWSARecvMsg));
}
}
}
}
private void EnsureWSARecvMsgBlocking(SafeCloseSocket socketHandle)
{
if (_recvMsgBlocking == null)
{
lock (_lockObject)
{
if (_recvMsgBlocking == null)
{
Guid guid = new Guid("{0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}");
IntPtr ptrWSARecvMsg = LoadDynamicFunctionPointer(socketHandle, ref guid);
Volatile.Write(ref _recvMsgBlocking, Marshal.GetDelegateForFunctionPointer<WSARecvMsgDelegateBlocking>(ptrWSARecvMsg));
}
}
}
}
private void EnsureTransmitPackets(SafeCloseSocket socketHandle)
{
if (_transmitPackets == null)
{
lock (_lockObject)
{
if (_transmitPackets == null)
{
Guid guid = new Guid("{0xd9689da0,0x1f90,0x11d3,{0x99,0x71,0x00,0xc0,0x4f,0x68,0xc8,0x76}}");
IntPtr ptrTransmitPackets = LoadDynamicFunctionPointer(socketHandle, ref guid);
Volatile.Write(ref _transmitPackets, Marshal.GetDelegateForFunctionPointer<TransmitPacketsDelegate>(ptrTransmitPackets));
}
}
}
}
}
internal delegate bool AcceptExDelegate(
SafeCloseSocket listenSocketHandle,
SafeCloseSocket acceptSocketHandle,
IntPtr buffer,
int len,
int localAddressLength,
int remoteAddressLength,
out int bytesReceived,
SafeHandle overlapped);
internal delegate void GetAcceptExSockaddrsDelegate(
IntPtr buffer,
int receiveDataLength,
int localAddressLength,
int remoteAddressLength,
out IntPtr localSocketAddress,
out int localSocketAddressLength,
out IntPtr remoteSocketAddress,
out int remoteSocketAddressLength);
internal delegate bool ConnectExDelegate(
SafeCloseSocket socketHandle,
IntPtr socketAddress,
int socketAddressSize,
IntPtr buffer,
int dataLength,
out int bytesSent,
SafeHandle overlapped);
internal delegate bool DisconnectExDelegate(
SafeCloseSocket socketHandle,
SafeHandle overlapped,
int flags,
int reserved);
internal delegate bool DisconnectExDelegateBlocking(
SafeCloseSocket socketHandle,
IntPtr overlapped,
int flags,
int reserved);
internal delegate SocketError WSARecvMsgDelegate(
SafeCloseSocket socketHandle,
IntPtr msg,
out int bytesTransferred,
SafeHandle overlapped,
IntPtr completionRoutine);
internal delegate SocketError WSARecvMsgDelegateBlocking(
IntPtr socketHandle,
IntPtr msg,
out int bytesTransferred,
IntPtr overlapped,
IntPtr completionRoutine);
internal delegate bool TransmitPacketsDelegate(
SafeCloseSocket socketHandle,
IntPtr packetArray,
int elementCount,
int sendSize,
SafeNativeOverlapped overlapped,
TransmitFileOptions flags);
}
| |
// 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.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.AspNetCore.Routing.Template;
using Xunit;
namespace Microsoft.AspNetCore.Routing.Tree
{
public class LinkGenerationDecisionTreeTest
{
[Fact]
public void GetMatches_AllowsNullAmbientValues()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry = CreateMatch(new { });
entries.Add(entry);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { });
// Act
var matches = tree.GetMatches(context.Values, ambientValues: null);
// Assert
Assert.Same(entry, Assert.Single(matches).Match);
}
[Fact]
public void SelectSingleEntry_NoCriteria()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry = CreateMatch(new { });
entries.Add(entry);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues);
// Assert
Assert.Same(entry, Assert.Single(matches).Match);
}
[Fact]
public void SelectSingleEntry_MultipleCriteria()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry = CreateMatch(new { controller = "Store", action = "Buy" });
entries.Add(entry);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Store", action = "Buy" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues);
// Assert
Assert.Same(entry, Assert.Single(matches).Match);
}
[Fact]
public void SelectSingleEntry_MultipleCriteria_AmbientValues()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry = CreateMatch(new { controller = "Store", action = "Buy" });
entries.Add(entry);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(values: null, ambientValues: new { controller = "Store", action = "Buy" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues);
// Assert
var match = Assert.Single(matches);
Assert.Same(entry, match.Match);
Assert.False(match.IsFallbackMatch);
}
[Fact]
public void SelectSingleEntry_MultipleCriteria_Replaced()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry = CreateMatch(new { controller = "Store", action = "Buy" });
entries.Add(entry);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(
values: new { action = "Buy" },
ambientValues: new { controller = "Store", action = "Cart" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues);
// Assert
var match = Assert.Single(matches);
Assert.Same(entry, match.Match);
Assert.False(match.IsFallbackMatch);
}
[Fact]
public void SelectSingleEntry_MultipleCriteria_AmbientValue_Ignored()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry = CreateMatch(new { controller = "Store", action = (string)null });
entries.Add(entry);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(
values: new { controller = "Store" },
ambientValues: new { controller = "Store", action = "Buy" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues);
// Assert
var match = Assert.Single(matches);
Assert.Same(entry, match.Match);
Assert.True(match.IsFallbackMatch);
}
[Fact]
public void SelectSingleEntry_MultipleCriteria_NoMatch()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry = CreateMatch(new { controller = "Store", action = "Buy" });
entries.Add(entry);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Store", action = "AddToCart" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues);
// Assert
Assert.Empty(matches);
}
[Fact]
public void SelectSingleEntry_MultipleCriteria_AmbientValue_NoMatch()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry = CreateMatch(new { controller = "Store", action = "Buy" });
entries.Add(entry);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(
values: new { controller = "Store" },
ambientValues: new { controller = "Store", action = "Cart" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues);
// Assert
Assert.Empty(matches);
}
[Fact]
public void SelectMultipleEntries_OneDoesntMatch()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Store", action = "Buy" });
entries.Add(entry1);
var entry2 = CreateMatch(new { controller = "Store", action = "Cart" });
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(
values: new { controller = "Store" },
ambientValues: new { controller = "Store", action = "Buy" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues);
// Assert
Assert.Same(entry1, Assert.Single(matches).Match);
}
[Fact]
public void SelectMultipleEntries_BothMatch_CriteriaSubset()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Store", action = "Buy" });
entries.Add(entry1);
var entry2 = CreateMatch(new { controller = "Store" });
entry2.Entry.Order = 1;
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(
values: new { controller = "Store" },
ambientValues: new { controller = "Store", action = "Buy" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Equal(entries, matches);
}
[Fact]
public void SelectMultipleEntries_BothMatch_NonOverlappingCriteria()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Store", action = "Buy" });
entries.Add(entry1);
var entry2 = CreateMatch(new { slug = "1234" });
entry2.Entry.Order = 1;
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Store", action = "Buy", slug = "1234" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Equal(entries, matches);
}
// Precedence is ignored for sorting because they have different order
[Fact]
public void SelectMultipleEntries_BothMatch_OrderedByOrder()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Store", action = "Buy" });
entry1.Entry.Precedence = 0;
entries.Add(entry1);
var entry2 = CreateMatch(new { controller = "Store", action = "Buy" });
entry2.Entry.Order = 1;
entry2.Entry.Precedence = 1;
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Store", action = "Buy" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Equal(entries, matches);
}
// Precedence is used for sorting because they have the same order
[Fact]
public void SelectMultipleEntries_BothMatch_OrderedByPrecedence()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Store", action = "Buy" });
entry1.Entry.Precedence = 1;
entries.Add(entry1);
var entry2 = CreateMatch(new { controller = "Store", action = "Buy" });
entry2.Entry.Precedence = 0;
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Store", action = "Buy" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Equal(entries, matches);
}
// Template is used for sorting because they have the same order
[Fact]
public void SelectMultipleEntries_BothMatch_OrderedByTemplate()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Store", action = "Buy" });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { controller = "Store", action = "Buy" });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Store", action = "Buy" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Equal(entries, matches);
}
[Fact]
public void GetMatches_ControllersWithArea_AllValuesExplicit()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Store", action = "Buy", area = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { controller = "Store", action = "Buy", area = "Admin" });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Store", action = "Buy", area = "Admin" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
// Assert
Assert.Collection(
matches,
m => { Assert.Same(entry2, m); });
}
[Fact]
public void GetMatches_ControllersWithArea_SomeValuesAmbient()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Store", action = "Buy", area = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { controller = "Store", action = "Buy", area = "Admin" });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Store", }, new { action = "Buy", area = "Admin", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Collection(
matches,
m => { Assert.Same(entry2, m); },
m => { Assert.Same(entry1, m); });
}
[Fact]
public void GetMatches_ControllersWithArea_AllValuesAmbient()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Store", action = "Buy", area = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { controller = "Store", action = "Buy", area = "Admin" });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { }, new { controller = "Store", action = "Buy", area = "Admin", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Collection(
matches,
m => { Assert.Same(entry2, m); },
m => { Assert.Same(entry1, m); });
}
[Fact]
public void GetMatches_PagesWithArea_AllValuesExplicit()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { page = "/Store/Buy", area = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = "Admin" });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { page = "/Store/Buy", area = "Admin" });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Collection(
matches,
m => { Assert.Same(entry2, m); });
}
[Fact]
public void GetMatches_PagesWithArea_SomeValuesAmbient()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { page = "/Store/Buy", area = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = "Admin" });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { page = "/Store/Buy", }, new { area = "Admin", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Collection(
matches,
m => { Assert.Same(entry2, m); },
m => { Assert.Same(entry1, m); });
}
[Fact]
public void GetMatches_PagesWithArea_AllValuesAmbient()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { page = "/Store/Buy", area = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = "Admin" });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { }, new { page = "/Store/Buy", area = "Admin", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Collection(
matches,
m => { Assert.Same(entry2, m); },
m => { Assert.Same(entry1, m); });
}
[Fact]
public void GetMatches_LinkToControllerFromPage()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Home", action = "Index", }, new { page = "/Store/Buy", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Collection(
matches,
m => { Assert.Same(entry1, m); });
}
[Fact]
public void GetMatches_LinkToControllerFromPage_WithArea()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = "Admin", page = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = "Admin", controller = (string)null, action = (string)null, });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Home", action = "Index", }, new { page = "/Store/Buy", area = "Admin", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Collection(
matches,
m => { Assert.Same(entry1, m); });
}
[Fact]
public void GetMatches_LinkToControllerFromPage_WithPageValue()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Home", action = "Index", page = "16", }, new { page = "/Store/Buy", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Empty(matches);
}
[Fact]
public void GetMatches_LinkToControllerFromPage_WithPageValueAmbiguous()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { controller = "Home", action = "Index", page = "/Store/Buy", }, new { page = "/Store/Buy", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Empty(matches);
}
[Fact]
public void GetMatches_LinkToPageFromController()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { page = "/Store/Buy", }, new { controller = "Home", action = "Index", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Collection(
matches,
m => { Assert.Same(entry2, m); });
}
[Fact]
public void GetMatches_LinkToPageFromController_WithArea()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = "Admin", page = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = "Admin", controller = (string)null, action = (string)null, });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { page = "/Store/Buy", }, new { controller = "Home", action = "Index", area = "Admin", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Collection(
matches,
m => { Assert.Same(entry2, m); });
}
[Fact]
public void GetMatches_LinkToPageFromController_WithActionValue()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { page = "/Store/Buy", action = "buy", }, new { controller = "Home", action = "Index", page = "16", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Empty(matches);
}
[Fact]
public void GetMatches_LinkToPageFromController_WithActionValueAmbiguous()
{
// Arrange
var entries = new List<OutboundMatch>();
var entry1 = CreateMatch(new { controller = "Home", action = "Index", area = (string)null, page = (string)null, });
entry1.Entry.RouteTemplate = TemplateParser.Parse("a");
entries.Add(entry1);
var entry2 = CreateMatch(new { page = "/Store/Buy", area = (string)null, controller = (string)null, action = (string)null, });
entry2.Entry.RouteTemplate = TemplateParser.Parse("b");
entries.Add(entry2);
var tree = new LinkGenerationDecisionTree(entries);
var context = CreateContext(new { page = "/Store/Buy", action = "Index", }, new { controller = "Home", action = "Index", page = "16", });
// Act
var matches = tree.GetMatches(context.Values, context.AmbientValues).Select(m => m.Match).ToList();
// Assert
Assert.Empty(matches);
}
[Fact]
public void ToDebuggerDisplayString_GivesAFlattenedTree()
{
// Arrange
var entries = new List<OutboundMatch>();
entries.Add(CreateMatch(new { action = "Buy", controller = "Store", version = "V1" }, "Store/Buy/V1"));
entries.Add(CreateMatch(new { action = "Buy", controller = "Store", area = "Admin" }, "Admin/Store/Buy"));
entries.Add(CreateMatch(new { action = "Buy", controller = "Products" }, "Products/Buy"));
entries.Add(CreateMatch(new { action = "Buy", controller = "Store", version = "V2" }, "Store/Buy/V2"));
entries.Add(CreateMatch(new { action = "Cart", controller = "Store" }, "Store/Cart"));
entries.Add(CreateMatch(new { action = "Index", controller = "Home" }, "Home/Index/{id?}"));
var tree = new LinkGenerationDecisionTree(entries);
var newLine = Environment.NewLine;
var expected =
" => action: Buy => controller: Store => version: V1 (Matches: Store/Buy/V1)" + newLine +
" => action: Buy => controller: Store => version: V2 (Matches: Store/Buy/V2)" + newLine +
" => action: Buy => controller: Store => area: Admin (Matches: Admin/Store/Buy)" + newLine +
" => action: Buy => controller: Products (Matches: Products/Buy)" + newLine +
" => action: Cart => controller: Store (Matches: Store/Cart)" + newLine +
" => action: Index => controller: Home (Matches: Home/Index/{id?})" + newLine;
// Act
var flattenedTree = tree.DebuggerDisplayString;
// Assert
Assert.Equal(expected, flattenedTree);
}
private OutboundMatch CreateMatch(object requiredValues, string routeTemplate = null)
{
var match = new OutboundMatch();
match.Entry = new OutboundRouteEntry();
match.Entry.RequiredLinkValues = new RouteValueDictionary(requiredValues);
if (!string.IsNullOrEmpty(routeTemplate))
{
match.Entry.RouteTemplate = new RouteTemplate(RoutePatternFactory.Parse(routeTemplate));
}
return match;
}
private VirtualPathContext CreateContext(object values, object ambientValues = null)
{
var context = new VirtualPathContext(
new DefaultHttpContext(),
new RouteValueDictionary(ambientValues),
new RouteValueDictionary(values));
return context;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Operation_Cronos.Display;
namespace Operation_Cronos
{
public enum Align
{
Right,
Left
}
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class SpriteText : DrawableGameComponent, IStackable, IPositionable
{
private SpriteFont font;
private string text = string.Empty;
private int x;
private int y;
private int xrel;
private int yrel;
private int stackOrder;
private Color tint = Color.White;
/// <summary>
/// Default value = 100
/// </summary>
private int maxLength = 500;
private Boolean isVisible;
private Align align;
#region Properties
public Align TextAlignment
{
set { align = value; }
get { return align; }
}
public int MaxLength
{
get { return maxLength; }
set { maxLength = value; }
}
public string Text
{
get { return text; }
set
{
if (value.Length <= maxLength)
{
text = value;
}
}
}
//-----------------------properties used to implement IStackable and IPositionable
public int X
{
get { return x; }
set { x = value; }
}
public int Y
{
get { return y; }
set { y = value; }
}
/// <summary>
/// The width of the texture.
/// </summary>
public int Width
{
get { return (int)font.MeasureString(Text).X; }
set { }
}
/// <summary>
/// The height of the texture.
/// </summary>
public int Height
{
get { return (int)font.MeasureString(Text).Y; }
set { }
}
/// <summary>
/// The X location of the SpriteText relative to its parent.
/// </summary>
public int XRelative
{
get { return xrel; }
set { xrel = value; }
}
/// <summary>
/// The Y location of the SpriteText relative to its parent.
/// </summary>
public int YRelative
{
get { return yrel; }
set { yrel = value; }
}
public Boolean Collides(Point position)
{
return false;
}
public Boolean CollidesTile(Point position)
{
return false;
}
public int StackOrder
{
get { return stackOrder; }
set { stackOrder = value; }
}
public Color Tint {
get { return tint; }
set { tint = value; }
}
public Boolean IsVisible {
get { return isVisible; }
set { isVisible = value; Visible = value; }
}
//--------------------------------------------------------------
#endregion
/// <summary>
/// SpriteText Constructor.
/// </summary>
/// <param name="game">The current game</param>
/// <param name="_font">The font associated with the text.</param>
public SpriteText(Game game, SpriteFont _font)
: base(game) {
font = _font;
IsVisible = true;
Game.Components.Add(this);
align = Align.Left;
}
/// <summary>
/// SpriteText Constructor.
/// </summary>
/// <param name="game">The current game.</param>
/// <param name="x">The x coordonate of the SpriteText.</param>
/// <param name="y">The y coordonate of the SpriteText.</param>
/// <param name="_font">The font asociated to the text</param>
/// <param name="_text">The text that will be written</param>
public SpriteText(Game game, int _x, int _y, SpriteFont _font, string _text)
: base(game)
{
x = _x;
y = _y;
this.font = _font;
this.text = _text;
Game.Components.Add(this);
align = Align.Left;
}
#region SplitTextToRows
/// <summary>
/// Distributes the Text to rows, so that the SpriteText will fit into
/// a given width
/// </summary>
public void SplitTextToRows(int width)
{
//will contain the final string, in rows
string initialString = this.Text;
this.Text = "";
//will contain the final string, split into rows, to fit the given width
string finalString = "";
//will contain a word from the initialString
string wordString = "";
//will contain a row of words from the initialString, fitting into the given width
string rowString = "";
//---counting the words of the initial text
int wordCount = 0;
for (int i = 0; i < initialString.Length; i++)
if (initialString[i] == ' ')
wordCount++;
if (initialString.Length > initialString.LastIndexOf(' '))
//the text does not end with ' ', so there is one
//more word left after the last ' '.
wordCount++;
//----------------------------------------
//for each word in the initial text..
for (int i = 0; i < wordCount; i++)
{
if (i < (wordCount - 1)) //if the current word is not the last word
{
wordString = initialString.Substring(0, initialString.IndexOf(' '));
}
else//the current word is the last word
{
wordString = initialString;
}
//if the word can be added to rowString without exceding the given width
//then it is added and also removed from the initial string, along with the
//' ' that precedes it
this.Text = rowString + " " + wordString;
if (this.Width <= width)
{
if (wordString != "")
rowString += " ";
rowString += wordString;
if (i < (wordCount - 1)) //this is not the last word
{
//the word is removed from the initial string
initialString = initialString.Substring(initialString.IndexOf(' ') + 1);
}
else //this is the last word
{
//it is added to the final String
if (finalString != "")
finalString += "\n";
finalString += rowString;
}
}
//by adding the word, the rowString excedes the given width.
//the word is not added to rowString, but rowString
//is added to the end of finalString
else
{
if (finalString != "")
finalString += "\n";
finalString += rowString;
//because the current word needs to be processed again
//and added to the next rowString
i--;
rowString = "";
}
this.Text = "";
}
this.Text = finalString;
}
#endregion
#region Override
public override void Draw(GameTime gameTime)
{
SpriteBatch spriteBatch = (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch));
if (align == Align.Left)
{
spriteBatch.DrawString(font, text, new Vector2(x, y), tint);
}
else
{
spriteBatch.DrawString(font, text, new Vector2(x-Width, y), tint);
}
base.Draw(gameTime);
}
#endregion
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
//
// Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Text;
using System.IO;
#if NET_ZIP
using System.IO.Compression;
#else
using PdfSharp.SharpZipLib.Zip.Compression;
using PdfSharp.SharpZipLib.Zip.Compression.Streams;
#endif
namespace PdfSharp.Pdf.Filters
{
/// <summary>
/// Implements the FlateDecode filter by wrapping SharpZipLib.
/// </summary>
public class FlateDecode : Filter
{
/// <summary>
/// Encodes the specified data.
/// </summary>
public override byte[] Encode(byte[] data)
{
MemoryStream ms = new MemoryStream();
// DeflateStream/GZipStream does not work immediately and I have not the leisure to work it out.
// So I keep on using SharpZipLib even with .NET 2.0.
#if NET_ZIP
// See http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97064
//
// Excerpt from the RFC 1950 specs for first byte:
//
// CMF (Compression Method and flags)
// This byte is divided into a 4-bit compression method and a 4-
// bit information field depending on the compression method.
//
// bits 0 to 3 CM Compression method
// bits 4 to 7 CINFO Compression info
//
// CM (Compression method)
// This identifies the compression method used in the file. CM = 8
// denotes the "deflate" compression method with a window size up
// to 32K. This is the method used by gzip and PNG (see
// references [1] and [2] in Chapter 3, below, for the reference
// documents). CM = 15 is reserved. It might be used in a future
// version of this specification to indicate the presence of an
// extra field before the compressed data.
//
// CINFO (Compression info)
// For CM = 8, CINFO is the base-2 logarithm of the LZ77 window
// size, minus eight (CINFO=7 indicates a 32K window size). Values
// of CINFO above 7 are not allowed in this version of the
// specification. CINFO is not defined in this specification for
// CM not equal to 8.
ms.WriteByte(0x78);
// Excerpt from the RFC 1950 specs for second byte:
//
// FLG (FLaGs)
// This flag byte is divided as follows:
//
// bits 0 to 4 FCHECK (check bits for CMF and FLG)
// bit 5 FDICT (preset dictionary)
// bits 6 to 7 FLEVEL (compression level)
//
// The FCHECK value must be such that CMF and FLG, when viewed as
// a 16-bit unsigned integer stored in MSB order (CMF*256 + FLG),
// is a multiple of 31.
//
// FDICT (Preset dictionary)
// If FDICT is set, a DICT dictionary identifier is present
// immediately after the FLG byte. The dictionary is a sequence of
// bytes which are initially fed to the compressor without
// producing any compressed output. DICT is the Adler-32 checksum
// of this sequence of bytes (see the definition of ADLER32
// below). The decompressor can use this identifier to determine
// which dictionary has been used by the compressor.
//
// FLEVEL (Compression level)
// These flags are available for use by specific compression
// methods. The "deflate" method (CM = 8) sets these flags as
// follows:
//
// 0 - compressor used fastest algorithm
// 1 - compressor used fast algorithm
// 2 - compressor used default algorithm
// 3 - compressor used maximum compression, slowest algorithm
//
// The information in FLEVEL is not needed for decompression; it
// is there to indicate if recompression might be worthwhile.
ms.WriteByte(0x49);
DeflateStream zip = new DeflateStream(ms, CompressionMode.Compress, true);
zip.Write(data, 0, data.Length);
zip.Close();
#else
DeflaterOutputStream zip = new DeflaterOutputStream(ms, new Deflater(Deflater.DEFAULT_COMPRESSION, false));
zip.Write(data, 0, data.Length);
zip.Finish();
#endif
ms.Capacity = (int)ms.Length;
return ms.GetBuffer();
}
/// <summary>
/// Encodes the specified data.
/// </summary>
public byte[] Encode(byte[] data, PdfFlateEncodeMode mode)
{
MemoryStream ms = new MemoryStream();
// DeflateStream/GZipStream does not work immediately and I have not the leisure to work it out.
// So I keep on using SharpZipLib even with .NET 2.0.
#if NET_ZIP
// See http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97064
//
// Excerpt from the RFC 1950 specs for first byte:
//
// CMF (Compression Method and flags)
// This byte is divided into a 4-bit compression method and a 4-
// bit information field depending on the compression method.
//
// bits 0 to 3 CM Compression method
// bits 4 to 7 CINFO Compression info
//
// CM (Compression method)
// This identifies the compression method used in the file. CM = 8
// denotes the "deflate" compression method with a window size up
// to 32K. This is the method used by gzip and PNG (see
// references [1] and [2] in Chapter 3, below, for the reference
// documents). CM = 15 is reserved. It might be used in a future
// version of this specification to indicate the presence of an
// extra field before the compressed data.
//
// CINFO (Compression info)
// For CM = 8, CINFO is the base-2 logarithm of the LZ77 window
// size, minus eight (CINFO=7 indicates a 32K window size). Values
// of CINFO above 7 are not allowed in this version of the
// specification. CINFO is not defined in this specification for
// CM not equal to 8.
ms.WriteByte(0x78);
// Excerpt from the RFC 1950 specs for second byte:
//
// FLG (FLaGs)
// This flag byte is divided as follows:
//
// bits 0 to 4 FCHECK (check bits for CMF and FLG)
// bit 5 FDICT (preset dictionary)
// bits 6 to 7 FLEVEL (compression level)
//
// The FCHECK value must be such that CMF and FLG, when viewed as
// a 16-bit unsigned integer stored in MSB order (CMF*256 + FLG),
// is a multiple of 31.
//
// FDICT (Preset dictionary)
// If FDICT is set, a DICT dictionary identifier is present
// immediately after the FLG byte. The dictionary is a sequence of
// bytes which are initially fed to the compressor without
// producing any compressed output. DICT is the Adler-32 checksum
// of this sequence of bytes (see the definition of ADLER32
// below). The decompressor can use this identifier to determine
// which dictionary has been used by the compressor.
//
// FLEVEL (Compression level)
// These flags are available for use by specific compression
// methods. The "deflate" method (CM = 8) sets these flags as
// follows:
//
// 0 - compressor used fastest algorithm
// 1 - compressor used fast algorithm
// 2 - compressor used default algorithm
// 3 - compressor used maximum compression, slowest algorithm
//
// The information in FLEVEL is not needed for decompression; it
// is there to indicate if recompression might be worthwhile.
ms.WriteByte(0x49);
DeflateStream zip = new DeflateStream(ms, CompressionMode.Compress, true);
zip.Write(data, 0, data.Length);
zip.Close();
#else
int level = Deflater.DEFAULT_COMPRESSION;
switch (mode)
{
case PdfFlateEncodeMode.BestCompression:
level = Deflater.BEST_COMPRESSION;
break;
case PdfFlateEncodeMode.BestSpeed:
level = Deflater.BEST_SPEED;
break;
}
DeflaterOutputStream zip = new DeflaterOutputStream(ms, new Deflater(level, false));
zip.Write(data, 0, data.Length);
zip.Finish();
#endif
#if !NETFX_CORE && !UWP
ms.Capacity = (int)ms.Length;
return ms.GetBuffer();
#else
return ms.ToArray();
#endif
}
/// <summary>
/// Decodes the specified data.
/// </summary>
public override byte[] Decode(byte[] data, FilterParms parms)
{
MemoryStream msInput = new MemoryStream(data);
MemoryStream msOutput = new MemoryStream();
#if NET_ZIP
// See http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97064
// It seems to work when skipping the first two bytes.
byte header; // 0x30 0x59
header = (byte)msInput.ReadByte();
//Debug.Assert(header == 48);
header = (byte)msInput.ReadByte();
//Debug.Assert(header == 89);
DeflateStream zip = new DeflateStream(msInput, CompressionMode.Decompress, true);
int cbRead;
byte[] abResult = new byte[1024];
do
{
cbRead = zip.Read(abResult, 0, abResult.Length);
if (cbRead > 0)
msOutput.Write(abResult, 0, cbRead);
}
while (cbRead > 0);
zip.Close();
msOutput.Flush();
if (msOutput.Length >= 0)
{
msOutput.Capacity = (int)msOutput.Length;
return msOutput.GetBuffer();
}
return null;
#else
InflaterInputStream iis = new InflaterInputStream(msInput, new Inflater(false));
int cbRead;
byte[] abResult = new byte[32768];
do
{
cbRead = iis.Read(abResult, 0, abResult.Length);
if (cbRead > 0)
msOutput.Write(abResult, 0, cbRead);
}
while (cbRead > 0);
iis.Close();
msOutput.Flush();
if (msOutput.Length >= 0)
{
msOutput.Capacity = (int)msOutput.Length;
return msOutput.GetBuffer();
}
return null;
#endif
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Xml;
using Reporting.Rdl.Utility;
using System.Globalization;
namespace Reporting.Rdl
{
///<summary>
/// Collection of report parameters.
///</summary>
[Serializable]
internal class ReportParameters : ReportLink, ICollection
{
IDictionary _Items; // list of report items
internal ReportParameters(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
if (xNode.ChildNodes.Count < 10)
_Items = new ListDictionary(); // Hashtable is overkill for small lists
else
_Items = new Hashtable(xNode.ChildNodes.Count);
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
if (xNodeLoop.Name == "ReportParameter")
{
ReportParameter rp = new ReportParameter(r, this, xNodeLoop);
if (rp.Name != null)
_Items.Add(rp.Name.Nm, rp);
}
else
OwnerReport.rl.LogError(4, "Unknown ReportParameters element '" + xNodeLoop.Name + "' ignored.");
}
}
internal void SetRuntimeValues(Report rpt, IDictionary parms)
{
// Fill the values to use in the report parameters
foreach (string pname in parms.Keys) // Loop thru the passed parameters
{
ReportParameter rp = (ReportParameter) _Items[pname];
if (rp == null)
{ // When not found treat it as a warning message
if (!pname.StartsWith("rs:")) // don't care about report server parameters
rpt.rl.LogError(4, "Unknown ReportParameter passed '" + pname + "' ignored.");
continue;
}
// Search for the valid values
object parmValue = parms[pname];
if (parmValue is string && rp.ValidValues != null)
{
string[] dvs = rp.ValidValues.DisplayValues(rpt);
if (dvs != null && dvs.Length > 0)
{
for (int i = 0; i < dvs.Length; i++)
{
if (dvs[i] == (string) parmValue)
{
object[] dv = rp.ValidValues.DataValues(rpt);
parmValue = dv[i];
break;
}
}
}
}
rp.SetRuntimeValue(rpt, parmValue);
}
return;
}
override internal void FinalPass()
{
foreach (ReportParameter rp in _Items.Values)
{
rp.FinalPass();
}
return;
}
internal IDictionary Items
{
get { return _Items; }
}
#region ICollection Members
public bool IsSynchronized
{
get
{
return _Items.IsSynchronized;
}
}
public int Count
{
get
{
return _Items.Count;
}
}
public void CopyTo(Array array, int index)
{
_Items.CopyTo(array, index);
}
public object SyncRoot
{
get
{
return _Items.SyncRoot;
}
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return _Items.Values.GetEnumerator();
}
#endregion
}
///<summary>
/// Represent a report parameter (name, default value, runtime value,
///</summary>
[Serializable]
internal class ReportParameter : ReportLink
{
Name _Name; // Name of the parameter
// Note: Parameter names need only be
// unique within the containing Parameters collection
TypeCode _dt; // The data type of the parameter
bool _NumericType = false; // true if _dt is a numeric type
bool _Nullable; // Indicates the value for this parameter is allowed to be Null.
DefaultValue _DefaultValue; // Default value to use for the parameter (if not provided by the user)
// If no value is provided as a part of the
// definition or by the user, the value is
// null. Required if there is no Prompt and
// either Nullable is False or a ValidValues
// list is provided that does not contain Null
// (an omitted Value).
bool _AllowBlank; // Indicates the value for this parameter is
// allowed to be the empty string. Ignored
// if DataType is not string.
string _Prompt; // The user prompt to display when asking
// for parameter values
// If omitted, the user should not be
// prompted for a value for this parameter.
ValidValues _ValidValues; // Possible values for the parameter (for an
// end-user prompting interface)
bool _Hidden = false; // indicates parameter should not be showed to user
bool _MultiValue = false; // indicates parameter is a collection - expressed as 0 based arrays Parameters!p1.Value(0)
TrueFalseAutoEnum _UsedInQuery; // Enum True | False | Auto (default)
// Indicates whether or not the parameter is
// used in a query in the report. This is
// needed to determine if the queries need
// to be re-executed if the parameter
// changes. Auto indicates the
// UsedInQuery setting should be
// autodetected as follows: True if the
// parameter is referenced in any query
// value expression.
internal ReportParameter(ReportDefn r, ReportLink p, XmlNode xNode)
: base(r, p)
{
_Name = null;
_dt = TypeCode.Object;
_Nullable = false;
_DefaultValue = null;
_AllowBlank = false;
_Prompt = null;
_ValidValues = null;
_UsedInQuery = TrueFalseAutoEnum.Auto;
// Run thru the attributes
foreach (XmlAttribute xAttr in xNode.Attributes)
{
switch (xAttr.Name)
{
case "Name":
_Name = new Name(xAttr.Value);
break;
}
}
// Loop thru all the child nodes
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "DataType":
_dt = DataType.GetStyle(xNodeLoop.InnerText, this.OwnerReport);
_NumericType = DataType.IsNumeric(_dt);
break;
case "Nullable":
_Nullable = Conversion.ToBoolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "DefaultValue":
_DefaultValue = new DefaultValue(r, this, xNodeLoop);
break;
case "AllowBlank":
_AllowBlank = Conversion.ToBoolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "Prompt":
_Prompt = xNodeLoop.InnerText;
break;
case "Hidden":
_Hidden = Conversion.ToBoolean(xNodeLoop.InnerText, OwnerReport.rl);
OwnerReport.rl.LogError(4, "ReportParameter element Hidden is currently ignored."); // TODO
break;
case "MultiValue":
_MultiValue = Conversion.ToBoolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "ValidValues":
_ValidValues = new ValidValues(r, this, xNodeLoop);
break;
case "UsedInQuery":
_UsedInQuery = TrueFalseAuto.GetStyle(xNodeLoop.InnerText, OwnerReport.rl);
break;
default:
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown ReportParameter element '" + xNodeLoop.Name + "' ignored.");
break;
}
}
if (_Name == null)
OwnerReport.rl.LogError(8, "ReportParameter name is required but not specified.");
if (_dt == TypeCode.Object)
OwnerReport.rl.LogError(8, string.Format("ReportParameter DataType is required but not specified or invalid for {0}.", _Name == null ? "<unknown name>" : _Name.Nm));
}
override internal void FinalPass()
{
if (_DefaultValue != null)
_DefaultValue.FinalPass();
if (_ValidValues != null)
_ValidValues.FinalPass();
return;
}
internal Name Name
{
get { return _Name; }
set { _Name = value; }
}
internal object GetRuntimeValue(Report rpt)
{
object rtv = rpt == null ? null :
rpt.Cache.Get(this, "runtimevalue");
if (rtv != null)
return rtv;
if (_DefaultValue == null)
return null;
object[] result = _DefaultValue.GetValue(rpt);
if (result == null)
return null;
object v = result[0];
if (v is String && _NumericType)
v = ConvertStringToNumber((string)v);
rtv = Convert.ChangeType(v, _dt);
if (rpt != null)
rpt.Cache.Add(this, "runtimevalue", rtv);
return rtv;
}
internal ArrayList GetRuntimeValues(Report rpt)
{
ArrayList rtv = rpt == null ? null :
(ArrayList)rpt.Cache.Get(this, "rtvs");
if (rtv != null)
return rtv;
if (_DefaultValue == null)
return null;
object[] result = _DefaultValue.GetValue(rpt);
if (result == null)
return null;
ArrayList ar = new ArrayList(result.Length);
foreach (object v in result)
{
object nv = v;
if (nv is String && _NumericType)
nv = ConvertStringToNumber((string)nv);
ar.Add(Convert.ChangeType(nv, _dt));
}
if (rpt != null)
rpt.Cache.Add(this, "rtvs", ar);
return ar;
}
internal void SetRuntimeValue(Report rpt, object v)
{
if (this.MultiValue)
{ // ok to only set one parameter of multiValue; but we still save as MultiValue
ArrayList ar;
if (v is string)
{ // when the value is a string we parse it looking for multiple arguments
ParameterLexer pl = new ParameterLexer(v as string);
ar = pl.Lex();
}
else if (v is ICollection)
{ // when collection put it in local array
ar = new ArrayList(v as ICollection);
}
else
{
ar = new ArrayList(1);
ar.Add(v);
}
SetRuntimeValues(rpt, ar);
return;
}
object rtv;
//Added from Forum, User: solidstore http://www.fyireporting.com/forum/viewtopic.php?t=905
if (v is Guid)
v = ((Guid)v).ToString("B");
if (!AllowBlank && _dt == TypeCode.String && (string)v == "")
throw new ArgumentException(string.Format("Empty string isn't allowed for {0}.", Name.Nm));
try
{
if (v is String && _NumericType)
v = ConvertStringToNumber((string)v);
rtv = Convert.ChangeType(v, _dt);
}
catch (Exception e)
{
// illegal parameter passed
string err = "Illegal parameter value for '" + Name.Nm + "' provided. Value =" + v.ToString();
if (rpt == null)
OwnerReport.rl.LogError(4, err);
else
rpt.rl.LogError(4, err);
throw new ArgumentException(string.Format("Unable to convert '{0}' to {1} for {2}", v, _dt, Name.Nm), e);
}
rpt.Cache.AddReplace(this, "runtimevalue", rtv);
}
internal void SetRuntimeValues(Report rpt, ArrayList vs)
{
if (!this.MultiValue)
throw new ArgumentException(string.Format("{0} is not a MultiValue parameter. SetRuntimeValues only valid for MultiValue parameters", this.Name.Nm));
ArrayList ar = new ArrayList(vs.Count);
foreach (object v in vs)
{
object rtv;
if (!AllowBlank && _dt == TypeCode.String && (string)v == "")
{
string err = string.Format("Empty string isn't allowed for {0}.", Name.Nm);
if (rpt == null)
OwnerReport.rl.LogError(4, err);
else
rpt.rl.LogError(4, err);
throw new ArgumentException(err);
}
try
{
object nv = v;
if (nv is String && _NumericType)
nv = ConvertStringToNumber((string)nv);
rtv = Convert.ChangeType(nv, _dt);
ar.Add(rtv);
}
catch (Exception e)
{
// illegal parameter passed
string err = "Illegal parameter value for '" + Name.Nm + "' provided. Value =" + v.ToString();
if (rpt == null)
OwnerReport.rl.LogError(4, err);
else
rpt.rl.LogError(4, err);
throw new ArgumentException(string.Format("Unable to convert '{0}' to {1} for {2}", v, _dt, Name.Nm), e);
}
}
rpt.Cache.AddReplace(this, "rtvs", ar);
}
private object ConvertStringToNumber(string newv)
{
// remove any commas, currency symbols (internationalized)
NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
newv = newv.Replace(nfi.NumberGroupSeparator, "");
newv = newv.Replace(nfi.CurrencySymbol, "");
return newv;
}
internal TypeCode dt
{
get { return _dt; }
set { _dt = value; }
}
internal bool Nullable
{
get { return _Nullable; }
set { _Nullable = value; }
}
internal bool Hidden
{
get { return _Hidden; }
set { _Hidden = value; }
}
internal bool MultiValue
{
get { return _MultiValue; }
set { _MultiValue = value; }
}
internal DefaultValue DefaultValue
{
get { return _DefaultValue; }
set { _DefaultValue = value; }
}
internal bool AllowBlank
{
get { return _AllowBlank; }
set { _AllowBlank = value; }
}
internal string Prompt
{
get { return _Prompt; }
set { _Prompt = value; }
}
internal ValidValues ValidValues
{
get { return _ValidValues; }
set { _ValidValues = value; }
}
internal TrueFalseAutoEnum UsedInQuery
{
get { return _UsedInQuery; }
set { _UsedInQuery = value; }
}
}
/// <summary>
/// Public class used to pass user provided report parameters.
/// </summary>
public class UserReportParameter
{
Report _rpt;
ReportParameter _rp;
object[] _DefaultValue;
string[] _DisplayValues;
object[] _DataValues;
internal UserReportParameter(Report rpt, ReportParameter rp)
{
_rpt = rpt;
_rp = rp;
}
/// <summary>
/// Name of the report paramenter.
/// </summary>
public string Name
{
get { return _rp.Name.Nm; }
}
/// <summary>
/// Type of the report parameter.
/// </summary>
public TypeCode dt
{
get { return _rp.dt; }
}
/// <summary>
/// Is parameter allowed to be null.
/// </summary>
public bool Nullable
{
get { return _rp.Nullable; }
}
/// <summary>
/// Default value(s) of the parameter.
/// </summary>
public object[] DefaultValue
{
get
{
if (_DefaultValue == null)
{
if (_rp.DefaultValue != null)
_DefaultValue = _rp.DefaultValue.ValuesCalc(this._rpt);
}
return _DefaultValue;
}
}
/// <summary>
/// Is parameter allowed to be the empty string?
/// </summary>
public bool AllowBlank
{
get { return _rp.AllowBlank; }
}
/// <summary>
/// Does parameters accept multiple values?
/// </summary>
public bool MultiValue
{
get { return _rp.MultiValue; }
}
/// <summary>
/// Text used to prompt for the parameter.
/// </summary>
public string Prompt
{
get { return _rp.Prompt; }
}
/// <summary>
/// The display values for the parameter. These may differ from the data values.
/// </summary>
public string[] DisplayValues
{
get
{
if (_DisplayValues == null)
{
if (_rp.ValidValues != null)
_DisplayValues = _rp.ValidValues.DisplayValues(_rpt);
}
return _DisplayValues;
}
}
/// <summary>
/// The data values of the parameter.
/// </summary>
public object[] DataValues
{
get
{
if (_DataValues == null)
{
if (_rp.ValidValues != null)
_DataValues = _rp.ValidValues.DataValues(this._rpt);
}
return _DataValues;
}
}
/// <summary>
/// Obtain the data value from a (potentially) display value
/// </summary>
/// <param name="dvalue">Display value</param>
/// <returns>The data value cooresponding to the display value.</returns>
private object GetDataValueFromDisplay(object dvalue)
{
object val = dvalue;
if (dvalue != null &&
DisplayValues != null &&
DataValues != null &&
DisplayValues.Length == DataValues.Length) // this should always be true
{ // if display values are provided then we may need to
// use the provided value with a display value and use
// the cooresponding data value
string sval = dvalue.ToString();
for (int index = 0; index < DisplayValues.Length; index++)
{
if (DisplayValues[index].CompareTo(sval) == 0)
{
val = DataValues[index];
break;
}
}
}
return val;
}
/// <summary>
/// The runtime value of the parameter.
/// </summary>
public object Value
{
get { return _rp.GetRuntimeValue(this._rpt); }
set
{
if (this.MultiValue && value is string)
{ // treat this as a multiValue request
Values = ParseValue(value as string);
return;
}
object dvalue = GetDataValueFromDisplay(value);
_rp.SetRuntimeValue(_rpt, dvalue);
}
}
/// <summary>
/// Take a string and parse it into multiple values
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
private ArrayList ParseValue(string v)
{
ParameterLexer pl = new ParameterLexer(v);
return pl.Lex();
}
/// <summary>
/// The runtime values of the parameter when MultiValue.
/// </summary>
public ArrayList Values
{
get { return _rp.GetRuntimeValues(this._rpt); }
set
{
ArrayList ar = new ArrayList(value.Count);
foreach (object v in value)
{
ar.Add(GetDataValueFromDisplay(v));
}
_rp.SetRuntimeValues(_rpt, ar);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using ReMi.Plugin.Common;
using ReMi.Plugin.ZenDesk.DataAccess.Gateways;
using ReMi.Plugin.ZenDesk.Models;
using RestSharp.Extensions;
namespace ReMi.Plugin.ZenDesk.BusinessLogic
{
/// <summary>
/// More info: http://developer.zendesk.com/documentation/rest_api/introduction.html
/// </summary>
public class ZenDeskRequest : RestApiRequest, IZenDeskRequest
{
public Func<IGlobalConfigurationGateway> GlobalConfigurationGatewayFactory { get; set; }
public override string BaseUrl
{
get { return Configuration.ZenDeskUrl; }
}
protected override string UserName { get { return Configuration.ZenDeskUser; } set { } }
protected override string Password { get { return Configuration.ZenDeskPassword; } set { } }
private PluginConfigurationEntity Configuration
{
get
{
using (var gateway = GlobalConfigurationGatewayFactory())
{
return gateway.GetGlobalConfiguration();
}
}
}
public User Me()
{
return GetData<UserWrapper>("users/me.json").User;
}
public List<Ticket> Tickets()
{
var response = GetData<TicketsWrapper>("tickets.json");
return response.Tickets;
}
/// <summary>
/// More info: http://developer.zendesk.com/documentation/rest_api/search.html , https://support.zendesk.com/entries/20239737
/// </summary>
/// <param name="seacrhCondition"></param>
/// <returns></returns>
private List<Ticket> SearchTickets(string seacrhCondition)
{
var response = GetData<SearchResultsWrapper>("search.json", new Dictionary<string, string> { { "query", seacrhCondition } });
return response.Results;
}
public List<Ticket> NotSolvedTickets()
{
return SearchTickets("status<solved ticket_type:ticket");
}
public Ticket Ticket(int ticketId)
{
if (ticketId <= 0)
throw new ArgumentException("Invaid ticket number");
var response = GetData<TicketWrapper>(string.Format("tickets/{0}.json", ticketId));
return response != null ? response.Ticket : null;
}
public Ticket CreateTicket(Ticket ticket)
{
var response = Post<TicketWrapper>("tickets.json", new TicketWrapper { Ticket = ticket });
if (response.StatusCode != HttpStatusCode.Created || response.Data == null ||
response.Data.Ticket == null) return null;
return response.Data.Ticket;
}
public Ticket UpdateTicket(Ticket ticket)
{
var response = Put<TicketWrapper>(string.Format("tickets/{0}.json", ticket.Id),
new TicketWrapper { Ticket = ticket });
if (response.StatusCode != HttpStatusCode.OK || response.Data == null || response.Data.Ticket == null)
return null;
return response.Data.Ticket;
}
public void DeleteTicket(string ticketRef)
{
var response = Delete<TicketWrapper>(string.Format("tickets/{0}.json", ticketRef));
switch (response.StatusCode)
{
case HttpStatusCode.OK:
return;
case HttpStatusCode.Forbidden:
throw new ZenDeskAccessDeniedException("DeleteTicket");
default:
throw new ZenDeskTicketNotFoundException(ticketRef);
}
}
public void MarkTicketAsResolved(string ticketRef)
{
int ticketId;
if (!int.TryParse(ticketRef, out ticketId))
throw new ArgumentException("TicketRef is not a number", "ticketRef");
var ticket = new Ticket
{
Id = ticketId,
Status = Statuses.solved,
Comment = new TicketComment { Body = "TicketResolved", Public = true },
Assignee_Id = 683585607
};
var updatedTicket = UpdateTicket(ticket);
if (updatedTicket == null)
{
throw new ZenDeskTicketNotFoundException(ticketRef);
}
if (updatedTicket.Status != Statuses.solved)
{
throw new ZenDeskFailedToUpdateTicketStatusException(ticketId);
}
}
public Attachment AddAttachment(int ticketId, string fileName, byte[] data, string comment = null)
{
var text = comment ?? string.Format("Attachment: {0}", fileName);
var uploadResponse = UploadFile<UploadWrapper>(
string.Format("uploads.json?filename={0}", fileName), null,
new Dictionary<string, byte[]> { { fileName, data } });
if (uploadResponse.StatusCode != HttpStatusCode.Created || uploadResponse.Data == null ||
uploadResponse.Data.Upload == null || string.IsNullOrEmpty(uploadResponse.Data.Upload.Token) ||
!uploadResponse.Data.Upload.Attachments.Any())
{
return null;
}
var uploadToken = uploadResponse.Data.Upload.Token;
var ticket = new Ticket
{
Id = ticketId,
Comment = new TicketComment
{
Body = text,
Uploads = new[] { uploadToken }
}
};
return UpdateTicket(ticket) != null ? uploadResponse.Data.Upload.Attachments.First() : null;
}
public byte[] GetAttachment(int attachmentId)
{
if (attachmentId <= 0)
throw new ArgumentException("Invaid attachment id");
var response = GetData<AttachmentWrapper>(string.Format("attachments/{0}.json", attachmentId));
if (response == null || response.Attachment == null
|| string.IsNullOrEmpty(response.Attachment.Content_Url))
return null;
var attachmentUrl = response.Attachment.Content_Url;
var request = WebRequest.Create(attachmentUrl);
request.Credentials = new NetworkCredential(UserName, Password);
using (var webResponse = (HttpWebResponse)request.GetResponse())
{
return webResponse.StatusCode == HttpStatusCode.OK ? webResponse.GetResponseStream().ReadAsBytes() : null;
}
}
public List<Group> Groups()
{
var response = GetData<GroupsWrapper>("groups.json");
return response != null ? response.Groups : null;
}
public User User(int id)
{
return Users(id).FirstOrDefault();
}
public List<User> Users(params int[] userIds)
{
if (userIds == null || userIds.Length == 0)
throw new ArgumentException("Invalid list of user ids");
var ids = string.Join(",", userIds.Select(o => o.ToString(CultureInfo.InvariantCulture)));
var response = GetData<UsersWrapper>("users/show_many.json?ids=" + ids);
return response.Users;
}
public List<User> Users()
{
var response = GetData<UsersWrapper>("users.json");
return response.Users;
}
public List<User> UsersInGroup(int groupId)
{
var response = GetData<UsersWrapper>(string.Format("groups/{0}/users.json", groupId));
return response.Users;
}
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Capabilities;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
using OpenSim.Capabilities.Handlers;
namespace OpenSim.Region.ClientStack.Linden
{
/// <summary>
/// This module implements both WebFetchInventoryDescendents and FetchInventoryDescendents2 capabilities.
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WebFetchInvDescModule")]
public class WebFetchInvDescModule : INonSharedRegionModule
{
class aPollRequest
{
public PollServiceInventoryEventArgs thepoll;
public UUID reqID;
public Hashtable request;
public ScenePresence presence;
public List<UUID> folders;
}
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Control whether requests will be processed asynchronously.
/// </summary>
/// <remarks>
/// Defaults to true. Can currently not be changed once a region has been added to the module.
/// </remarks>
public bool ProcessQueuedRequestsAsync { get; private set; }
/// <summary>
/// Number of inventory requests processed by this module.
/// </summary>
/// <remarks>
/// It's the PollServiceRequestManager that actually sends completed requests back to the requester.
/// </remarks>
public static int ProcessedRequestsCount { get; set; }
private static Stat s_queuedRequestsStat;
private static Stat s_processedRequestsStat;
public Scene Scene { get; private set; }
private IInventoryService m_InventoryService;
private ILibraryService m_LibraryService;
private bool m_Enabled;
private string m_fetchInventoryDescendents2Url;
private string m_webFetchInventoryDescendentsUrl;
private static FetchInvDescHandler m_webFetchHandler;
private static Thread[] m_workerThreads = null;
private static DoubleQueue<aPollRequest> m_queue =
new DoubleQueue<aPollRequest>();
#region ISharedRegionModule Members
public WebFetchInvDescModule() : this(true) {}
public WebFetchInvDescModule(bool processQueuedResultsAsync)
{
ProcessQueuedRequestsAsync = processQueuedResultsAsync;
}
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["ClientStack.LindenCaps"];
if (config == null)
return;
m_fetchInventoryDescendents2Url = config.GetString("Cap_FetchInventoryDescendents2", string.Empty);
m_webFetchInventoryDescendentsUrl = config.GetString("Cap_WebFetchInventoryDescendents", string.Empty);
if (m_fetchInventoryDescendents2Url != string.Empty || m_webFetchInventoryDescendentsUrl != string.Empty)
{
m_Enabled = true;
}
}
public void AddRegion(Scene s)
{
if (!m_Enabled)
return;
Scene = s;
}
public void RemoveRegion(Scene s)
{
if (!m_Enabled)
return;
Scene.EventManager.OnRegisterCaps -= RegisterCaps;
StatsManager.DeregisterStat(s_processedRequestsStat);
StatsManager.DeregisterStat(s_queuedRequestsStat);
if (ProcessQueuedRequestsAsync)
{
if (m_workerThreads != null)
{
foreach (Thread t in m_workerThreads)
Watchdog.AbortThread(t.ManagedThreadId);
m_workerThreads = null;
}
}
Scene = null;
}
public void RegionLoaded(Scene s)
{
if (!m_Enabled)
return;
if (s_processedRequestsStat == null)
s_processedRequestsStat =
new Stat(
"ProcessedFetchInventoryRequests",
"Number of processed fetch inventory requests",
"These have not necessarily yet been dispatched back to the requester.",
"",
"inventory",
"httpfetch",
StatType.Pull,
MeasuresOfInterest.AverageChangeOverTime,
stat => { stat.Value = ProcessedRequestsCount; },
StatVerbosity.Debug);
if (s_queuedRequestsStat == null)
s_queuedRequestsStat =
new Stat(
"QueuedFetchInventoryRequests",
"Number of fetch inventory requests queued for processing",
"",
"",
"inventory",
"httpfetch",
StatType.Pull,
MeasuresOfInterest.AverageChangeOverTime,
stat => { stat.Value = m_queue.Count; },
StatVerbosity.Debug);
StatsManager.RegisterStat(s_processedRequestsStat);
StatsManager.RegisterStat(s_queuedRequestsStat);
m_InventoryService = Scene.InventoryService;
m_LibraryService = Scene.LibraryService;
// We'll reuse the same handler for all requests.
m_webFetchHandler = new FetchInvDescHandler(m_InventoryService, m_LibraryService);
Scene.EventManager.OnRegisterCaps += RegisterCaps;
if (ProcessQueuedRequestsAsync && m_workerThreads == null)
{
m_workerThreads = new Thread[2];
for (uint i = 0; i < 2; i++)
{
m_workerThreads[i] = WorkManager.StartThread(DoInventoryRequests,
String.Format("InventoryWorkerThread{0}", i),
ThreadPriority.Normal,
false,
true,
null,
int.MaxValue);
}
}
}
public void PostInitialise()
{
}
public void Close() { }
public string Name { get { return "WebFetchInvDescModule"; } }
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
private class PollServiceInventoryEventArgs : PollServiceEventArgs
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<UUID, Hashtable> responses =
new Dictionary<UUID, Hashtable>();
private WebFetchInvDescModule m_module;
public PollServiceInventoryEventArgs(WebFetchInvDescModule module, string url, UUID pId) :
base(null, url, null, null, null, pId, int.MaxValue)
{
m_module = module;
HasEvents = (x, y) => { lock (responses) return responses.ContainsKey(x); };
GetEvents = (x, y) =>
{
lock (responses)
{
try
{
return responses[x];
}
finally
{
responses.Remove(x);
}
}
};
Request = (x, y) =>
{
ScenePresence sp = m_module.Scene.GetScenePresence(Id);
if (sp == null)
{
m_log.ErrorFormat("[INVENTORY]: Unable to find ScenePresence for {0}", Id);
return;
}
aPollRequest reqinfo = new aPollRequest();
reqinfo.thepoll = this;
reqinfo.reqID = x;
reqinfo.request = y;
reqinfo.presence = sp;
reqinfo.folders = new List<UUID>();
// Decode the request here
string request = y["body"].ToString();
request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>");
request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>");
request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>");
Hashtable hash = new Hashtable();
try
{
hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
}
catch (LLSD.LLSDParseException e)
{
m_log.ErrorFormat("[INVENTORY]: Fetch error: {0}{1}" + e.Message, e.StackTrace);
m_log.Error("Request: " + request);
return;
}
catch (System.Xml.XmlException)
{
m_log.ErrorFormat("[INVENTORY]: XML Format error");
}
ArrayList foldersrequested = (ArrayList)hash["folders"];
bool highPriority = false;
for (int i = 0; i < foldersrequested.Count; i++)
{
Hashtable inventoryhash = (Hashtable)foldersrequested[i];
string folder = inventoryhash["folder_id"].ToString();
UUID folderID;
if (UUID.TryParse(folder, out folderID))
{
if (!reqinfo.folders.Contains(folderID))
{
//TODO: Port COF handling from Avination
reqinfo.folders.Add(folderID);
}
}
}
if (highPriority)
m_queue.EnqueueHigh(reqinfo);
else
m_queue.EnqueueLow(reqinfo);
};
NoEvents = (x, y) =>
{
/*
lock (requests)
{
Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString());
requests.Remove(request);
}
*/
Hashtable response = new Hashtable();
response["int_response_code"] = 500;
response["str_response_string"] = "Script timeout";
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
return response;
};
}
public void Process(aPollRequest requestinfo)
{
UUID requestID = requestinfo.reqID;
Hashtable response = new Hashtable();
response["int_response_code"] = 200;
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
response["str_response_string"] = m_webFetchHandler.FetchInventoryDescendentsRequest(
requestinfo.request["body"].ToString(), String.Empty, String.Empty, null, null);
lock (responses)
responses[requestID] = response;
WebFetchInvDescModule.ProcessedRequestsCount++;
}
}
private void RegisterCaps(UUID agentID, Caps caps)
{
RegisterFetchDescendentsCap(agentID, caps, "FetchInventoryDescendents2", m_fetchInventoryDescendents2Url);
}
private void RegisterFetchDescendentsCap(UUID agentID, Caps caps, string capName, string url)
{
string capUrl;
// disable the cap clause
if (url == "")
{
return;
}
// handled by the simulator
else if (url == "localhost")
{
capUrl = "/CAPS/" + UUID.Random() + "/";
// Register this as a poll service
PollServiceInventoryEventArgs args = new PollServiceInventoryEventArgs(this, capUrl, agentID);
args.Type = PollServiceEventArgs.EventType.Inventory;
caps.RegisterPollHandler(capName, args);
}
// external handler
else
{
capUrl = url;
IExternalCapsModule handler = Scene.RequestModuleInterface<IExternalCapsModule>();
if (handler != null)
handler.RegisterExternalUserCapsHandler(agentID,caps,capName,capUrl);
else
caps.RegisterHandler(capName, capUrl);
}
// m_log.DebugFormat(
// "[FETCH INVENTORY DESCENDENTS2 MODULE]: Registered capability {0} at {1} in region {2} for {3}",
// capName, capUrl, m_scene.RegionInfo.RegionName, agentID);
}
// private void DeregisterCaps(UUID agentID, Caps caps)
// {
// string capUrl;
//
// if (m_capsDict.TryGetValue(agentID, out capUrl))
// {
// MainServer.Instance.RemoveHTTPHandler("", capUrl);
// m_capsDict.Remove(agentID);
// }
// }
private void DoInventoryRequests()
{
while (true)
{
Watchdog.UpdateThread();
WaitProcessQueuedInventoryRequest();
}
}
public void WaitProcessQueuedInventoryRequest()
{
aPollRequest poolreq = m_queue.Dequeue();
if (poolreq != null && poolreq.thepoll != null)
{
try
{
poolreq.thepoll.Process(poolreq);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[INVENTORY]: Failed to process queued inventory request {0} for {1} in {2}. Exception {3}",
poolreq.reqID, poolreq.presence != null ? poolreq.presence.Name : "unknown", Scene.Name, e);
}
}
}
}
}
| |
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 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.Collections;
using SSCX = System.Security.Cryptography.X509Certificates;
using Mono.Security.X509;
using Mono.Security.X509.Extensions;
namespace Mono.Security.Protocol.Tls.Handshake.Server
{
internal class TlsClientCertificate : HandshakeMessage
{
#region Fields
private X509CertificateCollection clientCertificates;
#endregion
#region Constructors
public TlsClientCertificate(Context context, byte[] buffer)
: base(context, HandshakeType.Certificate, buffer)
{
}
#endregion
#region Methods
public override void Update()
{
foreach (X509Certificate certificate in clientCertificates) {
this.Context.ClientSettings.Certificates.Add (new SSCX.X509Certificate (certificate.RawData));
}
}
public bool HasCertificate {
get { return clientCertificates.Count > 0; }
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
this.ProcessAsTls1();
}
protected override void ProcessAsTls1()
{
int bytesRead = 0;
int length = this.ReadInt24 ();
this.clientCertificates = new X509CertificateCollection ();
while (length > bytesRead) {
int certLength = this.ReadInt24 ();
bytesRead += certLength + 3;
byte[] cert = this.ReadBytes (certLength);
this.clientCertificates.Add (new X509Certificate (cert));
}
if (this.clientCertificates.Count > 0)
{
this.validateCertificates (this.clientCertificates);
}
else if ((this.Context as ServerContext).ClientCertificateRequired)
{
throw new TlsException (AlertDescription.NoCertificate);
}
}
#endregion
#region Private Methods
private bool checkCertificateUsage (X509Certificate cert)
{
ServerContext context = (ServerContext)this.Context;
// certificate extensions are required for this
// we "must" accept older certificates without proofs
if (cert.Version < 3)
return true;
KeyUsages ku = KeyUsages.none;
switch (context.Negotiating.Cipher.ExchangeAlgorithmType)
{
case ExchangeAlgorithmType.RsaSign:
case ExchangeAlgorithmType.RsaKeyX:
ku = KeyUsages.digitalSignature;
break;
case ExchangeAlgorithmType.DiffieHellman:
ku = KeyUsages.keyAgreement;
break;
case ExchangeAlgorithmType.Fortezza:
return false; // unsupported certificate type
}
KeyUsageExtension kux = null;
ExtendedKeyUsageExtension eku = null;
X509Extension xtn = cert.Extensions["2.5.29.15"];
if (xtn != null)
kux = new KeyUsageExtension (xtn);
xtn = cert.Extensions["2.5.29.37"];
if (xtn != null)
eku = new ExtendedKeyUsageExtension (xtn);
if ((kux != null) && (eku != null))
{
// RFC3280 states that when both KeyUsageExtension and
// ExtendedKeyUsageExtension are present then BOTH should
// be valid
return (kux.Support (ku) &&
eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.2"));
}
else if (kux != null)
{
return kux.Support (ku);
}
else if (eku != null)
{
// Client Authentication (1.3.6.1.5.5.7.3.2)
return eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.2");
}
// last chance - try with older (deprecated) Netscape extensions
xtn = cert.Extensions["2.16.840.1.113730.1.1"];
if (xtn != null)
{
NetscapeCertTypeExtension ct = new NetscapeCertTypeExtension (xtn);
return ct.Support (NetscapeCertTypeExtension.CertTypes.SslClient);
}
// certificate isn't valid for SSL server usage
return false;
}
private void validateCertificates (X509CertificateCollection certificates)
{
ServerContext context = (ServerContext)this.Context;
AlertDescription description = AlertDescription.BadCertificate;
SSCX.X509Certificate client = null;
int[] certificateErrors = null;
// note: certificate may be null is no certificate is sent
// (e.g. optional mutual authentication)
if (certificates.Count > 0) {
X509Certificate leaf = certificates[0];
ArrayList errors = new ArrayList ();
// SSL specific check - not all certificates can be
// used to server-side SSL some rules applies after
// all ;-)
if (!checkCertificateUsage (leaf))
{
// WinError.h CERT_E_PURPOSE 0x800B0106
errors.Add ((int)-2146762490);
}
X509Chain verify;
// was a chain supplied ? if so use it, if not
if (certificates.Count > 1) {
// if so use it (and don't build our own)
X509CertificateCollection chain = new X509CertificateCollection (certificates);
chain.Remove (leaf);
verify = new X509Chain (chain);
} else {
// if not, then let's build our own (based on what's available in the stores)
verify = new X509Chain ();
}
bool result = false;
try
{
result = verify.Build (leaf);
}
catch (Exception)
{
result = false;
}
if (!result)
{
switch (verify.Status)
{
case X509ChainStatusFlags.InvalidBasicConstraints:
// WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019
errors.Add ((int)-2146869223);
break;
case X509ChainStatusFlags.NotSignatureValid:
// WinError.h TRUST_E_BAD_DIGEST 0x80096010
errors.Add ((int)-2146869232);
break;
case X509ChainStatusFlags.NotTimeNested:
// WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102
errors.Add ((int)-2146762494);
break;
case X509ChainStatusFlags.NotTimeValid:
// WinError.h CERT_E_EXPIRED 0x800B0101
description = AlertDescription.CertificateExpired;
errors.Add ((int)-2146762495);
break;
case X509ChainStatusFlags.PartialChain:
// WinError.h CERT_E_CHAINING 0x800B010A
description = AlertDescription.UnknownCA;
errors.Add ((int)-2146762486);
break;
case X509ChainStatusFlags.UntrustedRoot:
// WinError.h CERT_E_UNTRUSTEDROOT 0x800B0109
description = AlertDescription.UnknownCA;
errors.Add ((int)-2146762487);
break;
default:
// unknown error
description = AlertDescription.CertificateUnknown;
errors.Add ((int)verify.Status);
break;
}
}
client = new SSCX.X509Certificate (leaf.RawData);
certificateErrors = (int[])errors.ToArray (typeof (int));
}
else
{
certificateErrors = new int[0];
}
SSCX.X509CertificateCollection certCollection = new SSCX.X509CertificateCollection ();
foreach (X509Certificate certificate in certificates) {
certCollection.Add (new SSCX.X509Certificate (certificate.RawData));
}
if (!context.SslStream.RaiseClientCertificateValidation(client, certificateErrors))
{
throw new TlsException (
description,
"Invalid certificate received from client.");
}
this.Context.ClientSettings.ClientCertificate = client;
}
#endregion
}
}
| |
#region Copyright (c) all rights reserved.
// <copyright file="CsvDataSource.cs">
// THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// </copyright>
#endregion
namespace Ditto.DataLoad
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using Ditto.DomainEvents;
using Ditto.Core;
using Ditto.DataLoad.DomainEvents;
using Csv = CsvHelper.Configuration;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// FolderMode enumeration.
/// </summary>
public enum FolderMode
{
/// <summary>
/// Loads multiple files in a single batch.
/// </summary>
MultipleFile = 0,
/// <summary>
/// Loads a single file per batch.
/// </summary>
SingleFile,
/// <summary>
/// Loads only the last file (assumes that each file is a full extract).
/// </summary>
LastFileOnly,
}
/// <summary>
/// Csv Data Source.
/// </summary>
[CLSCompliant(false)]
public class CsvDataSource : IDataSource
{
/// <summary>
/// The source name.
/// </summary>
private readonly string name;
/// <summary>
/// The connection.
/// </summary>
private readonly DataConnection connection;
/// <summary>
/// The file pattern.
/// </summary>
private readonly string filePattern;
/// <summary>
/// The file system.
/// </summary>
private readonly IFileSystemService fileSystem;
/// <summary>
/// Folder handling mode.
/// </summary>
private readonly FolderMode mode;
/// <summary>
/// The CSV configuration.
/// </summary>
private readonly Csv.Configuration config;
/// <summary>
/// Initializes a new instance of the <see cref="CsvDataSource" /> class.
/// </summary>
/// <param name="name">The name of the data source.</param>
/// <param name="connection">The connection.</param>
/// <param name="filePattern">The file pattern.</param>
/// <param name="mode">The file mode.</param>
/// <param name="config">The CSV configuration.</param>
public CsvDataSource(string name, DataConnection connection, string filePattern, FolderMode mode, Csv.Configuration config)
: this(name, connection, filePattern, mode, config, new FileSystemService())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CsvDataSource" /> class.
/// </summary>
/// <param name="name">The source name.</param>
/// <param name="connection">The connection.</param>
/// <param name="filePattern">The file pattern.</param>
/// <param name="mode">The file mode.</param>
/// <param name="config">The CSV configuration.</param>
/// <param name="fileSystem">The file system.</param>
/// <exception cref="System.ArgumentNullException">If any arguments are null.</exception>
public CsvDataSource(string name, DataConnection connection, string filePattern, FolderMode mode, Csv.Configuration config, IFileSystemService fileSystem)
{
this.name = name ?? throw new ArgumentNullException("name");
this.connection = connection ?? throw new ArgumentNullException("connection");
this.filePattern = filePattern ?? throw new ArgumentNullException("filePattern");
this.config = config ?? throw new ArgumentNullException("config");
this.fileSystem = fileSystem ?? throw new ArgumentNullException("fileSystem");
this.mode = mode;
}
/// <summary>
/// Gets the name of the source.
/// </summary>
/// <value>
/// The name of the data source.
/// </value>
public string Name
{
get { return this.name; }
}
/// <summary>
/// Gets the name of the connection.
/// </summary>
/// <value>
/// The name of the connection.
/// </value>
public string ConnectionName
{
get { return this.connection.Name; }
}
/// <summary>
/// Gets or sets the parent.
/// </summary>
/// <value>
/// The parent.
/// </value>
public IDataOperationInfo Parent { get; set; }
/// <summary>
/// Gets the columns.
/// </summary>
/// <param name="previousHighWatermark">The previous high watermark.</param>
/// <returns>
/// A sequence of columns.
/// </returns>
public IEnumerable<string> GetColumns(Watermark previousHighWatermark)
{
// The CSV source is a little complex because we derive the column list from real
// source data. If there are files we need to use the actual one that is going to be
// imported. If not then any file will do - even ones below the watermark.
using (var latestData = this.GetData(Enumerable.Empty<string>(), previousHighWatermark))
using (var sampleData = this.GetData(Enumerable.Empty<string>(), null))
{
var columnData = latestData ?? sampleData;
if (columnData == null)
{
yield break;
}
for (int i = 0; i < columnData.FieldCount; ++i)
{
yield return columnData.GetName(i);
}
}
}
/// <summary>
/// Returns a <see cref="System.Data.DataTable" /> that describes the column metadata of the <see cref="System.Data.IDataReader" />.
/// </summary>
/// <returns>
/// A <see cref="System.Data.DataTable" /> that describes the column metadata.
/// </returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "JS: This follows the correct transfer of ownership pattern")]
public DataTable GetSchemaTable()
{
DataTable tempTable = null;
DataTable schemaTable = null;
try
{
tempTable = new DataTable
{
Locale = CultureInfo.CurrentCulture
};
var columns = new DataColumn[]
{
new DataColumn("ColumnOrdinal", typeof(int)),
new DataColumn("ColumnName", typeof(string)),
new DataColumn("ColumnSize", typeof(int)),
new DataColumn("DataType", typeof(Type)),
new DataColumn("AllowDBNull", typeof(bool)),
};
tempTable.Columns.AddRange(columns);
var columnNames = this.GetColumns(null).ToArray();
// If the file has no columns (or there are no files) then don't add any more
// metadata columns.
if (columnNames.Count() != 0)
{
// Fixed columns get real metadata (until I've implemented the schema functionality)
tempTable.Rows.Add(0, "_LineNumber", 0, typeof(int), false);
tempTable.Rows.Add(0, "_SourceFile", 260, typeof(string), false);
// In particular this one or the high watermarking won't work.
tempTable.Rows.Add(0, "_LastWriteTimeUtc", 0, typeof(DateTime), false);
for (int i = tempTable.Rows.Count; i < columnNames.Length; ++i)
{
tempTable.Rows.Add(i, columnNames[i], 255, typeof(string), true);
}
}
schemaTable = tempTable;
tempTable = null;
}
finally
{
if (tempTable != null)
{
tempTable.Dispose();
}
}
return schemaTable;
}
/// <summary>
/// Determines whether the specified previous high watermark has data.
/// </summary>
/// <param name="previousHighWatermark">The previous high watermark.</param>
/// <returns>
/// True if there is data.
/// </returns>
/// <remarks>
/// This allows a shortcut for sources that may not exist e.g. files.
/// </remarks>
public bool HasData(Watermark previousHighWatermark)
{
return this.FindFiles(previousHighWatermark).Any();
}
/// <summary>
/// Gets the data.
/// </summary>
/// <param name="columns">The columns.</param>
/// <param name="previousHighWatermark">The previous high watermark.</param>
/// <returns>
/// A streaming reader for the data.
/// </returns>
public IDataReader GetData(IEnumerable<string> columns, Watermark previousHighWatermark)
{
try
{
IEnumerable<IFileInfo> files = this.FindFiles(previousHighWatermark);
if (files.Count() == 0)
{
return null;
}
EventPublisher.Raise(
new SourceFileFoundEvent
{
OperationId = this.Parent.OperationId,
SourceName = this.name,
ConnectionName = this.ConnectionName,
FoundFiles = files
});
return this.fileSystem.CreateDataReader(files, this.config);
}
catch (IOException ex)
{
if (ex.IsFileLocked())
{
EventPublisher.Raise(
new SourceFileLockedEvent
{
OperationId = this.Parent.OperationId,
SourceName = this.Name,
ConnectionName = this.ConnectionName,
Exception = ex
});
// Back off and wait till next time.
return null;
}
EventPublisher.Raise(
new SourceErrorEvent
{
OperationId = this.Parent.OperationId,
SourceName = this.Name,
ConnectionName = this.ConnectionName,
Exception = ex
});
throw;
}
}
/// <summary>
/// Finds the files.
/// </summary>
/// <param name="previousHighWatermark">The previous high watermark.</param>
/// <returns>A sequence of files to import.</returns>
private IEnumerable<IFileInfo> FindFiles(Watermark previousHighWatermark)
{
var allFiles = this.fileSystem.EnumerateFiles(this.connection.ConnectionString, this.filePattern)
.Where(f => previousHighWatermark == null || f.LastWriteTimeUtc > previousHighWatermark.WatermarkValue);
IEnumerable<IFileInfo> importFiles = null;
switch (this.mode)
{
case FolderMode.MultipleFile:
importFiles = allFiles.OrderBy(f => f.LastWriteTimeUtc);
break;
case FolderMode.SingleFile:
importFiles = allFiles.OrderBy(f => f.LastWriteTimeUtc).Take(1);
break;
case FolderMode.LastFileOnly:
importFiles = allFiles.OrderByDescending(f => f.LastWriteTimeUtc).Take(1);
break;
}
return importFiles;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using Orleans.Messaging;
namespace Orleans.Runtime.Messaging
{
internal class IncomingMessageAcceptor : AsynchAgent
{
private readonly IPEndPoint listenAddress;
private Action<Message> sniffIncomingMessageHandler;
internal Socket AcceptingSocket;
protected MessageCenter MessageCenter;
protected HashSet<Socket> OpenReceiveSockets;
public Action<Message> SniffIncomingMessage
{
set
{
if (sniffIncomingMessageHandler != null)
throw new InvalidOperationException("IncomingMessageAcceptor SniffIncomingMessage already set");
sniffIncomingMessageHandler = value;
}
}
private const int LISTEN_BACKLOG_SIZE = 1024;
protected SocketDirection SocketDirection { get; private set; }
// Used for holding enough info to handle receive completion
internal IncomingMessageAcceptor(MessageCenter msgCtr, IPEndPoint here, SocketDirection socketDirection)
{
MessageCenter = msgCtr;
listenAddress = here;
if (here == null)
listenAddress = MessageCenter.MyAddress.Endpoint;
AcceptingSocket = SocketManager.GetAcceptingSocketForEndpoint(listenAddress);
Log.Info(ErrorCode.Messaging_IMA_OpenedListeningSocket, "Opened a listening socket at address " + AcceptingSocket.LocalEndPoint);
OpenReceiveSockets = new HashSet<Socket>();
OnFault = FaultBehavior.CrashOnFault;
SocketDirection = socketDirection;
}
protected override void Run()
{
try
{
AcceptingSocket.Listen(LISTEN_BACKLOG_SIZE);
#if !NETSTANDARD_TODO
AcceptingSocket.BeginAccept(AcceptCallback, this);
#endif
}
catch (Exception ex)
{
Log.Error(ErrorCode.MessagingBeginAcceptSocketException, "Exception beginning accept on listening socket", ex);
throw;
}
if (Log.IsVerbose3) Log.Verbose3("Started accepting connections.");
}
public override void Stop()
{
base.Stop();
if (Log.IsVerbose) Log.Verbose("Disconnecting the listening socket");
SocketManager.CloseSocket(AcceptingSocket);
Socket[] temp;
lock (Lockable)
{
temp = new Socket[OpenReceiveSockets.Count];
OpenReceiveSockets.CopyTo(temp);
}
foreach (var socket in temp)
{
SafeCloseSocket(socket);
}
lock (Lockable)
{
ClearSockets();
}
}
protected virtual bool RecordOpenedSocket(Socket sock)
{
GrainId client;
if (!ReceiveSocketPreample(sock, false, out client)) return false;
NetworkingStatisticsGroup.OnOpenedReceiveSocket();
return true;
}
protected bool ReceiveSocketPreample(Socket sock, bool expectProxiedConnection, out GrainId client)
{
client = null;
if (Cts.IsCancellationRequested) return false;
if (!ReadConnectionPreamble(sock, out client))
{
return false;
}
if (Log.IsVerbose2) Log.Verbose2(ErrorCode.MessageAcceptor_Connection, "Received connection from {0} at source address {1}", client, sock.RemoteEndPoint.ToString());
if (expectProxiedConnection)
{
// Proxied Gateway Connection - must have sender id
if (client.Equals(Constants.SiloDirectConnectionId))
{
Log.Error(ErrorCode.MessageAcceptor_NotAProxiedConnection, string.Format("Gateway received unexpected non-proxied connection from {0} at source address {1}", client, sock.RemoteEndPoint));
return false;
}
}
else
{
// Direct connection - should not have sender id
if (!client.Equals(Constants.SiloDirectConnectionId))
{
Log.Error(ErrorCode.MessageAcceptor_UnexpectedProxiedConnection, string.Format("Silo received unexpected proxied connection from {0} at source address {1}", client, sock.RemoteEndPoint));
return false;
}
}
lock (Lockable)
{
OpenReceiveSockets.Add(sock);
}
return true;
}
private bool ReadConnectionPreamble(Socket socket, out GrainId grainId)
{
grainId = null;
byte[] buffer = null;
try
{
buffer = ReadFromSocket(socket, sizeof(int)); // Read the size
if (buffer == null) return false;
Int32 size = BitConverter.ToInt32(buffer, 0);
if (size > 0)
{
buffer = ReadFromSocket(socket, size); // Receive the client ID
if (buffer == null) return false;
grainId = GrainId.FromByteArray(buffer);
}
return true;
}
catch (Exception exc)
{
Log.Error(ErrorCode.GatewayFailedToParse,
String.Format("Failed to convert the data that read from the socket. buffer = {0}, from endpoint {1}.",
Utils.EnumerableToString(buffer), socket.RemoteEndPoint), exc);
return false;
}
}
private byte[] ReadFromSocket(Socket sock, int expected)
{
var buffer = new byte[expected];
int offset = 0;
while (offset < buffer.Length)
{
try
{
int bytesRead = sock.Receive(buffer, offset, buffer.Length - offset, SocketFlags.None);
if (bytesRead == 0)
{
Log.Warn(ErrorCode.GatewayAcceptor_SocketClosed,
"Remote socket closed while receiving connection preamble data from endpoint {0}.", sock.RemoteEndPoint);
return null;
}
offset += bytesRead;
}
catch (Exception ex)
{
Log.Warn(ErrorCode.GatewayAcceptor_ExceptionReceiving,
"Exception receiving connection preamble data from endpoint " + sock.RemoteEndPoint, ex);
return null;
}
}
return buffer;
}
protected virtual void RecordClosedSocket(Socket sock)
{
if (TryRemoveClosedSocket(sock))
NetworkingStatisticsGroup.OnClosedReceivingSocket();
}
protected bool TryRemoveClosedSocket(Socket sock)
{
lock (Lockable)
{
return OpenReceiveSockets.Remove(sock);
}
}
protected virtual void ClearSockets()
{
OpenReceiveSockets.Clear();
}
#if !NETSTANDARD_TODO
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "BeginAccept")]
private static void AcceptCallback(IAsyncResult result)
{
var ima = result.AsyncState as IncomingMessageAcceptor;
try
{
if (ima == null)
{
var logger = LogManager.GetLogger("IncomingMessageAcceptor", LoggerType.Runtime);
if (result.AsyncState == null)
logger.Warn(ErrorCode.Messaging_IMA_AcceptCallbackNullState, "AcceptCallback invoked with a null unexpected async state");
else
logger.Warn(ErrorCode.Messaging_IMA_AcceptCallbackUnexpectedState, "AcceptCallback invoked with an unexpected async state of type {0}", result.AsyncState.GetType());
return;
}
// First check to see if we're shutting down, in which case there's no point in doing anything other
// than closing the accepting socket and returning.
if (ima.Cts.IsCancellationRequested)
{
SocketManager.CloseSocket(ima.AcceptingSocket);
ima.Log.Info(ErrorCode.Messaging_IMA_ClosingSocket, "Closing accepting socket during shutdown");
return;
}
// Then, start a new Accept
try
{
ima.AcceptingSocket.BeginAccept(AcceptCallback, ima);
}
catch (Exception ex)
{
ima.Log.Warn(ErrorCode.MessagingBeginAcceptSocketException, "Exception on accepting socket during BeginAccept", ex);
// Open a new one
ima.RestartAcceptingSocket();
}
Socket sock;
// Complete this accept
try
{
sock = ima.AcceptingSocket.EndAccept(result);
}
catch (ObjectDisposedException)
{
// Socket was closed, but we're not shutting down; we need to open a new socket and start over...
// Close the old socket and open a new one
ima.Log.Warn(ErrorCode.MessagingAcceptingSocketClosed, "Accepting socket was closed when not shutting down");
ima.RestartAcceptingSocket();
return;
}
catch (Exception ex)
{
// There was a network error. We need to get a new accepting socket and re-issue an accept before we continue.
// Close the old socket and open a new one
ima.Log.Warn(ErrorCode.MessagingEndAcceptSocketException, "Exception on accepting socket during EndAccept", ex);
ima.RestartAcceptingSocket();
return;
}
if (ima.Log.IsVerbose3) ima.Log.Verbose3("Received a connection from {0}", sock.RemoteEndPoint);
// Finally, process the incoming request:
// Prep the socket so it will reset on close
sock.LingerState = new LingerOption(true, 0);
// Add the socket to the open socket collection
if (ima.RecordOpenedSocket(sock))
{
// And set up the asynch receive
var rcc = new ReceiveCallbackContext(sock, ima);
try
{
rcc.BeginReceive(ReceiveCallback);
}
catch (Exception exception)
{
var socketException = exception as SocketException;
ima.Log.Warn(ErrorCode.Messaging_IMA_NewBeginReceiveException,
String.Format("Exception on new socket during BeginReceive with RemoteEndPoint {0}: {1}",
socketException != null ? socketException.SocketErrorCode.ToString() : "", rcc.RemoteEndPoint), exception);
ima.SafeCloseSocket(sock);
}
}
else
{
ima.SafeCloseSocket(sock);
}
}
catch (Exception ex)
{
var logger = ima != null ? ima.Log : LogManager.GetLogger("IncomingMessageAcceptor", LoggerType.Runtime);
logger.Error(ErrorCode.Messaging_IMA_ExceptionAccepting, "Unexpected exception in IncomingMessageAccepter.AcceptCallback", ex);
}
}
private static void ReceiveCallback(IAsyncResult result)
{
var rcc = result.AsyncState as ReceiveCallbackContext;
if (rcc == null)
{
// This should never happen. Trap it and drop it on the floor because allowing a null reference exception would
// kill the process silently.
return;
}
try
{
// First check to see if we're shutting down, in which case there's no point in doing anything other
// than closing the accepting socket and returning.
if (rcc.IMA.Cts.IsCancellationRequested)
{
// We're exiting, so close the socket and clean up
rcc.IMA.SafeCloseSocket(rcc.Sock);
}
int bytes;
// Complete the receive
try
{
bytes = rcc.Sock.EndReceive(result);
}
catch (ObjectDisposedException)
{
// The socket is closed. Just clean up and return.
rcc.IMA.RecordClosedSocket(rcc.Sock);
return;
}
catch (Exception ex)
{
rcc.IMA.Log.Warn(ErrorCode.Messaging_ExceptionReceiving, "Exception while completing a receive from " + rcc.Sock.RemoteEndPoint, ex);
// Either there was a network error or the socket is being closed. Either way, just clean up and return.
rcc.IMA.SafeCloseSocket(rcc.Sock);
return;
}
//rcc.IMA.log.Verbose("Receive completed with " + bytes.ToString(CultureInfo.InvariantCulture) + " bytes");
if (bytes == 0)
{
// Socket was closed by the sender. so close our end
rcc.IMA.SafeCloseSocket(rcc.Sock);
// And we're done
return;
}
// Process the buffer we received
try
{
rcc.ProcessReceivedBuffer(bytes);
}
catch (Exception ex)
{
rcc.IMA.Log.Error(ErrorCode.Messaging_IMA_BadBufferReceived,
String.Format("ProcessReceivedBuffer exception with RemoteEndPoint {0}: ",
rcc.RemoteEndPoint), ex);
// There was a problem with the buffer, presumably data corruption, so give up
rcc.IMA.SafeCloseSocket(rcc.Sock);
// And we're done
return;
}
// Start the next receive. Note that if this throws, the exception will be logged in the catch below.
rcc.BeginReceive(ReceiveCallback);
}
catch (Exception ex)
{
rcc.IMA.Log.Warn(ErrorCode.Messaging_IMA_DroppingConnection, "Exception receiving from end point " + rcc.RemoteEndPoint, ex);
rcc.IMA.SafeCloseSocket(rcc.Sock);
}
}
#endif
protected virtual void HandleMessage(Message msg, Socket receivedOnSocket)
{
// See it's a Ping message, and if so, short-circuit it
object pingObj;
var requestContext = msg.RequestContextData;
if (requestContext != null &&
requestContext.TryGetValue(RequestContext.PING_APPLICATION_HEADER, out pingObj) &&
pingObj is bool &&
(bool)pingObj)
{
MessagingStatisticsGroup.OnPingReceive(msg.SendingSilo);
if (Log.IsVerbose2) Log.Verbose2("Responding to Ping from {0}", msg.SendingSilo);
if (!msg.TargetSilo.Equals(MessageCenter.MyAddress)) // got ping that is not destined to me. For example, got a ping to my older incarnation.
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message rejection = msg.CreateRejectionResponse(Message.RejectionTypes.Unrecoverable,
string.Format("The target silo is no longer active: target was {0}, but this silo is {1}. The rejected ping message is {2}.",
msg.TargetSilo.ToLongString(), MessageCenter.MyAddress.ToLongString(), msg));
MessageCenter.OutboundQueue.SendMessage(rejection);
}
else
{
var response = msg.CreateResponseMessage();
response.BodyObject = Response.Done;
MessageCenter.SendMessage(response);
}
return;
}
// sniff message headers for directory cache management
if (sniffIncomingMessageHandler != null)
sniffIncomingMessageHandler(msg);
// Don't process messages that have already timed out
if (msg.IsExpired)
{
msg.DropExpiredMessage(MessagingStatisticsGroup.Phase.Receive);
return;
}
// If we've stopped application message processing, then filter those out now
// Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here.
if (MessageCenter.IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && !Constants.SystemMembershipTableId.Equals(msg.SendingGrain))
{
// We reject new requests, and drop all other messages
if (msg.Direction != Message.Directions.Request) return;
MessagingStatisticsGroup.OnRejectedMessage(msg);
var reject = msg.CreateRejectionResponse(Message.RejectionTypes.Unrecoverable, "Silo stopping");
MessageCenter.SendMessage(reject);
return;
}
// Make sure the message is for us. Note that some control messages may have no target
// information, so a null target silo is OK.
if ((msg.TargetSilo == null) || msg.TargetSilo.Matches(MessageCenter.MyAddress))
{
// See if it's a message for a client we're proxying.
if (MessageCenter.IsProxying && MessageCenter.TryDeliverToProxy(msg)) return;
// Nope, it's for us
MessageCenter.InboundQueue.PostMessage(msg);
return;
}
if (!msg.TargetSilo.Endpoint.Equals(MessageCenter.MyAddress.Endpoint))
{
// If the message is for some other silo altogether, then we need to forward it.
if (Log.IsVerbose2) Log.Verbose2("Forwarding message {0} from {1} to silo {2}", msg.Id, msg.SendingSilo, msg.TargetSilo);
MessageCenter.OutboundQueue.SendMessage(msg);
return;
}
// If the message was for this endpoint but an older epoch, then reject the message
// (if it was a request), or drop it on the floor if it was a response or one-way.
if (msg.Direction == Message.Directions.Request)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message rejection = msg.CreateRejectionResponse(Message.RejectionTypes.Transient,
string.Format("The target silo is no longer active: target was {0}, but this silo is {1}. The rejected message is {2}.",
msg.TargetSilo.ToLongString(), MessageCenter.MyAddress.ToLongString(), msg));
MessageCenter.OutboundQueue.SendMessage(rejection);
if (Log.IsVerbose) Log.Verbose("Rejecting an obsolete request; target was {0}, but this silo is {1}. The rejected message is {2}.",
msg.TargetSilo.ToLongString(), MessageCenter.MyAddress.ToLongString(), msg);
}
}
#if !NETSTANDARD_TODO
private void RestartAcceptingSocket()
{
try
{
SocketManager.CloseSocket(AcceptingSocket);
AcceptingSocket = SocketManager.GetAcceptingSocketForEndpoint(listenAddress);
AcceptingSocket.Listen(LISTEN_BACKLOG_SIZE);
AcceptingSocket.BeginAccept(AcceptCallback, this);
}
catch (Exception ex)
{
Log.Error(ErrorCode.Runtime_Error_100016, "Unable to create a new accepting socket", ex);
throw;
}
}
#endif
private void SafeCloseSocket(Socket sock)
{
RecordClosedSocket(sock);
SocketManager.CloseSocket(sock);
}
#if !NETSTANDARD_TODO
private class ReceiveCallbackContext
{
private readonly IncomingMessageBuffer _buffer;
public Socket Sock { get; private set; }
public EndPoint RemoteEndPoint { get; private set; }
public IncomingMessageAcceptor IMA { get; private set; }
public ReceiveCallbackContext(Socket sock, IncomingMessageAcceptor ima)
{
Sock = sock;
RemoteEndPoint = sock.RemoteEndPoint;
IMA = ima;
_buffer = new IncomingMessageBuffer(ima.Log);
}
public void BeginReceive(AsyncCallback callback)
{
try
{
Sock.BeginReceive(_buffer.BuildReceiveBuffer(), SocketFlags.None, callback, this);
}
catch (Exception ex)
{
IMA.Log.Warn(ErrorCode.MessagingBeginReceiveException, "Exception trying to begin receive from endpoint " + RemoteEndPoint, ex);
throw;
}
}
#if TRACK_DETAILED_STATS
// Global collection of ThreadTrackingStatistic for thread pool and IO completion threads.
public static readonly System.Collections.Concurrent.ConcurrentDictionary<int, ThreadTrackingStatistic> trackers = new System.Collections.Concurrent.ConcurrentDictionary<int, ThreadTrackingStatistic>();
#endif
public void ProcessReceivedBuffer(int bytes)
{
if (bytes == 0)
return;
#if TRACK_DETAILED_STATS
ThreadTrackingStatistic tracker = null;
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
int id = System.Threading.Thread.CurrentThread.ManagedThreadId;
if (!trackers.TryGetValue(id, out tracker))
{
tracker = new ThreadTrackingStatistic("ThreadPoolThread." + System.Threading.Thread.CurrentThread.ManagedThreadId);
bool added = trackers.TryAdd(id, tracker);
if (added)
{
tracker.OnStartExecution();
}
}
tracker.OnStartProcessing();
}
#endif
try
{
_buffer.UpdateReceivedData(bytes);
Message msg;
while (_buffer.TryDecodeMessage(out msg))
{
IMA.HandleMessage(msg, Sock);
}
}
catch (Exception exc)
{
try
{
// Log details of receive state machine
IMA.Log.Error(ErrorCode.MessagingProcessReceiveBufferException,
string.Format(
"Exception trying to process {0} bytes from endpoint {1}",
bytes, RemoteEndPoint),
exc);
}
catch (Exception) { }
_buffer.Reset(); // Reset back to a hopefully good base state
throw;
}
#if TRACK_DETAILED_STATS
finally
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
tracker.IncrementNumberOfProcessed();
tracker.OnStopProcessing();
}
}
#endif
}
}
#endif
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Threading;
using Nwc.XmlRpc;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
/***************************************************************************
* Simian Data Map
* ===============
*
* OwnerID -> Type -> Key
* -----------------------
*
* UserID -> Group -> ActiveGroup
* + GroupID
*
* UserID -> GroupSessionDropped -> GroupID
* UserID -> GroupSessionInvited -> GroupID
*
* UserID -> GroupMember -> GroupID
* + SelectedRoleID [UUID]
* + AcceptNotices [bool]
* + ListInProfile [bool]
* + Contribution [int]
*
* UserID -> GroupRole[GroupID] -> RoleID
*
*
* GroupID -> Group -> GroupName
* + Charter
* + ShowInList
* + InsigniaID
* + MembershipFee
* + OpenEnrollment
* + AllowPublish
* + MaturePublish
* + FounderID
* + EveryonePowers
* + OwnerRoleID
* + OwnersPowers
*
* GroupID -> GroupRole -> RoleID
* + Name
* + Description
* + Title
* + Powers
*
* GroupID -> GroupMemberInvite -> InviteID
* + AgentID
* + RoleID
*
* GroupID -> GroupNotice -> NoticeID
* + TimeStamp [uint]
* + FromName [string]
* + Subject [string]
* + Message [string]
* + BinaryBucket [byte[]]
*
* */
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianGroupsServicesConnectorModule")]
public class SimianGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome |
GroupPowers.Accountable |
GroupPowers.JoinChat |
GroupPowers.AllowVoiceChat |
GroupPowers.ReceiveNotices |
GroupPowers.StartProposal |
GroupPowers.VoteOnProposal;
// Would this be cleaner as (GroupPowers)ulong.MaxValue;
public const GroupPowers m_DefaultOwnerPowers = GroupPowers.Accountable
| GroupPowers.AllowEditLand
| GroupPowers.AllowFly
| GroupPowers.AllowLandmark
| GroupPowers.AllowRez
| GroupPowers.AllowSetHome
| GroupPowers.AllowVoiceChat
| GroupPowers.AssignMember
| GroupPowers.AssignMemberLimited
| GroupPowers.ChangeActions
| GroupPowers.ChangeIdentity
| GroupPowers.ChangeMedia
| GroupPowers.ChangeOptions
| GroupPowers.CreateRole
| GroupPowers.DeedObject
| GroupPowers.DeleteRole
| GroupPowers.Eject
| GroupPowers.FindPlaces
| GroupPowers.Invite
| GroupPowers.JoinChat
| GroupPowers.LandChangeIdentity
| GroupPowers.LandDeed
| GroupPowers.LandDivideJoin
| GroupPowers.LandEdit
| GroupPowers.LandEjectAndFreeze
| GroupPowers.LandGardening
| GroupPowers.LandManageAllowed
| GroupPowers.LandManageBanned
| GroupPowers.LandManagePasses
| GroupPowers.LandOptions
| GroupPowers.LandRelease
| GroupPowers.LandSetSale
| GroupPowers.ModerateChat
| GroupPowers.ObjectManipulate
| GroupPowers.ObjectSetForSale
| GroupPowers.ReceiveNotices
| GroupPowers.RemoveMember
| GroupPowers.ReturnGroupOwned
| GroupPowers.ReturnGroupSet
| GroupPowers.ReturnNonGroup
| GroupPowers.RoleProperties
| GroupPowers.SendNotices
| GroupPowers.SetLandingPoint
| GroupPowers.StartProposal
| GroupPowers.VoteOnProposal;
private bool m_connectorEnabled = false;
private string m_groupsServerURI = string.Empty;
private bool m_debugEnabled = false;
private Dictionary<string, bool> m_pendingRequests = new Dictionary<string,bool>();
private ExpiringCache<string, OSDMap> m_memoryCache;
private int m_cacheTimeout = 30;
// private IUserAccountService m_accountService = null;
#region Region Module interfaceBase Members
public string Name
{
get { return "SimianGroupsServicesConnector"; }
}
// this module is not intended to be replaced, but there should only be 1 of them.
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
// if groups aren't enabled, we're not needed.
// if we're not specified as the connector to use, then we're not wanted
if ((groupsConfig.GetBoolean("Enabled", false) == false)
|| (groupsConfig.GetString("ServicesConnectorModule", "XmlRpcGroupsServicesConnector") != Name))
{
m_connectorEnabled = false;
return;
}
m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR]: Initializing {0}", this.Name);
m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty);
if (string.IsNullOrEmpty(m_groupsServerURI))
{
m_log.ErrorFormat("Please specify a valid Simian Server for GroupsServerURI in OpenSim.ini, [Groups]");
m_connectorEnabled = false;
return;
}
m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30);
if (m_cacheTimeout == 0)
{
m_log.WarnFormat("[SIMIAN-GROUPS-CONNECTOR] Groups Cache Disabled.");
}
else
{
m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Groups Cache Timeout set to {0}.", m_cacheTimeout);
}
m_memoryCache = new ExpiringCache<string,OSDMap>();
// If we got all the config options we need, lets start'er'up
m_connectorEnabled = true;
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true);
}
}
public void Close()
{
m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR]: Closing {0}", this.Name);
}
public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (m_connectorEnabled)
{
scene.RegisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this)
{
scene.UnregisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene)
{
// TODO: May want to consider listenning for Agent Connections so we can pre-cache group info
// scene.EventManager.OnNewClient += OnNewClient;
}
#endregion
#region ISharedRegionModule Members
public void PostInitialise()
{
// NoOp
}
#endregion
#region IGroupsServicesConnector Members
/// <summary>
/// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role.
/// </summary>
public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
int membershipFee, bool openEnrollment, bool allowPublish,
bool maturePublish, UUID founderID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
UUID GroupID = UUID.Random();
UUID OwnerRoleID = UUID.Random();
OSDMap GroupInfoMap = new OSDMap();
GroupInfoMap["Charter"] = OSD.FromString(charter);
GroupInfoMap["ShowInList"] = OSD.FromBoolean(showInList);
GroupInfoMap["InsigniaID"] = OSD.FromUUID(insigniaID);
GroupInfoMap["MembershipFee"] = OSD.FromInteger(0);
GroupInfoMap["OpenEnrollment"] = OSD.FromBoolean(openEnrollment);
GroupInfoMap["AllowPublish"] = OSD.FromBoolean(allowPublish);
GroupInfoMap["MaturePublish"] = OSD.FromBoolean(maturePublish);
GroupInfoMap["FounderID"] = OSD.FromUUID(founderID);
GroupInfoMap["EveryonePowers"] = OSD.FromULong((ulong)m_DefaultEveryonePowers);
GroupInfoMap["OwnerRoleID"] = OSD.FromUUID(OwnerRoleID);
GroupInfoMap["OwnersPowers"] = OSD.FromULong((ulong)m_DefaultOwnerPowers);
if (SimianAddGeneric(GroupID, "Group", name, GroupInfoMap))
{
AddGroupRole(requestingAgentID, GroupID, UUID.Zero, "Everyone", "Members of " + name, "Member of " + name, (ulong)m_DefaultEveryonePowers);
AddGroupRole(requestingAgentID, GroupID, OwnerRoleID, "Owners", "Owners of " + name, "Owner of " + name, (ulong)m_DefaultOwnerPowers);
AddAgentToGroup(requestingAgentID, requestingAgentID, GroupID, OwnerRoleID);
return GroupID;
}
else
{
return UUID.Zero;
}
}
public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList,
UUID insigniaID, int membershipFee, bool openEnrollment,
bool allowPublish, bool maturePublish)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// TODO: Check to make sure requestingAgentID has permission to update group
string GroupName;
OSDMap GroupInfoMap;
if (SimianGetFirstGenericEntry(groupID, "GroupInfo", out GroupName, out GroupInfoMap))
{
GroupInfoMap["Charter"] = OSD.FromString(charter);
GroupInfoMap["ShowInList"] = OSD.FromBoolean(showInList);
GroupInfoMap["InsigniaID"] = OSD.FromUUID(insigniaID);
GroupInfoMap["MembershipFee"] = OSD.FromInteger(0);
GroupInfoMap["OpenEnrollment"] = OSD.FromBoolean(openEnrollment);
GroupInfoMap["AllowPublish"] = OSD.FromBoolean(allowPublish);
GroupInfoMap["MaturePublish"] = OSD.FromBoolean(maturePublish);
SimianAddGeneric(groupID, "Group", GroupName, GroupInfoMap);
}
}
public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupRoleInfo = new OSDMap();
GroupRoleInfo["Name"] = OSD.FromString(name);
GroupRoleInfo["Description"] = OSD.FromString(description);
GroupRoleInfo["Title"] = OSD.FromString(title);
GroupRoleInfo["Powers"] = OSD.FromULong((ulong)powers);
// TODO: Add security, make sure that requestingAgentID has permision to add roles
SimianAddGeneric(groupID, "GroupRole", roleID.ToString(), GroupRoleInfo);
}
public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// TODO: Add security
// Can't delete the Everyone Role
if (roleID != UUID.Zero)
{
// Remove all GroupRole Members from Role
Dictionary<UUID, OSDMap> GroupRoleMembers;
string GroupRoleMemberType = "GroupRole" + groupID.ToString();
if (SimianGetGenericEntries(GroupRoleMemberType, roleID.ToString(), out GroupRoleMembers))
{
foreach (UUID UserID in GroupRoleMembers.Keys)
{
EnsureRoleNotSelectedByMember(groupID, roleID, UserID);
SimianRemoveGenericEntry(UserID, GroupRoleMemberType, roleID.ToString());
}
}
// Remove role
SimianRemoveGenericEntry(groupID, "GroupRole", roleID.ToString());
}
}
public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// TODO: Security, check that requestingAgentID is allowed to update group roles
OSDMap GroupRoleInfo;
if (SimianGetGenericEntry(groupID, "GroupRole", roleID.ToString(), out GroupRoleInfo))
{
if (name != null)
{
GroupRoleInfo["Name"] = OSD.FromString(name);
}
if (description != null)
{
GroupRoleInfo["Description"] = OSD.FromString(description);
}
if (title != null)
{
GroupRoleInfo["Title"] = OSD.FromString(title);
}
GroupRoleInfo["Powers"] = OSD.FromULong((ulong)powers);
}
SimianAddGeneric(groupID, "GroupRole", roleID.ToString(), GroupRoleInfo);
}
public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID groupID, string groupName)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupInfoMap = null;
if (groupID != UUID.Zero)
{
if (!SimianGetFirstGenericEntry(groupID, "Group", out groupName, out GroupInfoMap))
{
return null;
}
}
else if (!string.IsNullOrEmpty(groupName))
{
if (!SimianGetFirstGenericEntry("Group", groupName, out groupID, out GroupInfoMap))
{
return null;
}
}
GroupRecord GroupInfo = new GroupRecord();
GroupInfo.GroupID = groupID;
GroupInfo.GroupName = groupName;
GroupInfo.Charter = GroupInfoMap["Charter"].AsString();
GroupInfo.ShowInList = GroupInfoMap["ShowInList"].AsBoolean();
GroupInfo.GroupPicture = GroupInfoMap["InsigniaID"].AsUUID();
GroupInfo.MembershipFee = GroupInfoMap["MembershipFee"].AsInteger();
GroupInfo.OpenEnrollment = GroupInfoMap["OpenEnrollment"].AsBoolean();
GroupInfo.AllowPublish = GroupInfoMap["AllowPublish"].AsBoolean();
GroupInfo.MaturePublish = GroupInfoMap["MaturePublish"].AsBoolean();
GroupInfo.FounderID = GroupInfoMap["FounderID"].AsUUID();
GroupInfo.OwnerRoleID = GroupInfoMap["OwnerRoleID"].AsUUID();
return GroupInfo;
}
public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID groupID, UUID memberID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap groupProfile;
string groupName;
if (!SimianGetFirstGenericEntry(groupID, "Group", out groupName, out groupProfile))
{
// GroupProfileData is not nullable
return new GroupProfileData();
}
GroupProfileData MemberGroupProfile = new GroupProfileData();
MemberGroupProfile.GroupID = groupID;
MemberGroupProfile.Name = groupName;
if (groupProfile["Charter"] != null)
{
MemberGroupProfile.Charter = groupProfile["Charter"].AsString();
}
MemberGroupProfile.ShowInList = groupProfile["ShowInList"].AsString() == "1";
MemberGroupProfile.InsigniaID = groupProfile["InsigniaID"].AsUUID();
MemberGroupProfile.MembershipFee = groupProfile["MembershipFee"].AsInteger();
MemberGroupProfile.OpenEnrollment = groupProfile["OpenEnrollment"].AsBoolean();
MemberGroupProfile.AllowPublish = groupProfile["AllowPublish"].AsBoolean();
MemberGroupProfile.MaturePublish = groupProfile["MaturePublish"].AsBoolean();
MemberGroupProfile.FounderID = groupProfile["FounderID"].AsUUID();;
MemberGroupProfile.OwnerRole = groupProfile["OwnerRoleID"].AsUUID();
Dictionary<UUID, OSDMap> Members;
if (SimianGetGenericEntries("GroupMember",groupID.ToString(), out Members))
{
MemberGroupProfile.GroupMembershipCount = Members.Count;
}
Dictionary<string, OSDMap> Roles;
if (SimianGetGenericEntries(groupID, "GroupRole", out Roles))
{
MemberGroupProfile.GroupRolesCount = Roles.Count;
}
// TODO: Get Group Money balance from somewhere
// group.Money = 0;
GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, memberID, groupID);
MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle;
MemberGroupProfile.PowersMask = MemberInfo.GroupPowers;
return MemberGroupProfile;
}
public void SetAgentActiveGroup(UUID requestingAgentID, UUID agentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap ActiveGroup = new OSDMap();
ActiveGroup.Add("GroupID", OSD.FromUUID(groupID));
SimianAddGeneric(agentID, "Group", "ActiveGroup", ActiveGroup);
}
public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupMemberInfo;
if (!SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out GroupMemberInfo))
{
GroupMemberInfo = new OSDMap();
}
GroupMemberInfo["SelectedRoleID"] = OSD.FromUUID(roleID);
SimianAddGeneric(agentID, "GroupMember", groupID.ToString(), GroupMemberInfo);
}
public void SetAgentGroupInfo(UUID requestingAgentID, UUID agentID, UUID groupID, bool acceptNotices, bool listInProfile)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupMemberInfo;
if (!SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out GroupMemberInfo))
{
GroupMemberInfo = new OSDMap();
}
GroupMemberInfo["AcceptNotices"] = OSD.FromBoolean(acceptNotices);
GroupMemberInfo["ListInProfile"] = OSD.FromBoolean(listInProfile);
GroupMemberInfo["Contribution"] = OSD.FromInteger(0);
GroupMemberInfo["SelectedRole"] = OSD.FromUUID(UUID.Zero);
SimianAddGeneric(agentID, "GroupMember", groupID.ToString(), GroupMemberInfo);
}
public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap Invite = new OSDMap();
Invite["AgentID"] = OSD.FromUUID(agentID);
Invite["RoleID"] = OSD.FromUUID(roleID);
SimianAddGeneric(groupID, "GroupMemberInvite", inviteID.ToString(), Invite);
}
public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupMemberInvite;
UUID GroupID;
if (!SimianGetFirstGenericEntry("GroupMemberInvite", inviteID.ToString(), out GroupID, out GroupMemberInvite))
{
return null;
}
GroupInviteInfo inviteInfo = new GroupInviteInfo();
inviteInfo.InviteID = inviteID;
inviteInfo.GroupID = GroupID;
inviteInfo.AgentID = GroupMemberInvite["AgentID"].AsUUID();
inviteInfo.RoleID = GroupMemberInvite["RoleID"].AsUUID();
return inviteInfo;
}
public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupInviteInfo invite = GetAgentToGroupInvite(requestingAgentID, inviteID);
SimianRemoveGenericEntry(invite.GroupID, "GroupMemberInvite", inviteID.ToString());
}
public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Setup Agent/Group information
SetAgentGroupInfo(requestingAgentID, AgentID, GroupID, true, true);
// Add agent to Everyone Group
AddAgentToGroupRole(requestingAgentID, AgentID, GroupID, UUID.Zero);
// Add agent to Specified Role
AddAgentToGroupRole(requestingAgentID, AgentID, GroupID, RoleID);
// Set selected role in this group to specified role
SetAgentActiveGroupRole(requestingAgentID, AgentID, GroupID, RoleID);
}
public void RemoveAgentFromGroup(UUID requestingAgentID, UUID agentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// If current active group is the group the agent is being removed from, change their group to UUID.Zero
GroupMembershipData memberActiveMembership = GetAgentActiveMembership(requestingAgentID, agentID);
if (memberActiveMembership.GroupID == groupID)
{
SetAgentActiveGroup(agentID, agentID, UUID.Zero);
}
// Remove Group Member information for this group
SimianRemoveGenericEntry(agentID, "GroupMember", groupID.ToString());
// By using a Simian Generics Type consisting of a prefix and a groupID,
// combined with RoleID as key allows us to get a list of roles a particular member
// of a group is assigned to.
string GroupRoleMemberType = "GroupRole" + groupID.ToString();
// Take Agent out of all other group roles
Dictionary<string, OSDMap> GroupRoles;
if (SimianGetGenericEntries(agentID, GroupRoleMemberType, out GroupRoles))
{
foreach (string roleID in GroupRoles.Keys)
{
SimianRemoveGenericEntry(agentID, GroupRoleMemberType, roleID);
}
}
}
public void AddAgentToGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
SimianAddGeneric(agentID, "GroupRole" + groupID.ToString(), roleID.ToString(), new OSDMap());
}
public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Cannot remove members from the Everyone Role
if (roleID != UUID.Zero)
{
EnsureRoleNotSelectedByMember(groupID, roleID, agentID);
string GroupRoleMemberType = "GroupRole" + groupID.ToString();
SimianRemoveGenericEntry(agentID, GroupRoleMemberType, roleID.ToString());
}
}
public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "Type", "Group" },
{ "Key", search },
{ "Fuzzy", "1" }
};
OSDMap response = CachedPostRequest(requestArgs);
if (response["Success"].AsBoolean() && response["Entries"] is OSDArray)
{
OSDArray entryArray = (OSDArray)response["Entries"];
foreach (OSDMap entryMap in entryArray)
{
DirGroupsReplyData data = new DirGroupsReplyData();
data.groupID = entryMap["OwnerID"].AsUUID();
data.groupName = entryMap["Key"].AsString();
// TODO: is there a better way to do this?
Dictionary<UUID, OSDMap> Members;
if (SimianGetGenericEntries("GroupMember", data.groupID.ToString(), out Members))
{
data.members = Members.Count;
}
else
{
data.members = 0;
}
// TODO: sort results?
// data.searchOrder = order;
findings.Add(data);
}
}
return findings;
}
public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID agentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupMembershipData data = null;
// bool foundData = false;
OSDMap UserGroupMemberInfo;
if (SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out UserGroupMemberInfo))
{
data = new GroupMembershipData();
data.AcceptNotices = UserGroupMemberInfo["AcceptNotices"].AsBoolean();
data.Contribution = UserGroupMemberInfo["Contribution"].AsInteger();
data.ListInProfile = UserGroupMemberInfo["ListInProfile"].AsBoolean();
data.ActiveRole = UserGroupMemberInfo["SelectedRoleID"].AsUUID();
///////////////////////////////
// Agent Specific Information:
//
OSDMap UserActiveGroup;
if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup))
{
data.Active = UserActiveGroup["GroupID"].AsUUID().Equals(groupID);
}
///////////////////////////////
// Role Specific Information:
//
OSDMap GroupRoleInfo;
if (SimianGetGenericEntry(groupID, "GroupRole", data.ActiveRole.ToString(), out GroupRoleInfo))
{
data.GroupTitle = GroupRoleInfo["Title"].AsString();
data.GroupPowers = GroupRoleInfo["Powers"].AsULong();
}
///////////////////////////////
// Group Specific Information:
//
OSDMap GroupInfo;
string GroupName;
if (SimianGetFirstGenericEntry(groupID, "Group", out GroupName, out GroupInfo))
{
data.GroupID = groupID;
data.AllowPublish = GroupInfo["AllowPublish"].AsBoolean();
data.Charter = GroupInfo["Charter"].AsString();
data.FounderID = GroupInfo["FounderID"].AsUUID();
data.GroupName = GroupName;
data.GroupPicture = GroupInfo["InsigniaID"].AsUUID();
data.MaturePublish = GroupInfo["MaturePublish"].AsBoolean();
data.MembershipFee = GroupInfo["MembershipFee"].AsInteger();
data.OpenEnrollment = GroupInfo["OpenEnrollment"].AsBoolean();
data.ShowInList = GroupInfo["ShowInList"].AsBoolean();
}
}
return data;
}
public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID agentID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
UUID GroupID = UUID.Zero;
OSDMap UserActiveGroup;
if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup))
{
GroupID = UserActiveGroup["GroupID"].AsUUID();
}
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Active GroupID : {0}", GroupID.ToString());
return GetAgentGroupMembership(requestingAgentID, agentID, GroupID);
}
public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID agentID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupMembershipData> memberships = new List<GroupMembershipData>();
Dictionary<string,OSDMap> GroupMemberShips;
if (SimianGetGenericEntries(agentID, "GroupMember", out GroupMemberShips))
{
foreach (string key in GroupMemberShips.Keys)
{
memberships.Add(GetAgentGroupMembership(requestingAgentID, agentID, UUID.Parse(key)));
}
}
return memberships;
}
public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID agentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRolesData> Roles = new List<GroupRolesData>();
Dictionary<string, OSDMap> GroupRoles;
if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles))
{
Dictionary<string, OSDMap> MemberRoles;
if (SimianGetGenericEntries(agentID, "GroupRole" + groupID.ToString(), out MemberRoles))
{
foreach (KeyValuePair<string, OSDMap> kvp in MemberRoles)
{
GroupRolesData data = new GroupRolesData();
data.RoleID = UUID.Parse(kvp.Key);
data.Name = GroupRoles[kvp.Key]["Name"].AsString();
data.Description = GroupRoles[kvp.Key]["Description"].AsString();
data.Title = GroupRoles[kvp.Key]["Title"].AsString();
data.Powers = GroupRoles[kvp.Key]["Powers"].AsULong();
Roles.Add(data);
}
}
}
return Roles;
}
public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRolesData> Roles = new List<GroupRolesData>();
Dictionary<string, OSDMap> GroupRoles;
if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles))
{
foreach (KeyValuePair<string, OSDMap> role in GroupRoles)
{
GroupRolesData data = new GroupRolesData();
data.RoleID = UUID.Parse(role.Key);
data.Name = role.Value["Name"].AsString();
data.Description = role.Value["Description"].AsString();
data.Title = role.Value["Title"].AsString();
data.Powers = role.Value["Powers"].AsULong();
Dictionary<UUID, OSDMap> GroupRoleMembers;
if (SimianGetGenericEntries("GroupRole" + groupID.ToString(), role.Key, out GroupRoleMembers))
{
data.Members = GroupRoleMembers.Count;
}
else
{
data.Members = 0;
}
Roles.Add(data);
}
}
return Roles;
}
public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupMembersData> members = new List<GroupMembersData>();
OSDMap GroupInfo;
string GroupName;
UUID GroupOwnerRoleID = UUID.Zero;
if (!SimianGetFirstGenericEntry(GroupID, "Group", out GroupName, out GroupInfo))
{
return members;
}
GroupOwnerRoleID = GroupInfo["OwnerRoleID"].AsUUID();
// Locally cache group roles, since we'll be needing this data for each member
Dictionary<string,OSDMap> GroupRoles;
SimianGetGenericEntries(GroupID, "GroupRole", out GroupRoles);
// Locally cache list of group owners
Dictionary<UUID, OSDMap> GroupOwners;
SimianGetGenericEntries("GroupRole" + GroupID.ToString(), GroupOwnerRoleID.ToString(), out GroupOwners);
Dictionary<UUID, OSDMap> GroupMembers;
if (SimianGetGenericEntries("GroupMember", GroupID.ToString(), out GroupMembers))
{
foreach (KeyValuePair<UUID, OSDMap> member in GroupMembers)
{
GroupMembersData data = new GroupMembersData();
data.AgentID = member.Key;
UUID SelectedRoleID = member.Value["SelectedRoleID"].AsUUID();
data.AcceptNotices = member.Value["AcceptNotices"].AsBoolean();
data.ListInProfile = member.Value["ListInProfile"].AsBoolean();
data.Contribution = member.Value["Contribution"].AsInteger();
data.IsOwner = GroupOwners.ContainsKey(member.Key);
OSDMap GroupRoleInfo = GroupRoles[SelectedRoleID.ToString()];
data.Title = GroupRoleInfo["Title"].AsString();
data.AgentPowers = GroupRoleInfo["Powers"].AsULong();
members.Add(data);
}
}
return members;
}
public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRoleMembersData> members = new List<GroupRoleMembersData>();
Dictionary<string, OSDMap> GroupRoles;
if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles))
{
foreach (KeyValuePair<string, OSDMap> Role in GroupRoles)
{
Dictionary<UUID, OSDMap> GroupRoleMembers;
if (SimianGetGenericEntries("GroupRole"+groupID.ToString(), Role.Key, out GroupRoleMembers))
{
foreach (KeyValuePair<UUID, OSDMap> GroupRoleMember in GroupRoleMembers)
{
GroupRoleMembersData data = new GroupRoleMembersData();
data.MemberID = GroupRoleMember.Key;
data.RoleID = UUID.Parse(Role.Key);
members.Add(data);
}
}
}
}
return members;
}
public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupNoticeData> values = new List<GroupNoticeData>();
Dictionary<string, OSDMap> Notices;
if (SimianGetGenericEntries(GroupID, "GroupNotice", out Notices))
{
foreach (KeyValuePair<string, OSDMap> Notice in Notices)
{
GroupNoticeData data = new GroupNoticeData();
data.NoticeID = UUID.Parse(Notice.Key);
data.Timestamp = Notice.Value["TimeStamp"].AsUInteger();
data.FromName = Notice.Value["FromName"].AsString();
data.Subject = Notice.Value["Subject"].AsString();
data.HasAttachment = Notice.Value["BinaryBucket"].AsBinary().Length > 0;
//TODO: Figure out how to get this
data.AssetType = 0;
values.Add(data);
}
}
return values;
}
public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupNotice;
UUID GroupID;
if (SimianGetFirstGenericEntry("GroupNotice", noticeID.ToString(), out GroupID, out GroupNotice))
{
GroupNoticeInfo data = new GroupNoticeInfo();
data.GroupID = GroupID;
data.Message = GroupNotice["Message"].AsString();
data.BinaryBucket = GroupNotice["BinaryBucket"].AsBinary();
data.noticeData.NoticeID = noticeID;
data.noticeData.Timestamp = GroupNotice["TimeStamp"].AsUInteger();
data.noticeData.FromName = GroupNotice["FromName"].AsString();
data.noticeData.Subject = GroupNotice["Subject"].AsString();
data.noticeData.HasAttachment = data.BinaryBucket.Length > 0;
data.noticeData.AssetType = 0;
if (data.Message == null)
{
data.Message = string.Empty;
}
return data;
}
return null;
}
public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap Notice = new OSDMap();
Notice["TimeStamp"] = OSD.FromUInteger((uint)Util.UnixTimeSinceEpoch());
Notice["FromName"] = OSD.FromString(fromName);
Notice["Subject"] = OSD.FromString(subject);
Notice["Message"] = OSD.FromString(message);
Notice["BinaryBucket"] = OSD.FromBinary(binaryBucket);
SimianAddGeneric(groupID, "GroupNotice", noticeID.ToString(), Notice);
}
#endregion
#region GroupSessionTracking
public void ResetAgentGroupChatSessions(UUID agentID)
{
Dictionary<string, OSDMap> agentSessions;
if (SimianGetGenericEntries(agentID, "GroupSessionDropped", out agentSessions))
{
foreach (string GroupID in agentSessions.Keys)
{
SimianRemoveGenericEntry(agentID, "GroupSessionDropped", GroupID);
}
}
if (SimianGetGenericEntries(agentID, "GroupSessionInvited", out agentSessions))
{
foreach (string GroupID in agentSessions.Keys)
{
SimianRemoveGenericEntry(agentID, "GroupSessionInvited", GroupID);
}
}
}
public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID)
{
OSDMap session;
return SimianGetGenericEntry(agentID, "GroupSessionDropped", groupID.ToString(), out session);
}
public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID)
{
SimianAddGeneric(agentID, "GroupSessionDropped", groupID.ToString(), new OSDMap());
}
public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
SimianAddGeneric(agentID, "GroupSessionInvited", groupID.ToString(), new OSDMap());
}
public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
OSDMap session;
return SimianGetGenericEntry(agentID, "GroupSessionDropped", groupID.ToString(), out session);
}
#endregion
private void EnsureRoleNotSelectedByMember(UUID groupID, UUID roleID, UUID userID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// If member's SelectedRole is roleID, change their selected role to Everyone
// before removing them from the role
OSDMap UserGroupInfo;
if (SimianGetGenericEntry(userID, "GroupMember", groupID.ToString(), out UserGroupInfo))
{
if (UserGroupInfo["SelectedRoleID"].AsUUID() == roleID)
{
UserGroupInfo["SelectedRoleID"] = OSD.FromUUID(UUID.Zero);
}
SimianAddGeneric(userID, "GroupMember", groupID.ToString(), UserGroupInfo);
}
}
#region Simian Util Methods
private bool SimianAddGeneric(UUID ownerID, string type, string key, OSDMap map)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key);
string value = OSDParser.SerializeJsonString(map);
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] value: {0}", value);
NameValueCollection RequestArgs = new NameValueCollection
{
{ "RequestMethod", "AddGeneric" },
{ "OwnerID", ownerID.ToString() },
{ "Type", type },
{ "Key", key },
{ "Value", value}
};
OSDMap Response = CachedPostRequest(RequestArgs);
if (Response["Success"].AsBoolean())
{
return true;
}
else
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error {0}, {1}, {2}, {3}", ownerID, type, key, Response["Message"]);
return false;
}
}
/// <summary>
/// Returns the first of possibly many entries for Owner/Type pair
/// </summary>
private bool SimianGetFirstGenericEntry(UUID ownerID, string type, out string key, out OSDMap map)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type);
NameValueCollection RequestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "OwnerID", ownerID.ToString() },
{ "Type", type }
};
OSDMap Response = CachedPostRequest(RequestArgs);
if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray)
{
OSDArray entryArray = (OSDArray)Response["Entries"];
if (entryArray.Count >= 1)
{
OSDMap entryMap = entryArray[0] as OSDMap;
key = entryMap["Key"].AsString();
map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString());
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
return true;
}
else
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
}
}
else
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]);
}
key = null;
map = null;
return false;
}
private bool SimianGetFirstGenericEntry(string type, string key, out UUID ownerID, out OSDMap map)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, type, key);
NameValueCollection RequestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "Type", type },
{ "Key", key}
};
OSDMap Response = CachedPostRequest(RequestArgs);
if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray)
{
OSDArray entryArray = (OSDArray)Response["Entries"];
if (entryArray.Count >= 1)
{
OSDMap entryMap = entryArray[0] as OSDMap;
ownerID = entryMap["OwnerID"].AsUUID();
map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString());
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
return true;
}
else
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
}
}
else
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]);
}
ownerID = UUID.Zero;
map = null;
return false;
}
private bool SimianGetGenericEntry(UUID ownerID, string type, string key, out OSDMap map)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key);
NameValueCollection RequestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "OwnerID", ownerID.ToString() },
{ "Type", type },
{ "Key", key}
};
OSDMap Response = CachedPostRequest(RequestArgs);
if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray)
{
OSDArray entryArray = (OSDArray)Response["Entries"];
if (entryArray.Count == 1)
{
OSDMap entryMap = entryArray[0] as OSDMap;
key = entryMap["Key"].AsString();
map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString());
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
return true;
}
else
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
}
}
else
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]);
}
map = null;
return false;
}
private bool SimianGetGenericEntries(UUID ownerID, string type, out Dictionary<string, OSDMap> maps)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name,ownerID, type);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "OwnerID", ownerID.ToString() },
{ "Type", type }
};
OSDMap response = CachedPostRequest(requestArgs);
if (response["Success"].AsBoolean() && response["Entries"] is OSDArray)
{
maps = new Dictionary<string, OSDMap>();
OSDArray entryArray = (OSDArray)response["Entries"];
foreach (OSDMap entryMap in entryArray)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
maps.Add(entryMap["Key"].AsString(), (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString()));
}
if (maps.Count == 0)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
}
return true;
}
else
{
maps = null;
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", response["Message"]);
}
return false;
}
private bool SimianGetGenericEntries(string type, string key, out Dictionary<UUID, OSDMap> maps)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, type, key);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "Type", type },
{ "Key", key }
};
OSDMap response = CachedPostRequest(requestArgs);
if (response["Success"].AsBoolean() && response["Entries"] is OSDArray)
{
maps = new Dictionary<UUID, OSDMap>();
OSDArray entryArray = (OSDArray)response["Entries"];
foreach (OSDMap entryMap in entryArray)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
maps.Add(entryMap["OwnerID"].AsUUID(), (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString()));
}
if (maps.Count == 0)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
}
return true;
}
else
{
maps = null;
m_log.WarnFormat("[SIMIAN-GROUPS-CONNECTOR]: Error retrieving group info ({0})", response["Message"]);
}
return false;
}
private bool SimianRemoveGenericEntry(UUID ownerID, string type, string key)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "RemoveGeneric" },
{ "OwnerID", ownerID.ToString() },
{ "Type", type },
{ "Key", key }
};
OSDMap response = CachedPostRequest(requestArgs);
if (response["Success"].AsBoolean())
{
return true;
}
else
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error {0}, {1}, {2}, {3}", ownerID, type, key, response["Message"]);
return false;
}
}
#endregion
#region CheesyCache
OSDMap CachedPostRequest(NameValueCollection requestArgs)
{
// Immediately forward the request if the cache is disabled.
if (m_cacheTimeout == 0)
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: cache is disabled");
return WebUtil.PostToService(m_groupsServerURI, requestArgs);
}
// Check if this is an update or a request
if (requestArgs["RequestMethod"] == "RemoveGeneric"
|| requestArgs["RequestMethod"] == "AddGeneric")
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: clearing generics cache");
// Any and all updates cause the cache to clear
m_memoryCache.Clear();
// Send update to server, return the response without caching it
return WebUtil.PostToService(m_groupsServerURI, requestArgs);
}
// If we're not doing an update, we must be requesting data
// Create the cache key for the request and see if we have it cached
string CacheKey = WebUtil.BuildQueryString(requestArgs);
// This code uses a leader/follower pattern. On a cache miss, the request is added
// to a queue; the first thread to add it to the queue completes the request while
// follow on threads busy wait for the results, this situation seems to happen
// often when checking permissions
while (true)
{
OSDMap response = null;
bool firstRequest = false;
lock (m_memoryCache)
{
if (m_memoryCache.TryGetValue(CacheKey, out response))
return response;
if (! m_pendingRequests.ContainsKey(CacheKey))
{
m_pendingRequests.Add(CacheKey,true);
firstRequest = true;
}
}
if (firstRequest)
{
// if it wasn't in the cache, pass the request to the Simian Grid Services
try
{
response = WebUtil.PostToService(m_groupsServerURI, requestArgs);
}
catch (Exception)
{
m_log.ErrorFormat("[SIMIAN GROUPS CONNECTOR]: request failed {0}", CacheKey);
}
// and cache the response
lock (m_memoryCache)
{
m_memoryCache.AddOrUpdate(CacheKey, response, TimeSpan.FromSeconds(m_cacheTimeout));
m_pendingRequests.Remove(CacheKey);
}
return response;
}
Thread.Sleep(50); // waiting for a web request to complete, 50msecs is reasonable
}
// if (!m_memoryCache.TryGetValue(CacheKey, out response))
// {
// m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: query not in the cache");
// Util.PrintCallStack();
// // if it wasn't in the cache, pass the request to the Simian Grid Services
// response = WebUtil.PostToService(m_groupsServerURI, requestArgs);
// // and cache the response
// m_memoryCache.AddOrUpdate(CacheKey, response, TimeSpan.FromSeconds(m_cacheTimeout));
// }
// // return cached response
// return response;
}
#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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// Common.cs
//
//
// Helper routines for the rest of the TPL Dataflow implementation.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security;
using System.Collections;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks.Dataflow.Internal.Threading;
namespace System.Threading.Tasks.Dataflow.Internal
{
/// <summary>Internal helper utilities.</summary>
internal static class Common
{
/// <summary>
/// An invalid ID to assign for reordering purposes. This value is chosen to be the last of the 64-bit integers that
/// could ever be assigned as a reordering ID.
/// </summary>
internal const long INVALID_REORDERING_ID = -1;
/// <summary>A well-known message ID for code that will send exactly one message or
/// where the exact message ID is not important.</summary>
internal const int SINGLE_MESSAGE_ID = 1;
/// <summary>A perf optimization for caching a well-known message header instead of
/// constructing one every time it is needed.</summary>
internal static readonly DataflowMessageHeader SingleMessageHeader = new DataflowMessageHeader(SINGLE_MESSAGE_ID);
/// <summary>The cached completed Task{bool} with a result of true.</summary>
internal static readonly Task<bool> CompletedTaskWithTrueResult = CreateCachedBooleanTask(true);
/// <summary>The cached completed Task{bool} with a result of false.</summary>
internal static readonly Task<bool> CompletedTaskWithFalseResult = CreateCachedBooleanTask(false);
/// <summary>The cached completed TaskCompletionSource{VoidResult}.</summary>
internal static readonly TaskCompletionSource<VoidResult> CompletedVoidResultTaskCompletionSource = CreateCachedTaskCompletionSource<VoidResult>();
/// <summary>Asserts that a given synchronization object is either held or not held.</summary>
/// <param name="syncObj">The monitor to check.</param>
/// <param name="held">Whether we want to assert that it's currently held or not held.</param>
[Conditional("DEBUG")]
internal static void ContractAssertMonitorStatus(object syncObj, bool held)
{
Contract.Requires(syncObj != null, "The monitor object to check must be provided.");
Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed.");
}
/// <summary>Keeping alive processing tasks: maximum number of processed messages.</summary>
internal const int KEEP_ALIVE_NUMBER_OF_MESSAGES_THRESHOLD = 1;
/// <summary>Keeping alive processing tasks: do not attempt this many times.</summary>
internal const int KEEP_ALIVE_BAN_COUNT = 1000;
/// <summary>A predicate type for TryKeepAliveUntil.</summary>
/// <param name="stateIn">Input state for the predicate in order to avoid closure allocations.</param>
/// <param name="stateOut">Output state for the predicate in order to avoid closure allocations.</param>
/// <returns>The state of the predicate.</returns>
internal delegate bool KeepAlivePredicate<TStateIn, TStateOut>(TStateIn stateIn, out TStateOut stateOut);
/// <summary>Actively waits for a predicate to become true.</summary>
/// <param name="predicate">The predicate to become true.</param>
/// <param name="stateIn">Input state for the predicate in order to avoid closure allocations.</param>
/// <param name="stateOut">Output state for the predicate in order to avoid closure allocations.</param>
/// <returns>True if the predicate was evaluated and it returned true. False otherwise.</returns>
internal static bool TryKeepAliveUntil<TStateIn, TStateOut>(KeepAlivePredicate<TStateIn, TStateOut> predicate,
TStateIn stateIn, out TStateOut stateOut)
{
Contract.Requires(predicate != null, "Non-null predicate to execute is required.");
const int ITERATION_LIMIT = 16;
for (int c = ITERATION_LIMIT; c > 0; c--)
{
if (!Thread.Yield())
{
// There was no other thread waiting.
// We may spend some more cycles to evaluate the predicate.
if (predicate(stateIn, out stateOut)) return true;
}
}
stateOut = default(TStateOut);
return false;
}
/// <summary>Unwraps an instance T from object state that is a WeakReference to that instance.</summary>
/// <typeparam name="T">The type of the data to be unwrapped.</typeparam>
/// <param name="state">The weak reference.</param>
/// <returns>The T instance.</returns>
internal static T UnwrapWeakReference<T>(object state) where T : class
{
var wr = state as WeakReference<T>;
Debug.Assert(wr != null, "Expected a WeakReference<T> as the state argument");
T item;
return wr.TryGetTarget(out item) ? item : null;
}
/// <summary>Gets an ID for the dataflow block.</summary>
/// <param name="block">The dataflow block.</param>
/// <returns>An ID for the dataflow block.</returns>
internal static int GetBlockId(IDataflowBlock block)
{
Contract.Requires(block != null, "Block required to extract an Id.");
const int NOTASKID = 0; // tasks don't have 0 as ids
Task t = Common.GetPotentiallyNotSupportedCompletionTask(block);
return t != null ? t.Id : NOTASKID;
}
/// <summary>Gets the name for the specified block, suitable to be rendered in a debugger window.</summary>
/// <param name="block">The block for which a name is needed.</param>
/// <param name="options">
/// The options to use when rendering the name. If no options are provided, the block's name is used directly.
/// </param>
/// <returns>The name of the object.</returns>
/// <remarks>This is used from DebuggerDisplay attributes.</remarks>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
internal static string GetNameForDebugger(
IDataflowBlock block, DataflowBlockOptions options = null)
{
Contract.Requires(block != null, "Should only be used with valid objects being displayed in the debugger.");
Contract.Requires(options == null || options.NameFormat != null, "If options are provided, NameFormat must be valid.");
if (block == null) return string.Empty;
string blockName = block.GetType().Name;
if (options == null) return blockName;
// {0} == block name
// {1} == block id
int blockId = GetBlockId(block);
// Since NameFormat is public, formatting may throw if the user has set
// a string that contains a reference to an argument higher than {1}.
// In the case of an exception, show the exception message.
try
{
return string.Format(options.NameFormat, blockName, blockId);
}
catch (Exception exception)
{
return exception.Message;
}
}
/// <summary>
/// Gets whether the exception represents a cooperative cancellation acknowledgment.
/// </summary>
/// <param name="exception">The exception to check.</param>
/// <returns>true if this exception represents a cooperative cancellation acknowledgment; otherwise, false.</returns>
internal static bool IsCooperativeCancellation(Exception exception)
{
Contract.Requires(exception != null, "An exception to check for cancellation must be provided.");
return exception is OperationCanceledException;
// Note that the behavior of this method does not exactly match that of Parallel.*, PLINQ, and Task.Factory.StartNew,
// in that it's more liberal and treats any OCE as acknowledgment of cancellation; in contrast, the other
// libraries only treat OCEs as such if they contain the same token that was provided by the user
// and if that token has cancellation requested. Such logic could be achieved here with:
// var oce = exception as OperationCanceledException;
// return oce != null &&
// oce.CancellationToken == dataflowBlockOptions.CancellationToken &&
// oce.CancellationToken.IsCancellationRequested;
// However, that leads to a discrepancy with the async processing case of dataflow blocks,
// where tasks are returned to represent the message processing, potentially in the Canceled state,
// and we simply ignore such tasks. Further, for blocks like TransformBlock, it's useful to be able
// to cancel an individual operation which must return a TOutput value, simply by throwing an OperationCanceledException.
// In such cases, you wouldn't want cancellation tied to the token, because you would only be able to
// cancel an individual message processing if the whole block was canceled.
}
/// <summary>Registers a block for cancellation by completing when cancellation is requested.</summary>
/// <param name="cancellationToken">The block's cancellation token.</param>
/// <param name="completionTask">The task that will complete when the block is completely done processing.</param>
/// <param name="completeAction">An action that will decline permanently on the state passed to it.</param>
/// <param name="completeState">The block on which to decline permanently.</param>
internal static void WireCancellationToComplete(
CancellationToken cancellationToken, Task completionTask, Action<object> completeAction, object completeState)
{
Contract.Requires(completionTask != null, "A task to wire up for completion is needed.");
Contract.Requires(completeAction != null, "An action to invoke upon cancellation is required.");
// If a cancellation request has already occurred, just invoke the declining action synchronously.
// CancellationToken would do this anyway but we can short-circuit it further and avoid a bunch of unnecessary checks.
if (cancellationToken.IsCancellationRequested)
{
completeAction(completeState);
}
// Otherwise, if a cancellation request occurs, we want to prevent the block from accepting additional
// data, and we also want to dispose of that registration when we complete so that we don't
// leak into a long-living cancellation token.
else if (cancellationToken.CanBeCanceled)
{
CancellationTokenRegistration reg = cancellationToken.Register(completeAction, completeState);
completionTask.ContinueWith((completed, state) => ((CancellationTokenRegistration)state).Dispose(),
reg, cancellationToken, Common.GetContinuationOptions(), TaskScheduler.Default);
}
}
/// <summary>Initializes the stack trace and watson bucket of an inactive exception.</summary>
/// <param name="exception">The exception to initialize.</param>
/// <returns>The initialized exception.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static Exception InitializeStackTrace(Exception exception)
{
Contract.Requires(exception != null && exception.StackTrace == null,
"A valid but uninitialized exception should be provided.");
try { throw exception; }
catch { return exception; }
}
/// <summary>The name of the key in an Exception's Data collection used to store information on a dataflow message.</summary>
internal const string EXCEPTIONDATAKEY_DATAFLOWMESSAGEVALUE = "DataflowMessageValue"; // should not be localized
/// <summary>Stores details on a dataflow message into an Exception's Data collection.</summary>
/// <typeparam name="T">Specifies the type of data stored in the message.</typeparam>
/// <param name="exc">The Exception whose Data collection should store message information.</param>
/// <param name="messageValue">The message information to be stored.</param>
/// <param name="targetInnerExceptions">Whether to store the data into the exception's inner exception(s) in addition to the exception itself.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static void StoreDataflowMessageValueIntoExceptionData<T>(Exception exc, T messageValue, bool targetInnerExceptions = false)
{
Contract.Requires(exc != null, "The exception into which data should be stored must be provided.");
// Get the string value to store
string strValue = messageValue as string;
if (strValue == null && messageValue != null)
{
try
{
strValue = messageValue.ToString();
}
catch { /* It's ok to eat all exceptions here. If ToString throws, we'll just ignore it. */ }
}
if (strValue == null) return;
// Store the data into the exception itself
StoreStringIntoExceptionData(exc, Common.EXCEPTIONDATAKEY_DATAFLOWMESSAGEVALUE, strValue);
// If we also want to target inner exceptions...
if (targetInnerExceptions)
{
// If this is an aggregate, store into all inner exceptions.
var aggregate = exc as AggregateException;
if (aggregate != null)
{
foreach (Exception innerException in aggregate.InnerExceptions)
{
StoreStringIntoExceptionData(innerException, Common.EXCEPTIONDATAKEY_DATAFLOWMESSAGEVALUE, strValue);
}
}
// Otherwise, if there's an Exception.InnerException, store into that.
else if (exc.InnerException != null)
{
StoreStringIntoExceptionData(exc.InnerException, Common.EXCEPTIONDATAKEY_DATAFLOWMESSAGEVALUE, strValue);
}
}
}
/// <summary>Stores the specified string value into the specified key slot of the specified exception's data dictionary.</summary>
/// <param name="exception">The exception into which the key/value should be stored.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value to be serialized as a string and stored.</param>
/// <remarks>If the key is already present in the exception's data dictionary, the value is not overwritten.</remarks>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void StoreStringIntoExceptionData(Exception exception, string key, string value)
{
Contract.Requires(exception != null, "An exception is needed to store the data into.");
Contract.Requires(key != null, "A key into the exception's data collection is needed.");
Contract.Requires(value != null, "The value to store must be provided.");
try
{
IDictionary data = exception.Data;
if (data != null && !data.IsFixedSize && !data.IsReadOnly && data[key] == null)
{
data[key] = value;
}
}
catch
{
// It's ok to eat all exceptions here. This could throw if an Exception type
// has overridden Data to behave differently than we expect.
}
}
/// <summary>Throws an exception asynchronously on the thread pool.</summary>
/// <param name="error">The exception to throw.</param>
/// <remarks>
/// This function is used when an exception needs to be propagated from a thread
/// other than the current context. This could happen, for example, if the exception
/// should cause the standard CLR exception escalation behavior, but we're inside
/// of a task that will squirrel the exception away.
/// </remarks>
internal static void ThrowAsync(Exception error)
{
ExceptionDispatchInfo edi = ExceptionDispatchInfo.Capture(error);
ThreadPool.QueueUserWorkItem(state => { ((ExceptionDispatchInfo)state).Throw(); }, edi);
}
/// <summary>Adds the exception to the list, first initializing the list if the list is null.</summary>
/// <param name="list">The list to add the exception to, and initialize if null.</param>
/// <param name="exception">The exception to add or whose inner exception(s) should be added.</param>
/// <param name="unwrapInnerExceptions">Unwrap and add the inner exception(s) rather than the specified exception directly.</param>
/// <remarks>This method is not thread-safe, in that it manipulates <paramref name="list"/> without any synchronization.</remarks>
internal static void AddException(ref List<Exception> list, Exception exception, bool unwrapInnerExceptions = false)
{
Contract.Requires(exception != null, "An exception to add is required.");
Contract.Requires(!unwrapInnerExceptions || exception.InnerException != null,
"If unwrapping is requested, an inner exception is required.");
// Make sure the list of exceptions is initialized (lazily).
if (list == null) list = new List<Exception>();
if (unwrapInnerExceptions)
{
AggregateException aggregate = exception as AggregateException;
if (aggregate != null)
{
list.AddRange(aggregate.InnerExceptions);
}
else
{
list.Add(exception.InnerException);
}
}
else list.Add(exception);
}
/// <summary>Creates a task we can cache for the desired Boolean result.</summary>
/// <param name="value">The value of the Boolean.</param>
/// <returns>A task that may be cached.</returns>
private static Task<Boolean> CreateCachedBooleanTask(bool value)
{
// AsyncTaskMethodBuilder<Boolean> caches tasks that are non-disposable.
// By using these same tasks, we're a bit more robust against disposals,
// in that such a disposed task's ((IAsyncResult)task).AsyncWaitHandle
// is still valid.
var atmb = System.Runtime.CompilerServices.AsyncTaskMethodBuilder<Boolean>.Create();
atmb.SetResult(value);
return atmb.Task; // must be accessed after SetResult to get the cached task
}
/// <summary>Creates a TaskCompletionSource{T} completed with a value of default(T) that we can cache.</summary>
/// <returns>Completed TaskCompletionSource{T} that may be cached.</returns>
private static TaskCompletionSource<T> CreateCachedTaskCompletionSource<T>()
{
var tcs = new TaskCompletionSource<T>();
tcs.SetResult(default(T));
return tcs;
}
/// <summary>Creates a task faulted with the specified exception.</summary>
/// <typeparam name="TResult">Specifies the type of the result for this task.</typeparam>
/// <param name="exception">The exception with which to complete the task.</param>
/// <returns>The faulted task.</returns>
internal static Task<TResult> CreateTaskFromException<TResult>(Exception exception)
{
var atmb = System.Runtime.CompilerServices.AsyncTaskMethodBuilder<TResult>.Create();
atmb.SetException(exception);
return atmb.Task;
}
/// <summary>Creates a task canceled with the specified cancellation token.</summary>
/// <typeparam name="TResult">Specifies the type of the result for this task.</typeparam>
/// <returns>The canceled task.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
internal static Task<TResult> CreateTaskFromCancellation<TResult>(CancellationToken cancellationToken)
{
Contract.Requires(cancellationToken.IsCancellationRequested,
"The task will only be immediately canceled if the token has cancellation requested already.");
var t = new Task<TResult>(CachedGenericDelegates<TResult>.DefaultTResultFunc, cancellationToken);
Debug.Assert(t.IsCanceled, "Task's constructor should cancel the task synchronously in the ctor.");
return t;
}
/// <summary>Gets the completion task of a block, and protects against common cases of the completion task not being implemented or supported.</summary>
/// <param name="block">The block.</param>
/// <returns>The completion task, or null if the block's completion task is not implemented or supported.</returns>
internal static Task GetPotentiallyNotSupportedCompletionTask(IDataflowBlock block)
{
Contract.Requires(block != null, "We need a block from which to retrieve a cancellation task.");
try
{
return block.Completion;
}
catch (NotImplementedException) { }
catch (NotSupportedException) { }
return null;
}
/// <summary>
/// Creates an IDisposable that, when disposed, will acquire the outgoing lock while removing
/// the target block from the target registry.
/// </summary>
/// <typeparam name="TOutput">Specifies the type of data in the block.</typeparam>
/// <param name="outgoingLock">The outgoing lock used to protect the target registry.</param>
/// <param name="targetRegistry">The target registry from which the target should be removed.</param>
/// <param name="targetBlock">The target to remove from the registry.</param>
/// <returns>An IDisposable that will unregister the target block from the registry while holding the outgoing lock.</returns>
internal static IDisposable CreateUnlinker<TOutput>(object outgoingLock, TargetRegistry<TOutput> targetRegistry, ITargetBlock<TOutput> targetBlock)
{
Contract.Requires(outgoingLock != null, "Monitor object needed to protect the operation.");
Contract.Requires(targetRegistry != null, "Registry from which to remove is required.");
Contract.Requires(targetBlock != null, "Target block to unlink is required.");
return Disposables.Create(CachedGenericDelegates<TOutput>.CreateUnlinkerShimAction,
outgoingLock, targetRegistry, targetBlock);
}
/// <summary>An infinite TimeSpan.</summary>
internal static readonly TimeSpan InfiniteTimeSpan = Timeout.InfiniteTimeSpan;
/// <summary>Validates that a timeout either is -1 or is non-negative and within the range of an Int32.</summary>
/// <param name="timeout">The timeout to validate.</param>
/// <returns>true if the timeout is valid; otherwise, false.</returns>
internal static bool IsValidTimeout(TimeSpan timeout)
{
long millisecondsTimeout = (long)timeout.TotalMilliseconds;
return millisecondsTimeout >= Timeout.Infinite && millisecondsTimeout <= Int32.MaxValue;
}
/// <summary>Gets the options to use for continuation tasks.</summary>
/// <param name="toInclude">Any options to include in the result.</param>
/// <returns>The options to use.</returns>
internal static TaskContinuationOptions GetContinuationOptions(TaskContinuationOptions toInclude = TaskContinuationOptions.None)
{
return toInclude | TaskContinuationOptions.DenyChildAttach;
}
/// <summary>Gets the options to use for tasks.</summary>
/// <param name="isReplacementReplica">If this task is being created to replace another.</param>
/// <remarks>
/// These options should be used for all tasks that have the potential to run user code or
/// that are repeatedly spawned and thus need a modicum of fair treatment.
/// </remarks>
/// <returns>The options to use.</returns>
internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false)
{
TaskCreationOptions options = TaskCreationOptions.DenyChildAttach;
if (isReplacementReplica) options |= TaskCreationOptions.PreferFairness;
return options;
}
/// <summary>Starts an already constructed task with handling and observing exceptions that may come from the scheduling process.</summary>
/// <param name="task">Task to be started.</param>
/// <param name="scheduler">TaskScheduler to schedule the task on.</param>
/// <returns>null on success, an exception reference on scheduling error. In the latter case, the task reference is nulled out.</returns>
internal static Exception StartTaskSafe(Task task, TaskScheduler scheduler)
{
Contract.Requires(task != null, "Task to start is required.");
Contract.Requires(scheduler != null, "Scheduler on which to start the task is required.");
if (scheduler == TaskScheduler.Default)
{
task.Start(scheduler);
return null; // We don't need to worry about scheduler exceptions from the default scheduler.
}
// Slow path with try/catch separated out so that StartTaskSafe may be inlined in the common case.
else return StartTaskSafeCore(task, scheduler);
}
/// <summary>Starts an already constructed task with handling and observing exceptions that may come from the scheduling process.</summary>
/// <param name="task">Task to be started.</param>
/// <param name="scheduler">TaskScheduler to schedule the task on.</param>
/// <returns>null on success, an exception reference on scheduling error. In the latter case, the task reference is nulled out.</returns>
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static Exception StartTaskSafeCore(Task task, TaskScheduler scheduler)
{
Contract.Requires(task != null, "Task to start is needed.");
Contract.Requires(scheduler != null, "Scheduler on which to start the task is required.");
Exception schedulingException = null;
try
{
task.Start(scheduler);
}
catch (Exception caughtException)
{
// Verify TPL has faulted the task
Debug.Assert(task.IsFaulted, "The task should have been faulted if it failed to start.");
// Observe the task's exception
AggregateException ignoredTaskException = task.Exception;
schedulingException = caughtException;
}
return schedulingException;
}
/// <summary>Pops and explicitly releases postponed messages after the block is done with processing.</summary>
/// <remarks>No locks should be held at this time. Unfortunately we cannot assert that.</remarks>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static void ReleaseAllPostponedMessages<T>(ITargetBlock<T> target,
QueuedMap<ISourceBlock<T>, DataflowMessageHeader> postponedMessages,
ref List<Exception> exceptions)
{
Contract.Requires(target != null, "There must be a subject target.");
Contract.Requires(postponedMessages != null, "The stacked map of postponed messages must exist.");
// Note that we don't synchronize on lockObject for postponedMessages here,
// because no one should be adding to it at this time. We do a bit of
// checking just for sanity's sake.
int initialCount = postponedMessages.Count;
int processedCount = 0;
KeyValuePair<ISourceBlock<T>, DataflowMessageHeader> sourceAndMessage;
while (postponedMessages.TryPop(out sourceAndMessage))
{
// Loop through all postponed messages declining each messages.
// The only way we have to do this is by reserving and then immediately releasing each message.
// This is important for sources like SendAsyncSource, which keep state around until
// they get a response to a postponed message.
try
{
Debug.Assert(sourceAndMessage.Key != null, "Postponed messages must have an associated source.");
if (sourceAndMessage.Key.ReserveMessage(sourceAndMessage.Value, target))
{
sourceAndMessage.Key.ReleaseReservation(sourceAndMessage.Value, target);
}
}
catch (Exception exc)
{
Common.AddException(ref exceptions, exc);
}
processedCount++;
}
Debug.Assert(processedCount == initialCount,
"We should have processed the exact number of elements that were initially there.");
}
/// <summary>Cache ThrowAsync to avoid allocations when it is passed into PropagateCompletionXxx.</summary>
internal static readonly Action<Exception> AsyncExceptionHandler = ThrowAsync;
/// <summary>
/// Propagates completion of sourceCompletionTask to target synchronously.
/// </summary>
/// <param name="sourceCompletionTask">The task whose completion is to be propagated. It must be completed.</param>
/// <param name="target">The block where completion is propagated.</param>
/// <param name="exceptionHandler">Handler for exceptions from the target. May be null which would propagate the exception to the caller.</param>
internal static void PropagateCompletion(Task sourceCompletionTask, IDataflowBlock target, Action<Exception> exceptionHandler)
{
Contract.Requires(sourceCompletionTask != null, "sourceCompletionTask may not be null.");
Contract.Requires(target != null, "The target where completion is to be propagated may not be null.");
Debug.Assert(sourceCompletionTask.IsCompleted, "sourceCompletionTask must be completed in order to propagate its completion.");
AggregateException exception = sourceCompletionTask.IsFaulted ? sourceCompletionTask.Exception : null;
try
{
if (exception != null) target.Fault(exception);
else target.Complete();
}
catch (Exception exc)
{
if (exceptionHandler != null) exceptionHandler(exc);
else throw;
}
}
/// <summary>
/// Creates a continuation off sourceCompletionTask to complete target. See PropagateCompletion.
/// </summary>
private static void PropagateCompletionAsContinuation(Task sourceCompletionTask, IDataflowBlock target)
{
Contract.Requires(sourceCompletionTask != null, "sourceCompletionTask may not be null.");
Contract.Requires(target != null, "The target where completion is to be propagated may not be null.");
sourceCompletionTask.ContinueWith((task, state) => Common.PropagateCompletion(task, (IDataflowBlock)state, AsyncExceptionHandler),
target, CancellationToken.None, Common.GetContinuationOptions(), TaskScheduler.Default);
}
/// <summary>
/// Propagates completion of sourceCompletionTask to target based on sourceCompletionTask's current state. See PropagateCompletion.
/// </summary>
internal static void PropagateCompletionOnceCompleted(Task sourceCompletionTask, IDataflowBlock target)
{
Contract.Requires(sourceCompletionTask != null, "sourceCompletionTask may not be null.");
Contract.Requires(target != null, "The target where completion is to be propagated may not be null.");
// If sourceCompletionTask is completed, propagate completion synchronously.
// Otherwise hook up a continuation.
if (sourceCompletionTask.IsCompleted) PropagateCompletion(sourceCompletionTask, target, exceptionHandler: null);
else PropagateCompletionAsContinuation(sourceCompletionTask, target);
}
/// <summary>Static class used to cache generic delegates the C# compiler doesn't cache by default.</summary>
/// <remarks>Without this, we end up allocating the generic delegate each time the operation is used.</remarks>
static class CachedGenericDelegates<T>
{
/// <summary>A function that returns the default value of T.</summary>
internal readonly static Func<T> DefaultTResultFunc = () => default(T);
/// <summary>
/// A function to use as the body of ActionOnDispose in CreateUnlinkerShim.
/// Passed a tuple of the sync obj, the target registry, and the target block as the state parameter.
/// </summary>
internal readonly static Action<object, TargetRegistry<T>, ITargetBlock<T>> CreateUnlinkerShimAction =
(syncObj, registry, target) =>
{
lock (syncObj) registry.Remove(target);
};
}
}
/// <summary>State used only when bounding.</summary>
[DebuggerDisplay("BoundedCapacity={BoundedCapacity}}")]
internal class BoundingState
{
/// <summary>The maximum number of messages allowed to be buffered.</summary>
internal readonly int BoundedCapacity;
/// <summary>The number of messages currently stored.</summary>
/// <remarks>
/// This value may temporarily be higher than the actual number stored.
/// That's ok, we just can't accept any new messages if CurrentCount >= BoundedCapacity.
/// Worst case is that we may temporarily have fewer items in the block than our maximum allows,
/// but we'll never have more.
/// </remarks>
internal int CurrentCount;
/// <summary>Initializes the BoundingState.</summary>
/// <param name="boundedCapacity">The positive bounded capacity.</param>
internal BoundingState(int boundedCapacity)
{
Contract.Requires(boundedCapacity > 0, "Bounded is only supported with positive values.");
BoundedCapacity = boundedCapacity;
}
/// <summary>Gets whether there's room available to add another message.</summary>
internal bool CountIsLessThanBound { get { return CurrentCount < BoundedCapacity; } }
}
/// <summary>Stated used only when bounding and when postponed messages are stored.</summary>
/// <typeparam name="TInput">Specifies the type of input messages.</typeparam>
[DebuggerDisplay("BoundedCapacity={BoundedCapacity}, PostponedMessages={PostponedMessagesCountForDebugger}")]
internal class BoundingStateWithPostponed<TInput> : BoundingState
{
/// <summary>Queue of postponed messages.</summary>
internal readonly QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader> PostponedMessages =
new QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader>();
/// <summary>
/// The number of transfers from the postponement queue to the input queue currently being processed.
/// </summary>
/// <remarks>
/// Blocks that use TargetCore need to transfer messages from the postponed queue to the input messages
/// queue. While doing that, new incoming messages may arrive, and if they view the postponed queue
/// as being empty (after the block has removed the last postponed message and is consuming it, before
/// storing it into the input queue), they might go directly into the input queue... that will then mess
/// up the ordering between those postponed messages and the newly incoming messages. To address that,
/// OutstandingTransfers is used to track the number of transfers currently in progress. Incoming
/// messages must be postponed not only if there are already any postponed messages, but also if
/// there are any transfers in progress (i.e. this value is > 0). It's an integer because the DOP could
/// be greater than 1, and thus we need to ref count multiple transfers that might be in progress.
/// </remarks>
internal int OutstandingTransfers;
/// <summary>Initializes the BoundingState.</summary>
/// <param name="boundedCapacity">The positive bounded capacity.</param>
internal BoundingStateWithPostponed(int boundedCapacity) : base(boundedCapacity)
{
}
/// <summary>Gets the number of postponed messages for the debugger.</summary>
private int PostponedMessagesCountForDebugger { get { return PostponedMessages.Count; } }
}
/// <summary>Stated used only when bounding and when postponed messages and a task are stored.</summary>
/// <typeparam name="TInput">Specifies the type of input messages.</typeparam>
internal class BoundingStateWithPostponedAndTask<TInput> : BoundingStateWithPostponed<TInput>
{
/// <summary>The task used to process messages.</summary>
internal Task TaskForInputProcessing;
/// <summary>Initializes the BoundingState.</summary>
/// <param name="boundedCapacity">The positive bounded capacity.</param>
internal BoundingStateWithPostponedAndTask(int boundedCapacity) : base(boundedCapacity)
{
}
}
/// <summary>
/// Type used with TaskCompletionSource(Of TResult) as the TResult
/// to ensure that the resulting task can't be upcast to something
/// that in the future could lead to compat problems.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
[DebuggerNonUserCode]
internal struct VoidResult { }
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
//
// Copyright (C) 2008 Novell (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.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
// The NUnit version of this file introduces conditional compilation for
// building under .NET Standard
//
// 11/5/2015 -
// Change namespace to avoid conflict with user code use of mono.options
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Compatibility;
// Missing XML Docs
#pragma warning disable 1591
#if !NETSTANDARD1_4
using System.Security.Permissions;
using System.Runtime.Serialization;
#endif
namespace NUnit.Options
{
public class OptionValueCollection : IList, IList<string> {
readonly List<string> values = new List<string>();
readonly OptionContext c;
internal OptionValueCollection (OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
#endregion
#region ICollection<T>
public void Add (string item) {values.Add (item);}
public void Clear () {values.Clear ();}
public bool Contains (string item) {return values.Contains (item);}
public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
public bool Remove (string item) {return values.Remove (item);}
public int Count {get {return values.Count;}}
public bool IsReadOnly {get {return false;}}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IList
int IList.Add (object value) {return (values as IList).Add (value);}
bool IList.Contains (object value) {return (values as IList).Contains (value);}
int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
void IList.Remove (object value) {(values as IList).Remove (value);}
void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
bool IList.IsFixedSize {get {return false;}}
object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
#endregion
#region IList<T>
public int IndexOf (string item) {return values.IndexOf (item);}
public void Insert (int index, string item) {values.Insert (index, item);}
public void RemoveAt (int index) {values.RemoveAt (index);}
private void AssertValid (int index)
{
if (c.Option == null)
throw new InvalidOperationException ("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException (nameof(index));
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException (string.Format (
c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this [int index] {
get {
AssertValid (index);
return index >= values.Count ? null : values [index];
}
set {
values [index] = value;
}
}
#endregion
public List<string> ToList ()
{
return new List<string> (values);
}
public string[] ToArray ()
{
return values.ToArray ();
}
public override string ToString ()
{
return string.Join (", ", values.ToArray ());
}
}
public class OptionContext {
private Option option;
private string name;
private int index;
private readonly OptionSet set;
private readonly OptionValueCollection c;
public OptionContext (OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection (this);
}
public Option Option {
get {return option;}
set {option = value;}
}
public string OptionName {
get {return name;}
set {name = value;}
}
public int OptionIndex {
get {return index;}
set {index = value;}
}
public OptionSet OptionSet {
get {return set;}
}
public OptionValueCollection OptionValues {
get {return c;}
}
}
public enum OptionValueType {
None,
Optional,
Required,
}
public abstract class Option {
readonly string prototype;
readonly string description;
readonly string[] names;
readonly OptionValueType type;
readonly int count;
string[] separators;
protected Option (string prototype, string description)
: this (prototype, description, 1)
{
}
protected Option (string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException (nameof(prototype));
if (prototype.Length == 0)
throw new ArgumentException ("Cannot be the empty string.", nameof(prototype));
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException (nameof(maxValueCount));
this.prototype = prototype;
this.names = prototype.Split ('|');
this.description = description;
this.count = maxValueCount;
this.type = ParsePrototype ();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException (
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
nameof(maxValueCount));
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException (
string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
nameof(maxValueCount));
if (Array.IndexOf (names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException (
"The default option handler '<>' cannot require values.",
nameof(prototype));
}
public string Prototype {get {return prototype;}}
public string Description {get {return description;}}
public OptionValueType OptionValueType {get {return type;}}
public int MaxValueCount {get {return count;}}
public string[] GetNames ()
{
return (string[]) names.Clone ();
}
public string[] GetValueSeparators ()
{
if (separators == null)
return new string [0];
return (string[]) separators.Clone ();
}
protected static T Parse<T> (string value, OptionContext c)
{
Type tt = typeof (T);
bool nullable = tt.GetTypeInfo().IsValueType && tt.GetTypeInfo().IsGenericType &&
!tt.GetTypeInfo().IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition () == typeof (Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
#if !NETSTANDARD1_4
TypeConverter conv = TypeDescriptor.GetConverter (targetType);
#endif
T t = default (T);
try {
if (value != null)
#if NETSTANDARD1_4
t = (T)Convert.ChangeType(value, tt, CultureInfo.InvariantCulture);
#else
t = (T) conv.ConvertFromString (value);
#endif
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names {get {return names;}}
internal string[] ValueSeparators {get {return separators;}}
static readonly char[] NameTerminator = new char[]{'=', ':'};
private OptionValueType ParsePrototype ()
{
char type = '\0';
List<string> seps = new List<string> ();
for (int i = 0; i < names.Length; ++i) {
string name = names [i];
if (name.Length == 0)
throw new ArgumentException ("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny (NameTerminator);
if (end == -1)
continue;
names [i] = name.Substring (0, end);
if (type == '\0' || type == name [end])
type = name [end];
else
throw new ArgumentException (
string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
"prototype");
AddSeparators (name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException (
string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1) {
if (seps.Count == 0)
this.separators = new string[]{":", "="};
else if (seps.Count == 1 && seps [0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray ();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators (string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end+1; i < name.Length; ++i) {
switch (name [i]) {
case '{':
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i+1;
break;
case '}':
if (start == -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add (name.Substring (start, i-start));
start = -1;
break;
default:
if (start == -1)
seps.Add (name [i].ToString ());
break;
}
}
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke (OptionContext c)
{
OnParseComplete (c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear ();
}
protected abstract void OnParseComplete (OptionContext c);
public override string ToString ()
{
return Prototype;
}
}
[Serializable]
public class OptionException : Exception
{
private readonly string option;
public OptionException ()
{
}
public OptionException (string message, string optionName)
: base (message)
{
this.option = optionName;
}
public OptionException (string message, string optionName, Exception innerException)
: base (message, innerException)
{
this.option = optionName;
}
#if SERIALIZATION
protected OptionException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
this.option = info.GetString ("OptionName");
}
#endif
public string OptionName {
get {return this.option;}
}
#if SERIALIZATION
[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
base.GetObjectData (info, context);
info.AddValue ("OptionName", option);
}
#endif
}
public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
string Localizer(string msg)
{
return msg;
}
public string MessageLocalizer(string msg)
{
return msg;
}
protected override string GetKeyForItem (Option item)
{
if (item == null)
throw new ArgumentNullException (nameof(item));
if (item.Names != null && item.Names.Length > 0)
return item.Names [0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException ("Option has no names!");
}
[Obsolete ("Use KeyedCollection.this[string]")]
protected Option GetOptionForName (string option)
{
if (option == null)
throw new ArgumentNullException (nameof(option));
try {
return base [option];
}
catch (KeyNotFoundException) {
return null;
}
}
protected override void InsertItem (int index, Option item)
{
base.InsertItem (index, item);
AddImpl (item);
}
protected override void RemoveItem (int index)
{
base.RemoveItem (index);
Option p = Items [index];
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i) {
Dictionary.Remove (p.Names [i]);
}
}
protected override void SetItem (int index, Option item)
{
base.SetItem (index, item);
RemoveItem (index);
AddImpl (item);
}
private void AddImpl (Option option)
{
if (option == null)
throw new ArgumentNullException (nameof(option));
List<string> added = new List<string> (option.Names.Length);
try {
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i) {
Dictionary.Add (option.Names [i], option);
added.Add (option.Names [i]);
}
}
catch (Exception) {
foreach (string name in added)
Dictionary.Remove (name);
throw;
}
}
public new OptionSet Add (Option option)
{
base.Add (option);
return this;
}
sealed class ActionOption : Option {
readonly Action<OptionValueCollection> action;
public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
: base (prototype, description, count)
{
if (action == null)
throw new ArgumentNullException (nameof(action));
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (c.OptionValues);
}
}
public OptionSet Add (string prototype, Action<string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException (nameof(action));
Option p = new ActionOption (prototype, description, 1,
delegate (OptionValueCollection v) { action (v [0]); });
base.Add (p);
return this;
}
public OptionSet Add (string prototype, OptionAction<string, string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException (nameof(action));
Option p = new ActionOption (prototype, description, 2,
delegate (OptionValueCollection v) {action (v [0], v [1]);});
base.Add (p);
return this;
}
sealed class ActionOption<T> : Option {
readonly Action<T> action;
public ActionOption (string prototype, string description, Action<T> action)
: base (prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException (nameof(action));
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (Parse<T> (c.OptionValues [0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option {
readonly OptionAction<TKey, TValue> action;
public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
: base (prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException (nameof(action));
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<TKey> (c.OptionValues [0], c),
Parse<TValue> (c.OptionValues [1], c));
}
}
public OptionSet Add<T> (string prototype, Action<T> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<T> (string prototype, string description, Action<T> action)
{
return Add (new ActionOption<T> (prototype, description, action));
}
public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add (new ActionOption<TKey, TValue> (prototype, description, action));
}
protected virtual OptionContext CreateOptionContext ()
{
return new OptionContext (this);
}
public List<string> Parse (IEnumerable<string> arguments)
{
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string> ();
Option def = Contains ("<>") ? this ["<>"] : null;
foreach (string argument in arguments) {
++c.OptionIndex;
if (argument == "--") {
process = false;
continue;
}
if (!process) {
Unprocessed (unprocessed, def, c, argument);
continue;
}
if (!Parse (argument, c))
Unprocessed (unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke (c);
return unprocessed;
}
private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null) {
extra.Add (argument);
return false;
}
c.OptionValues.Add (argument);
c.Option = def;
c.Option.Invoke (c);
return false;
}
private readonly static Regex ValueOption = new Regex(
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException (nameof(argument));
flag = name = sep = value = null;
Match m = ValueOption.Match (argument);
if (!m.Success) {
return false;
}
flag = m.Groups ["flag"].Value;
name = m.Groups ["name"].Value;
if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
sep = m.Groups ["sep"].Value;
value = m.Groups ["value"].Value;
}
return true;
}
protected virtual bool Parse (string argument, OptionContext c)
{
if (c.Option != null) {
ParseValue (argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts (argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains (n)) {
p = this [n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType) {
case OptionValueType.None:
c.OptionValues.Add (n);
c.Option.Invoke (c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue (v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool (argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue (f, string.Concat (n + s + v), c))
return true;
return false;
}
private void ParseValue (string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split (c.Option.ValueSeparators, StringSplitOptions.None)
: new string[]{option}) {
c.OptionValues.Add (o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke (c);
else if (c.OptionValues.Count > c.Option.MaxValueCount) {
throw new OptionException (Localizer (string.Format (
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool (string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
Contains ((rn = n.Substring (0, n.Length-1)))) {
p = this [rn];
string v = n [n.Length-1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add (v);
p.Invoke (c);
return true;
}
return false;
}
private bool ParseBundledValue (string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i) {
Option p;
string opt = f + n [i].ToString ();
string rn = n [i].ToString ();
if (!Contains (rn)) {
if (i == 0)
return false;
throw new OptionException (string.Format (Localizer (
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this [rn];
switch (p.OptionValueType) {
case OptionValueType.None:
Invoke (c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required: {
string v = n.Substring (i+1);
c.Option = p;
c.OptionName = opt;
ParseValue (v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke (OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add (value);
option.Invoke (c);
}
private const int OptionWidth = 29;
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
bool indent = false;
string prefix = new string (' ', OptionWidth+2);
foreach (string line in GetLines (Localizer (GetDescription (p.Description)))) {
if (indent)
o.Write (prefix);
o.WriteLine (line);
indent = true;
}
}
}
bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex (names, 0);
if (i == names.Length)
return false;
if (names [i].Length == 1) {
Write (o, ref written, " -");
Write (o, ref written, names [0]);
}
else {
Write (o, ref written, " --");
Write (o, ref written, names [0]);
}
for ( i = GetNextOptionIndex (names, i+1);
i < names.Length; i = GetNextOptionIndex (names, i+1)) {
Write (o, ref written, ", ");
Write (o, ref written, names [i].Length == 1 ? "-" : "--");
Write (o, ref written, names [i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required) {
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, Localizer ("["));
}
Write (o, ref written, Localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators [0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c) {
Write (o, ref written, Localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, Localizer ("]"));
}
}
return true;
}
static int GetNextOptionIndex (string[] names, int i)
{
while (i < names.Length && names [i] == "<>") {
++i;
}
return i;
}
static void Write (TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write (s);
}
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription (string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder (description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i) {
switch (description [i]) {
case '{':
if (i == start) {
sb.Append ('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0) {
if ((i+1) == description.Length || description [i+1] != '}')
throw new InvalidOperationException ("Invalid option description: " + description);
++i;
sb.Append ("}");
}
else {
sb.Append (description.Substring (start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append (description [i]);
break;
}
}
return sb.ToString ();
}
private static IEnumerable<string> GetLines (string description)
{
if (string.IsNullOrEmpty (description)) {
yield return string.Empty;
yield break;
}
int length = 80 - OptionWidth - 1;
int start = 0, end;
do {
end = GetLineEnd (start, length, description);
char c = description [end-1];
if (char.IsWhiteSpace (c))
--end;
bool writeContinuation = end != description.Length && !IsEolChar (c);
string line = description.Substring (start, end - start) +
(writeContinuation ? "-" : "");
yield return line;
start = end;
if (char.IsWhiteSpace (c))
++start;
length = 80 - OptionWidth - 2 - 1;
} while (end < description.Length);
}
private static bool IsEolChar (char c)
{
return !char.IsLetterOrDigit (c);
}
private static int GetLineEnd (int start, int length, string description)
{
int end = System.Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start+1; i < end; ++i) {
if (description [i] == '\n')
return i+1;
if (IsEolChar (description [i]))
sep = i+1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SchemaNames.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Schema {
using System.Collections;
using System.Diagnostics;
internal sealed class SchemaNames {
XmlNameTable nameTable;
public XmlNameTable NameTable {
get { return nameTable; }
}
public string NsDataType;
public string NsDataTypeAlias;
public string NsDataTypeOld;
public string NsXml;
public string NsXmlNs;
public string NsXdr;
public string NsXdrAlias;
public string NsXs;
public string NsXsi;
public string XsiType;
public string XsiNil;
public string XsiSchemaLocation;
public string XsiNoNamespaceSchemaLocation;
public string XsdSchema;
public string XdrSchema;
public XmlQualifiedName QnPCData;
public XmlQualifiedName QnXml;
public XmlQualifiedName QnXmlNs;
public XmlQualifiedName QnDtDt;
public XmlQualifiedName QnXmlLang;
public XmlQualifiedName QnName;
public XmlQualifiedName QnType;
public XmlQualifiedName QnMaxOccurs;
public XmlQualifiedName QnMinOccurs;
public XmlQualifiedName QnInfinite;
public XmlQualifiedName QnModel;
public XmlQualifiedName QnOpen;
public XmlQualifiedName QnClosed;
public XmlQualifiedName QnContent;
public XmlQualifiedName QnMixed;
public XmlQualifiedName QnEmpty;
public XmlQualifiedName QnEltOnly;
public XmlQualifiedName QnTextOnly;
public XmlQualifiedName QnOrder;
public XmlQualifiedName QnSeq;
public XmlQualifiedName QnOne;
public XmlQualifiedName QnMany;
public XmlQualifiedName QnRequired;
public XmlQualifiedName QnYes;
public XmlQualifiedName QnNo;
public XmlQualifiedName QnString;
public XmlQualifiedName QnID;
public XmlQualifiedName QnIDRef;
public XmlQualifiedName QnIDRefs;
public XmlQualifiedName QnEntity;
public XmlQualifiedName QnEntities;
public XmlQualifiedName QnNmToken;
public XmlQualifiedName QnNmTokens;
public XmlQualifiedName QnEnumeration;
public XmlQualifiedName QnDefault;
public XmlQualifiedName QnXdrSchema;
public XmlQualifiedName QnXdrElementType;
public XmlQualifiedName QnXdrElement;
public XmlQualifiedName QnXdrGroup;
public XmlQualifiedName QnXdrAttributeType;
public XmlQualifiedName QnXdrAttribute;
public XmlQualifiedName QnXdrDataType;
public XmlQualifiedName QnXdrDescription;
public XmlQualifiedName QnXdrExtends;
public XmlQualifiedName QnXdrAliasSchema;
public XmlQualifiedName QnDtType;
public XmlQualifiedName QnDtValues;
public XmlQualifiedName QnDtMaxLength;
public XmlQualifiedName QnDtMinLength;
public XmlQualifiedName QnDtMax;
public XmlQualifiedName QnDtMin;
public XmlQualifiedName QnDtMinExclusive;
public XmlQualifiedName QnDtMaxExclusive;
// For XSD Schema
public XmlQualifiedName QnTargetNamespace;
public XmlQualifiedName QnVersion;
public XmlQualifiedName QnFinalDefault;
public XmlQualifiedName QnBlockDefault;
public XmlQualifiedName QnFixed;
public XmlQualifiedName QnAbstract;
public XmlQualifiedName QnBlock;
public XmlQualifiedName QnSubstitutionGroup;
public XmlQualifiedName QnFinal;
public XmlQualifiedName QnNillable;
public XmlQualifiedName QnRef;
public XmlQualifiedName QnBase;
public XmlQualifiedName QnDerivedBy;
public XmlQualifiedName QnNamespace;
public XmlQualifiedName QnProcessContents;
public XmlQualifiedName QnRefer;
public XmlQualifiedName QnPublic;
public XmlQualifiedName QnSystem;
public XmlQualifiedName QnSchemaLocation;
public XmlQualifiedName QnValue;
public XmlQualifiedName QnUse;
public XmlQualifiedName QnForm;
public XmlQualifiedName QnElementFormDefault;
public XmlQualifiedName QnAttributeFormDefault;
public XmlQualifiedName QnItemType;
public XmlQualifiedName QnMemberTypes;
public XmlQualifiedName QnXPath;
public XmlQualifiedName QnXsdSchema;
public XmlQualifiedName QnXsdAnnotation;
public XmlQualifiedName QnXsdInclude;
public XmlQualifiedName QnXsdImport;
public XmlQualifiedName QnXsdElement;
public XmlQualifiedName QnXsdAttribute;
public XmlQualifiedName QnXsdAttributeGroup;
public XmlQualifiedName QnXsdAnyAttribute;
public XmlQualifiedName QnXsdGroup;
public XmlQualifiedName QnXsdAll;
public XmlQualifiedName QnXsdChoice;
public XmlQualifiedName QnXsdSequence ;
public XmlQualifiedName QnXsdAny;
public XmlQualifiedName QnXsdNotation;
public XmlQualifiedName QnXsdSimpleType;
public XmlQualifiedName QnXsdComplexType;
public XmlQualifiedName QnXsdUnique;
public XmlQualifiedName QnXsdKey;
public XmlQualifiedName QnXsdKeyRef;
public XmlQualifiedName QnXsdSelector;
public XmlQualifiedName QnXsdField;
public XmlQualifiedName QnXsdMinExclusive;
public XmlQualifiedName QnXsdMinInclusive;
public XmlQualifiedName QnXsdMaxInclusive;
public XmlQualifiedName QnXsdMaxExclusive;
public XmlQualifiedName QnXsdTotalDigits;
public XmlQualifiedName QnXsdFractionDigits;
public XmlQualifiedName QnXsdLength;
public XmlQualifiedName QnXsdMinLength;
public XmlQualifiedName QnXsdMaxLength;
public XmlQualifiedName QnXsdEnumeration;
public XmlQualifiedName QnXsdPattern;
public XmlQualifiedName QnXsdDocumentation;
public XmlQualifiedName QnXsdAppinfo;
public XmlQualifiedName QnSource;
public XmlQualifiedName QnXsdComplexContent;
public XmlQualifiedName QnXsdSimpleContent;
public XmlQualifiedName QnXsdRestriction;
public XmlQualifiedName QnXsdExtension;
public XmlQualifiedName QnXsdUnion;
public XmlQualifiedName QnXsdList;
public XmlQualifiedName QnXsdWhiteSpace;
public XmlQualifiedName QnXsdRedefine;
public XmlQualifiedName QnXsdAnyType;
internal XmlQualifiedName[] TokenToQName = new XmlQualifiedName[(int)Token.XmlLang + 1];
public SchemaNames( XmlNameTable nameTable ) {
this.nameTable = nameTable;
NsDataType = nameTable.Add(XmlReservedNs.NsDataType);
NsDataTypeAlias = nameTable.Add(XmlReservedNs.NsDataTypeAlias);
NsDataTypeOld = nameTable.Add(XmlReservedNs.NsDataTypeOld);
NsXml = nameTable.Add(XmlReservedNs.NsXml);
NsXmlNs = nameTable.Add(XmlReservedNs.NsXmlNs);
NsXdr = nameTable.Add(XmlReservedNs.NsXdr);
NsXdrAlias = nameTable.Add(XmlReservedNs.NsXdrAlias);
NsXs = nameTable.Add(XmlReservedNs.NsXs);
NsXsi = nameTable.Add(XmlReservedNs.NsXsi);
XsiType = nameTable.Add("type");
XsiNil = nameTable.Add("nil");
XsiSchemaLocation = nameTable.Add("schemaLocation");
XsiNoNamespaceSchemaLocation = nameTable.Add("noNamespaceSchemaLocation");
XsdSchema = nameTable.Add("schema");
XdrSchema = nameTable.Add("Schema");
QnPCData = new XmlQualifiedName( nameTable.Add("#PCDATA") );
QnXml = new XmlQualifiedName( nameTable.Add("xml") );
QnXmlNs = new XmlQualifiedName( nameTable.Add("xmlns"), NsXmlNs );
QnDtDt = new XmlQualifiedName( nameTable.Add("dt"), NsDataType );
QnXmlLang= new XmlQualifiedName( nameTable.Add("lang"), NsXml);
// Empty namespace
QnName = new XmlQualifiedName( nameTable.Add("name") );
QnType = new XmlQualifiedName( nameTable.Add("type") );
QnMaxOccurs = new XmlQualifiedName( nameTable.Add("maxOccurs") );
QnMinOccurs = new XmlQualifiedName( nameTable.Add("minOccurs") );
QnInfinite = new XmlQualifiedName( nameTable.Add("*") );
QnModel = new XmlQualifiedName( nameTable.Add("model") );
QnOpen = new XmlQualifiedName( nameTable.Add("open") );
QnClosed = new XmlQualifiedName( nameTable.Add("closed") );
QnContent = new XmlQualifiedName( nameTable.Add("content") );
QnMixed = new XmlQualifiedName( nameTable.Add("mixed") );
QnEmpty = new XmlQualifiedName( nameTable.Add("empty") );
QnEltOnly = new XmlQualifiedName( nameTable.Add("eltOnly") );
QnTextOnly = new XmlQualifiedName( nameTable.Add("textOnly") );
QnOrder = new XmlQualifiedName( nameTable.Add("order") );
QnSeq = new XmlQualifiedName( nameTable.Add("seq") );
QnOne = new XmlQualifiedName( nameTable.Add("one") );
QnMany = new XmlQualifiedName( nameTable.Add("many") );
QnRequired = new XmlQualifiedName( nameTable.Add("required") );
QnYes = new XmlQualifiedName( nameTable.Add("yes") );
QnNo = new XmlQualifiedName( nameTable.Add("no") );
QnString = new XmlQualifiedName( nameTable.Add("string") );
QnID = new XmlQualifiedName( nameTable.Add("id") );
QnIDRef = new XmlQualifiedName( nameTable.Add("idref") );
QnIDRefs = new XmlQualifiedName( nameTable.Add("idrefs") );
QnEntity = new XmlQualifiedName( nameTable.Add("entity") );
QnEntities = new XmlQualifiedName( nameTable.Add("entities") );
QnNmToken = new XmlQualifiedName( nameTable.Add("nmtoken") );
QnNmTokens = new XmlQualifiedName( nameTable.Add("nmtokens") );
QnEnumeration = new XmlQualifiedName( nameTable.Add("enumeration") );
QnDefault = new XmlQualifiedName( nameTable.Add("default") );
//For XSD Schema
QnTargetNamespace = new XmlQualifiedName( nameTable.Add("targetNamespace") );
QnVersion = new XmlQualifiedName( nameTable.Add("version") );
QnFinalDefault = new XmlQualifiedName( nameTable.Add("finalDefault") );
QnBlockDefault = new XmlQualifiedName( nameTable.Add("blockDefault") );
QnFixed = new XmlQualifiedName( nameTable.Add("fixed") );
QnAbstract = new XmlQualifiedName( nameTable.Add("abstract") );
QnBlock = new XmlQualifiedName( nameTable.Add("block") );
QnSubstitutionGroup = new XmlQualifiedName( nameTable.Add("substitutionGroup") );
QnFinal = new XmlQualifiedName( nameTable.Add("final") );
QnNillable = new XmlQualifiedName( nameTable.Add("nillable") );
QnRef = new XmlQualifiedName( nameTable.Add("ref") );
QnBase = new XmlQualifiedName( nameTable.Add("base") );
QnDerivedBy = new XmlQualifiedName( nameTable.Add("derivedBy") );
QnNamespace = new XmlQualifiedName( nameTable.Add("namespace") );
QnProcessContents = new XmlQualifiedName( nameTable.Add("processContents") );
QnRefer = new XmlQualifiedName( nameTable.Add("refer") );
QnPublic = new XmlQualifiedName( nameTable.Add("public") );
QnSystem = new XmlQualifiedName( nameTable.Add("system") );
QnSchemaLocation = new XmlQualifiedName( nameTable.Add("schemaLocation") );
QnValue = new XmlQualifiedName( nameTable.Add("value") );
QnUse = new XmlQualifiedName( nameTable.Add("use") );
QnForm = new XmlQualifiedName( nameTable.Add("form") );
QnAttributeFormDefault = new XmlQualifiedName( nameTable.Add("attributeFormDefault") );
QnElementFormDefault = new XmlQualifiedName( nameTable.Add("elementFormDefault") );
QnSource = new XmlQualifiedName( nameTable.Add("source") );
QnMemberTypes = new XmlQualifiedName( nameTable.Add("memberTypes"));
QnItemType = new XmlQualifiedName( nameTable.Add("itemType"));
QnXPath = new XmlQualifiedName( nameTable.Add("xpath"));
// XDR namespace
QnXdrSchema = new XmlQualifiedName( XdrSchema, NsXdr );
QnXdrElementType = new XmlQualifiedName( nameTable.Add("ElementType"), NsXdr );
QnXdrElement = new XmlQualifiedName( nameTable.Add("element"), NsXdr );
QnXdrGroup = new XmlQualifiedName( nameTable.Add("group"), NsXdr );
QnXdrAttributeType = new XmlQualifiedName( nameTable.Add("AttributeType"), NsXdr );
QnXdrAttribute = new XmlQualifiedName( nameTable.Add("attribute"), NsXdr );
QnXdrDataType = new XmlQualifiedName( nameTable.Add("datatype"), NsXdr );
QnXdrDescription = new XmlQualifiedName( nameTable.Add("description"), NsXdr );
QnXdrExtends = new XmlQualifiedName( nameTable.Add("extends"), NsXdr );
// XDR alias namespace
QnXdrAliasSchema = new XmlQualifiedName( nameTable.Add("Schema"), NsDataTypeAlias );
// DataType namespace
QnDtType = new XmlQualifiedName( nameTable.Add("type"), NsDataType );
QnDtValues = new XmlQualifiedName( nameTable.Add("values"), NsDataType );
QnDtMaxLength = new XmlQualifiedName( nameTable.Add("maxLength"), NsDataType );
QnDtMinLength = new XmlQualifiedName( nameTable.Add("minLength"), NsDataType );
QnDtMax = new XmlQualifiedName( nameTable.Add("max"), NsDataType );
QnDtMin = new XmlQualifiedName( nameTable.Add("min"), NsDataType );
QnDtMinExclusive = new XmlQualifiedName( nameTable.Add("minExclusive"), NsDataType );
QnDtMaxExclusive = new XmlQualifiedName( nameTable.Add("maxExclusive"), NsDataType );
// XSD namespace
QnXsdSchema = new XmlQualifiedName( XsdSchema, NsXs );
QnXsdAnnotation= new XmlQualifiedName( nameTable.Add("annotation"), NsXs );
QnXsdInclude= new XmlQualifiedName( nameTable.Add("include"), NsXs );
QnXsdImport= new XmlQualifiedName( nameTable.Add("import"), NsXs );
QnXsdElement = new XmlQualifiedName( nameTable.Add("element"), NsXs );
QnXsdAttribute = new XmlQualifiedName( nameTable.Add("attribute"), NsXs );
QnXsdAttributeGroup = new XmlQualifiedName( nameTable.Add("attributeGroup"), NsXs );
QnXsdAnyAttribute = new XmlQualifiedName( nameTable.Add("anyAttribute"), NsXs );
QnXsdGroup = new XmlQualifiedName( nameTable.Add("group"), NsXs );
QnXsdAll = new XmlQualifiedName( nameTable.Add("all"), NsXs );
QnXsdChoice = new XmlQualifiedName( nameTable.Add("choice"), NsXs );
QnXsdSequence = new XmlQualifiedName( nameTable.Add("sequence"), NsXs );
QnXsdAny = new XmlQualifiedName( nameTable.Add("any"), NsXs );
QnXsdNotation = new XmlQualifiedName( nameTable.Add("notation"), NsXs );
QnXsdSimpleType = new XmlQualifiedName( nameTable.Add("simpleType"), NsXs );
QnXsdComplexType = new XmlQualifiedName( nameTable.Add("complexType"), NsXs );
QnXsdUnique = new XmlQualifiedName( nameTable.Add("unique"), NsXs );
QnXsdKey = new XmlQualifiedName( nameTable.Add("key"), NsXs );
QnXsdKeyRef = new XmlQualifiedName( nameTable.Add("keyref"), NsXs );
QnXsdSelector= new XmlQualifiedName( nameTable.Add("selector"), NsXs );
QnXsdField= new XmlQualifiedName( nameTable.Add("field"), NsXs );
QnXsdMinExclusive= new XmlQualifiedName( nameTable.Add("minExclusive"), NsXs );
QnXsdMinInclusive= new XmlQualifiedName( nameTable.Add("minInclusive"), NsXs );
QnXsdMaxInclusive= new XmlQualifiedName( nameTable.Add("maxInclusive"), NsXs );
QnXsdMaxExclusive= new XmlQualifiedName( nameTable.Add("maxExclusive"), NsXs );
QnXsdTotalDigits= new XmlQualifiedName( nameTable.Add("totalDigits"), NsXs );
QnXsdFractionDigits= new XmlQualifiedName( nameTable.Add("fractionDigits"), NsXs );
QnXsdLength= new XmlQualifiedName( nameTable.Add("length"), NsXs );
QnXsdMinLength= new XmlQualifiedName( nameTable.Add("minLength"), NsXs );
QnXsdMaxLength= new XmlQualifiedName( nameTable.Add("maxLength"), NsXs );
QnXsdEnumeration= new XmlQualifiedName( nameTable.Add("enumeration"), NsXs );
QnXsdPattern= new XmlQualifiedName( nameTable.Add("pattern"), NsXs );
QnXsdDocumentation= new XmlQualifiedName( nameTable.Add("documentation"), NsXs );
QnXsdAppinfo= new XmlQualifiedName( nameTable.Add("appinfo"), NsXs );
QnXsdComplexContent= new XmlQualifiedName( nameTable.Add("complexContent"), NsXs );
QnXsdSimpleContent= new XmlQualifiedName( nameTable.Add("simpleContent"), NsXs );
QnXsdRestriction= new XmlQualifiedName( nameTable.Add("restriction"), NsXs );
QnXsdExtension= new XmlQualifiedName( nameTable.Add("extension"), NsXs );
QnXsdUnion= new XmlQualifiedName( nameTable.Add("union"), NsXs );
QnXsdList= new XmlQualifiedName( nameTable.Add("list"), NsXs );
QnXsdWhiteSpace= new XmlQualifiedName( nameTable.Add("whiteSpace"), NsXs );
QnXsdRedefine= new XmlQualifiedName( nameTable.Add("redefine"), NsXs );
QnXsdAnyType= new XmlQualifiedName( nameTable.Add("anyType"), NsXs );
//Create token to Qname table
CreateTokenToQNameTable();
}
public void CreateTokenToQNameTable() {
TokenToQName[(int)Token.SchemaName] = QnName;
TokenToQName[(int)Token.SchemaType] = QnType;
TokenToQName[(int)Token.SchemaMaxOccurs] = QnMaxOccurs;
TokenToQName[(int)Token.SchemaMinOccurs] = QnMinOccurs;
TokenToQName[(int)Token.SchemaInfinite] = QnInfinite;
TokenToQName[(int)Token.SchemaModel] = QnModel;
TokenToQName[(int)Token.SchemaOpen] = QnOpen;
TokenToQName[(int)Token.SchemaClosed] = QnClosed;
TokenToQName[(int)Token.SchemaContent] = QnContent;
TokenToQName[(int)Token.SchemaMixed] = QnMixed;
TokenToQName[(int)Token.SchemaEmpty] = QnEmpty;
TokenToQName[(int)Token.SchemaElementOnly] = QnEltOnly;
TokenToQName[(int)Token.SchemaTextOnly] = QnTextOnly;
TokenToQName[(int)Token.SchemaOrder] = QnOrder;
TokenToQName[(int)Token.SchemaSeq] = QnSeq;
TokenToQName[(int)Token.SchemaOne] = QnOne;
TokenToQName[(int)Token.SchemaMany] = QnMany;
TokenToQName[(int)Token.SchemaRequired] = QnRequired;
TokenToQName[(int)Token.SchemaYes] = QnYes;
TokenToQName[(int)Token.SchemaNo] = QnNo;
TokenToQName[(int)Token.SchemaString] = QnString;
TokenToQName[(int)Token.SchemaId] = QnID;
TokenToQName[(int)Token.SchemaIdref] = QnIDRef;
TokenToQName[(int)Token.SchemaIdrefs] = QnIDRefs;
TokenToQName[(int)Token.SchemaEntity] = QnEntity;
TokenToQName[(int)Token.SchemaEntities] = QnEntities;
TokenToQName[(int)Token.SchemaNmtoken] = QnNmToken;
TokenToQName[(int)Token.SchemaNmtokens] = QnNmTokens;
TokenToQName[(int)Token.SchemaEnumeration] = QnEnumeration;
TokenToQName[(int)Token.SchemaDefault] = QnDefault;
TokenToQName[(int)Token.XdrRoot] = QnXdrSchema;
TokenToQName[(int)Token.XdrElementType] = QnXdrElementType;
TokenToQName[(int)Token.XdrElement] = QnXdrElement;
TokenToQName[(int)Token.XdrGroup] = QnXdrGroup;
TokenToQName[(int)Token.XdrAttributeType] = QnXdrAttributeType;
TokenToQName[(int)Token.XdrAttribute] = QnXdrAttribute;
TokenToQName[(int)Token.XdrDatatype] = QnXdrDataType;
TokenToQName[(int)Token.XdrDescription] = QnXdrDescription;
TokenToQName[(int)Token.XdrExtends] = QnXdrExtends;
TokenToQName[(int)Token.SchemaXdrRootAlias] = QnXdrAliasSchema;
TokenToQName[(int)Token.SchemaDtType] = QnDtType;
TokenToQName[(int)Token.SchemaDtValues] = QnDtValues;
TokenToQName[(int)Token.SchemaDtMaxLength] = QnDtMaxLength;
TokenToQName[(int)Token.SchemaDtMinLength] = QnDtMinLength;
TokenToQName[(int)Token.SchemaDtMax] = QnDtMax;
TokenToQName[(int)Token.SchemaDtMin] = QnDtMin;
TokenToQName[(int)Token.SchemaDtMinExclusive] = QnDtMinExclusive;
TokenToQName[(int)Token.SchemaDtMaxExclusive] = QnDtMaxExclusive;
TokenToQName[(int)Token.SchemaTargetNamespace] = QnTargetNamespace;
TokenToQName[(int)Token.SchemaVersion] = QnVersion;
TokenToQName[(int)Token.SchemaFinalDefault] = QnFinalDefault;
TokenToQName[(int)Token.SchemaBlockDefault] = QnBlockDefault;
TokenToQName[(int)Token.SchemaFixed] = QnFixed;
TokenToQName[(int)Token.SchemaAbstract] = QnAbstract;
TokenToQName[(int)Token.SchemaBlock] = QnBlock;
TokenToQName[(int)Token.SchemaSubstitutionGroup] = QnSubstitutionGroup;
TokenToQName[(int)Token.SchemaFinal] = QnFinal;
TokenToQName[(int)Token.SchemaNillable] = QnNillable;
TokenToQName[(int)Token.SchemaRef] = QnRef;
TokenToQName[(int)Token.SchemaBase] = QnBase;
TokenToQName[(int)Token.SchemaDerivedBy] = QnDerivedBy;
TokenToQName[(int)Token.SchemaNamespace] = QnNamespace;
TokenToQName[(int)Token.SchemaProcessContents] = QnProcessContents;
TokenToQName[(int)Token.SchemaRefer] = QnRefer;
TokenToQName[(int)Token.SchemaPublic] = QnPublic;
TokenToQName[(int)Token.SchemaSystem] = QnSystem;
TokenToQName[(int)Token.SchemaSchemaLocation] = QnSchemaLocation;
TokenToQName[(int)Token.SchemaValue] = QnValue;
TokenToQName[(int)Token.SchemaItemType] = QnItemType;
TokenToQName[(int)Token.SchemaMemberTypes] = QnMemberTypes;
TokenToQName[(int)Token.SchemaXPath] = QnXPath;
TokenToQName[(int)Token.XsdSchema] = QnXsdSchema;
TokenToQName[(int)Token.XsdAnnotation] = QnXsdAnnotation;
TokenToQName[(int)Token.XsdInclude] = QnXsdInclude;
TokenToQName[(int)Token.XsdImport] = QnXsdImport;
TokenToQName[(int)Token.XsdElement] = QnXsdElement;
TokenToQName[(int)Token.XsdAttribute] = QnXsdAttribute;
TokenToQName[(int)Token.xsdAttributeGroup] = QnXsdAttributeGroup;
TokenToQName[(int)Token.XsdAnyAttribute] = QnXsdAnyAttribute;
TokenToQName[(int)Token.XsdGroup] = QnXsdGroup;
TokenToQName[(int)Token.XsdAll] = QnXsdAll;
TokenToQName[(int)Token.XsdChoice] = QnXsdChoice;
TokenToQName[(int)Token.XsdSequence] = QnXsdSequence;
TokenToQName[(int)Token.XsdAny] = QnXsdAny;
TokenToQName[(int)Token.XsdNotation] = QnXsdNotation;
TokenToQName[(int)Token.XsdSimpleType] = QnXsdSimpleType;
TokenToQName[(int)Token.XsdComplexType] = QnXsdComplexType;
TokenToQName[(int)Token.XsdUnique] = QnXsdUnique;
TokenToQName[(int)Token.XsdKey] = QnXsdKey;
TokenToQName[(int)Token.XsdKeyref] = QnXsdKeyRef;
TokenToQName[(int)Token.XsdSelector] = QnXsdSelector;
TokenToQName[(int)Token.XsdField] = QnXsdField;
TokenToQName[(int)Token.XsdMinExclusive] = QnXsdMinExclusive;
TokenToQName[(int)Token.XsdMinInclusive] = QnXsdMinInclusive;
TokenToQName[(int)Token.XsdMaxExclusive] = QnXsdMaxExclusive;
TokenToQName[(int)Token.XsdMaxInclusive] = QnXsdMaxInclusive;
TokenToQName[(int)Token.XsdTotalDigits] = QnXsdTotalDigits;
TokenToQName[(int)Token.XsdFractionDigits] = QnXsdFractionDigits;
TokenToQName[(int)Token.XsdLength] = QnXsdLength;
TokenToQName[(int)Token.XsdMinLength] = QnXsdMinLength;
TokenToQName[(int)Token.XsdMaxLength] = QnXsdMaxLength;
TokenToQName[(int)Token.XsdEnumeration] = QnXsdEnumeration;
TokenToQName[(int)Token.XsdPattern] = QnXsdPattern;
TokenToQName[(int)Token.XsdWhitespace] = QnXsdWhiteSpace;
TokenToQName[(int)Token.XsdDocumentation] = QnXsdDocumentation;
TokenToQName[(int)Token.XsdAppInfo] = QnXsdAppinfo;
TokenToQName[(int)Token.XsdComplexContent] = QnXsdComplexContent;
TokenToQName[(int)Token.XsdComplexContentRestriction] = QnXsdRestriction;
TokenToQName[(int)Token.XsdSimpleContentRestriction] = QnXsdRestriction;
TokenToQName[(int)Token.XsdSimpleTypeRestriction] = QnXsdRestriction;
TokenToQName[(int)Token.XsdComplexContentExtension] = QnXsdExtension;
TokenToQName[(int)Token.XsdSimpleContentExtension] = QnXsdExtension;
TokenToQName[(int)Token.XsdSimpleContent] = QnXsdSimpleContent;
TokenToQName[(int)Token.XsdSimpleTypeUnion] = QnXsdUnion;
TokenToQName[(int)Token.XsdSimpleTypeList] = QnXsdList;
TokenToQName[(int)Token.XsdRedefine] = QnXsdRedefine;
TokenToQName[(int)Token.SchemaSource] = QnSource;
TokenToQName[(int)Token.SchemaUse] = QnUse;
TokenToQName[(int)Token.SchemaForm] = QnForm;
TokenToQName[(int)Token.SchemaElementFormDefault] = QnElementFormDefault;
TokenToQName[(int)Token.SchemaAttributeFormDefault] = QnAttributeFormDefault;
TokenToQName[(int)Token.XmlLang] = QnXmlLang;
TokenToQName[(int)Token.Empty] = XmlQualifiedName.Empty;
}
public SchemaType SchemaTypeFromRoot(string localName, string ns) {
if (IsXSDRoot(localName, ns)) {
return SchemaType.XSD;
}
else if (IsXDRRoot(localName, XmlSchemaDatatype.XdrCanonizeUri(ns, nameTable, this))) {
return SchemaType.XDR;
}
else {
return SchemaType.None;
}
}
public bool IsXSDRoot(string localName, string ns) {
return Ref.Equal(ns, NsXs) && Ref.Equal(localName, XsdSchema);
}
public bool IsXDRRoot(string localName, string ns) {
return Ref.Equal(ns, NsXdr) && Ref.Equal(localName, XdrSchema);
}
public XmlQualifiedName GetName(SchemaNames.Token token) {
return TokenToQName[(int)token];
}
public enum Token {
Empty,
SchemaName,
SchemaType,
SchemaMaxOccurs,
SchemaMinOccurs,
SchemaInfinite,
SchemaModel,
SchemaOpen,
SchemaClosed,
SchemaContent,
SchemaMixed,
SchemaEmpty,
SchemaElementOnly,
SchemaTextOnly,
SchemaOrder,
SchemaSeq,
SchemaOne,
SchemaMany,
SchemaRequired,
SchemaYes,
SchemaNo,
SchemaString,
SchemaId,
SchemaIdref,
SchemaIdrefs,
SchemaEntity,
SchemaEntities,
SchemaNmtoken,
SchemaNmtokens,
SchemaEnumeration,
SchemaDefault,
XdrRoot,
XdrElementType,
XdrElement,
XdrGroup,
XdrAttributeType,
XdrAttribute,
XdrDatatype,
XdrDescription,
XdrExtends,
SchemaXdrRootAlias,
SchemaDtType,
SchemaDtValues,
SchemaDtMaxLength,
SchemaDtMinLength,
SchemaDtMax,
SchemaDtMin,
SchemaDtMinExclusive,
SchemaDtMaxExclusive,
SchemaTargetNamespace,
SchemaVersion,
SchemaFinalDefault,
SchemaBlockDefault,
SchemaFixed,
SchemaAbstract,
SchemaBlock,
SchemaSubstitutionGroup,
SchemaFinal,
SchemaNillable,
SchemaRef,
SchemaBase,
SchemaDerivedBy,
SchemaNamespace,
SchemaProcessContents,
SchemaRefer,
SchemaPublic,
SchemaSystem,
SchemaSchemaLocation,
SchemaValue,
SchemaSource,
SchemaAttributeFormDefault,
SchemaElementFormDefault,
SchemaUse,
SchemaForm,
XsdSchema,
XsdAnnotation,
XsdInclude,
XsdImport,
XsdElement,
XsdAttribute,
xsdAttributeGroup,
XsdAnyAttribute,
XsdGroup,
XsdAll,
XsdChoice,
XsdSequence,
XsdAny,
XsdNotation,
XsdSimpleType,
XsdComplexType,
XsdUnique,
XsdKey,
XsdKeyref,
XsdSelector,
XsdField,
XsdMinExclusive,
XsdMinInclusive,
XsdMaxExclusive,
XsdMaxInclusive,
XsdTotalDigits,
XsdFractionDigits,
XsdLength,
XsdMinLength,
XsdMaxLength,
XsdEnumeration,
XsdPattern,
XsdDocumentation,
XsdAppInfo,
XsdComplexContent,
XsdComplexContentExtension,
XsdComplexContentRestriction,
XsdSimpleContent,
XsdSimpleContentExtension,
XsdSimpleContentRestriction,
XsdSimpleTypeList,
XsdSimpleTypeRestriction,
XsdSimpleTypeUnion,
XsdWhitespace,
XsdRedefine,
SchemaItemType,
SchemaMemberTypes,
SchemaXPath,
XmlLang
};
};
}
| |
//
// Copyright (c) 2004-2017 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
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Config;
using NLog.Filters;
using NLog.Internal;
/// <summary>
/// Implementation of logging engine.
/// </summary>
internal static class LoggerImpl
{
private const int StackTraceSkipMethods = 0;
private static readonly Assembly nlogAssembly = typeof(LoggerImpl).Assembly;
private static readonly Assembly mscorlibAssembly = typeof(string).Assembly;
private static readonly Assembly systemAssembly = typeof(Debug).Assembly;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using 'NLog' in message.")]
internal static void Write([NotNull] Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
{
if (targets == null)
{
return;
}
StackTraceUsage stu = targets.GetStackTraceUsage();
if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
{
StackTrace stackTrace;
#if !SILVERLIGHT
stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
#else
stackTrace = new StackTrace();
#endif
int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType);
logEvent.SetStackTrace(stackTrace, firstUserFrame);
}
AsyncContinuation exceptionHandler = (ex) => { };
if (factory.ThrowExceptions)
{
int originalThreadId = Thread.CurrentThread.ManagedThreadId;
exceptionHandler = ex =>
{
if (ex != null)
{
if (Thread.CurrentThread.ManagedThreadId == originalThreadId)
{
throw new NLogRuntimeException("Exception occurred in NLog", ex);
}
}
};
}
for (var t = targets; t != null; t = t.NextInChain)
{
if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
{
break;
}
}
}
/// <summary>
/// Finds first user stack frame in a stack trace
/// </summary>
/// <param name="stackTrace">The stack trace of the logging method invocation</param>
/// <param name="loggerType">Type of the logger or logger wrapper. This is still Logger if it's a subclass of Logger.</param>
/// <returns>Index of the first user stack frame or 0 if all stack frames are non-user</returns>
internal static int FindCallingMethodOnStackTrace([NotNull] StackTrace stackTrace, [NotNull] Type loggerType)
{
var stackFrames = stackTrace.GetFrames();
if (stackFrames == null)
return 0;
//create StackFrameWithIndex so the index is know after filtering
var allStackFrames = stackFrames.Select((f, i) => new StackFrameWithIndex(i, f)).ToList();
//filter on assemblies
var filteredStackframes = allStackFrames.Where(p => !SkipAssembly(p.StackFrame)).ToList();
//find until logger type
var intermediate = filteredStackframes.SkipWhile(p => !IsLoggerType(p.StackFrame, loggerType));
//skip the logger type
var stackframesAfterLogger = intermediate.SkipWhile(p => IsLoggerType(p.StackFrame, loggerType)).ToList();
//get first call after logger (or skip if is moveNext)
var candidateStackFrames = stackframesAfterLogger;
if (!candidateStackFrames.Any())
{
//If some calls got inlined, we can't find LoggerType on the stack. Fallback to the filteredStackframes
candidateStackFrames = filteredStackframes;
}
return FindIndexOfCallingMethod(allStackFrames, candidateStackFrames);
}
/// <summary>
/// Get the index which correspondens to the calling method.
///
/// This is most of the time the first index after <paramref name="candidateStackFrames"/>.
/// </summary>
/// <param name="allStackFrames">all the frames of the stacktrace</param>
/// <param name="candidateStackFrames">frames which all hiddenAssemblies are removed</param>
/// <returns>index on stacktrace</returns>
private static int FindIndexOfCallingMethod(List<StackFrameWithIndex> allStackFrames, List<StackFrameWithIndex> candidateStackFrames)
{
var stackFrameWithIndex = candidateStackFrames.FirstOrDefault();
var last = stackFrameWithIndex;
if (last != null)
{
#if NET4_5
//movenext and then AsyncTaskMethodBuilder (method start)? this is a generated MoveNext by async.
if (last.StackFrame.GetMethod().Name == "MoveNext")
{
if (allStackFrames.Count > last.StackFrameIndex)
{
var next = allStackFrames[last.StackFrameIndex + 1];
var declaringType = next.StackFrame.GetMethod().DeclaringType;
if (declaringType == typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder) ||
declaringType == typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<>))
{
//async, search futher
candidateStackFrames = candidateStackFrames.Skip(1).ToList();
return FindIndexOfCallingMethod(allStackFrames, candidateStackFrames);
}
}
}
#endif
return last.StackFrameIndex;
}
return 0;
}
/// <summary>
/// Assembly to skip?
/// </summary>
/// <param name="frame">Find assembly via this frame. </param>
/// <returns><c>true</c>, we should skip.</returns>
private static bool SkipAssembly(StackFrame frame)
{
var method = frame.GetMethod();
var assembly = method.DeclaringType != null ? method.DeclaringType.Assembly : method.Module.Assembly;
// skip stack frame if the method declaring type assembly is from hidden assemblies list
var skipAssembly = SkipAssembly(assembly);
return skipAssembly;
}
/// <summary>
/// Is this the type of the logger?
/// </summary>
/// <param name="frame">get type of this logger in this frame.</param>
/// <param name="loggerType">Type of the logger.</param>
/// <returns></returns>
private static bool IsLoggerType(StackFrame frame, Type loggerType)
{
var method = frame.GetMethod();
Type declaringType = method.DeclaringType;
var isLoggerType = declaringType != null && (loggerType == declaringType || declaringType.IsSubclassOf(loggerType) || declaringType.IsSubclassOf(typeof(ILogger)));
return isLoggerType;
}
private static bool SkipAssembly(Assembly assembly)
{
if (assembly == nlogAssembly)
{
return true;
}
if (assembly == mscorlibAssembly)
{
return true;
}
if (assembly == systemAssembly)
{
return true;
}
if (LogManager.IsHiddenAssembly(assembly))
{
return true;
}
return false;
}
private static bool WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException)
{
FilterResult result = GetFilterResult(targetListHead.FilterChain, logEvent);
if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal))
{
if (InternalLogger.IsDebugEnabled)
{
InternalLogger.Debug("{0}.{1} Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level);
}
if (result == FilterResult.IgnoreFinal)
{
return false;
}
return true;
}
targetListHead.Target.WriteAsyncLogEvent(logEvent.WithContinuation(onException));
if (result == FilterResult.LogFinal)
{
return false;
}
return true;
}
/// <summary>
/// Gets the filter result.
/// </summary>
/// <param name="filterChain">The filter chain.</param>
/// <param name="logEvent">The log event.</param>
/// <returns>The result of the filter.</returns>
private static FilterResult GetFilterResult(IList<Filter> filterChain, LogEventInfo logEvent)
{
FilterResult result = FilterResult.Neutral;
if (filterChain == null || filterChain.Count == 0)
return result;
try
{
//Memory profiling pointed out that using a foreach-loop was allocating
//an Enumerator. Switching to a for-loop avoids the memory allocation.
for (int i = 0; i < filterChain.Count; i++)
{
Filter f = filterChain[i];
result = f.GetFilterResult(logEvent);
if (result != FilterResult.Neutral)
{
break;
}
}
return result;
}
catch (Exception exception)
{
InternalLogger.Warn(exception, "Exception during filter evaluation. Message will be ignore.");
if (exception.MustBeRethrown())
{
throw;
}
return FilterResult.Ignore;
}
}
/// <summary>
/// Stackframe with correspending index on the stracktrace
/// </summary>
private class StackFrameWithIndex
{
/// <summary>
/// Index of <see cref="StackFrame"/> on the stack.
/// </summary>
public int StackFrameIndex { get; private set; }
/// <summary>
/// A stackframe
/// </summary>
public StackFrame StackFrame { get; private set; }
/// <summary>
/// New item
/// </summary>
/// <param name="stackFrameIndex">Index of <paramref name="stackFrame"/> on the stack.</param>
/// <param name="stackFrame">A stackframe</param>
public StackFrameWithIndex(int stackFrameIndex, StackFrame stackFrame)
{
StackFrameIndex = stackFrameIndex;
StackFrame = stackFrame;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using System.Net;
using System.Text;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Nini.Config;
using log4net;
namespace OpenSim.Server.Handlers.Simulation
{
public class AgentGetHandler : BaseStreamHandler
{
// TODO: unused: private ISimulationService m_SimulationService;
// TODO: unused: private IAuthenticationService m_AuthenticationService;
public AgentGetHandler(ISimulationService service, IAuthenticationService authentication) :
base("GET", "/agent")
{
// TODO: unused: m_SimulationService = service;
// TODO: unused: m_AuthenticationService = authentication;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// Not implemented yet
httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
return new byte[] { };
}
}
public class AgentPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ISimulationService m_SimulationService;
private IAuthenticationService m_AuthenticationService;
// TODO: unused: private bool m_AllowForeignGuests;
public AgentPostHandler(ISimulationService service, IAuthenticationService authentication, bool foreignGuests) :
base("POST", "/agent")
{
m_SimulationService = service;
m_AuthenticationService = authentication;
// TODO: unused: m_AllowForeignGuests = foreignGuests;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
byte[] result = new byte[0];
UUID agentID;
string action;
ulong regionHandle;
if (!RestHandlerUtils.GetParams(path, out agentID, out regionHandle, out action))
{
m_log.InfoFormat("[AgentPostHandler]: Invalid parameters for agent message {0}", path);
httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
httpResponse.StatusDescription = "Invalid parameters for agent message " + path;
return result;
}
if (m_AuthenticationService != null)
{
// Authentication
string authority = string.Empty;
string authToken = string.Empty;
if (!RestHandlerUtils.GetAuthentication(httpRequest, out authority, out authToken))
{
m_log.InfoFormat("[AgentPostHandler]: Authentication failed for agent message {0}", path);
httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized;
return result;
}
if (!m_AuthenticationService.VerifyKey(agentID, authToken))
{
m_log.InfoFormat("[AgentPostHandler]: Authentication failed for agent message {0}", path);
httpResponse.StatusCode = (int)HttpStatusCode.Forbidden;
return result;
}
m_log.DebugFormat("[AgentPostHandler]: Authentication succeeded for {0}", agentID);
}
OSDMap args = Util.GetOSDMap(request, (int)httpRequest.ContentLength);
if (args == null)
{
httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
httpResponse.StatusDescription = "Unable to retrieve data";
m_log.DebugFormat("[AgentPostHandler]: Unable to retrieve data for post {0}", path);
return result;
}
// retrieve the regionhandle
ulong regionhandle = 0;
if (args["destination_handle"] != null)
UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
AgentCircuitData aCircuit = new AgentCircuitData();
try
{
aCircuit.UnpackAgentCircuitData(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[AgentPostHandler]: exception on unpacking CreateAgent message {0}", ex.Message);
httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
httpResponse.StatusDescription = "Problems with data deserialization";
return result;
}
string reason = string.Empty;
// We need to clean up a few things in the user service before I can do this
//if (m_AllowForeignGuests)
// m_regionClient.AdjustUserInformation(aCircuit);
// Finally!
bool success = m_SimulationService.CreateAgent(regionhandle, aCircuit, out reason);
OSDMap resp = new OSDMap(1);
resp["success"] = OSD.FromBoolean(success);
httpResponse.StatusCode = (int)HttpStatusCode.OK;
return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(resp));
}
}
public class AgentPutHandler : BaseStreamHandler
{
// TODO: unused: private ISimulationService m_SimulationService;
// TODO: unused: private IAuthenticationService m_AuthenticationService;
public AgentPutHandler(ISimulationService service, IAuthenticationService authentication) :
base("PUT", "/agent")
{
// TODO: unused: m_SimulationService = service;
// TODO: unused: m_AuthenticationService = authentication;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// Not implemented yet
httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
return new byte[] { };
}
}
public class AgentDeleteHandler : BaseStreamHandler
{
// TODO: unused: private ISimulationService m_SimulationService;
// TODO: unused: private IAuthenticationService m_AuthenticationService;
public AgentDeleteHandler(ISimulationService service, IAuthenticationService authentication) :
base("DELETE", "/agent")
{
// TODO: unused: m_SimulationService = service;
// TODO: unused: m_AuthenticationService = authentication;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// Not implemented yet
httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
return new byte[] { };
}
}
}
| |
//-----------------------------------------------------------------------
// This file is part of Microsoft Robotics Developer Studio Code Samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// $File: DriveState.cs $ $Revision: 1 $
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.Dss.Core.Attributes;
using motor = Microsoft.Robotics.Services.Motor;
namespace Microsoft.Robotics.Services.Drive
{
/// <summary>
/// Differential Drive State Definition
/// </summary>
[DataContract]
[Description("The state of the differential drive.")]
public class DriveDifferentialTwoWheelState
{
private motor.WheeledMotorState _leftWheel;
private motor.WheeledMotorState _rightWheel;
private bool _isEnabled;
private double _distanceBetweenWheels;
private DriveStage _driveDistanceStage = DriveStage.InitialRequest;
private DriveStage _rotateDegreesStage = DriveStage.InitialRequest;
private DriveRequestOperation _internalPendingDriveOperation;
DateTime _timeStamp;
///<summary>
/// The last drive request operation
///</summary>
public DriveRequestOperation InternalPendingDriveOperation
{
get { return _internalPendingDriveOperation; }
set { _internalPendingDriveOperation = value; }
}
/// <summary>
/// The timestamp of the last state change.
/// </summary>
[DataMember(XmlOmitDefaultValue = true)]
[Browsable (false)]
[Description("Indicates the timestamp of the last state change.")]
public DateTime TimeStamp
{
get { return _timeStamp; }
set { _timeStamp = value; }
}
/// <summary>
/// The left wheel's state.
/// </summary>
[DataMember]
[Description("The left wheel's state.")]
public motor.WheeledMotorState LeftWheel
{
get { return this._leftWheel; }
set { this._leftWheel = value; }
}
/// <summary>
/// The right wheel's state.
/// </summary>
[DataMember]
[Description("The right wheel's state.")]
public motor.WheeledMotorState RightWheel
{
get { return this._rightWheel; }
set { this._rightWheel = value; }
}
/// <summary>
/// The distance between the drive wheels (meters).
/// </summary>
[DataMember]
[Description("Indicates the distance between the drive wheels (meters).")]
public double DistanceBetweenWheels
{
get { return this._distanceBetweenWheels; }
set { this._distanceBetweenWheels = value; }
}
/// <summary>
/// Indicates whether the drive has been enabled.
/// </summary>
[DataMember]
[Description("Indicates whether the drive has been enabled.")]
public bool IsEnabled
{
get { return _isEnabled; }
set { _isEnabled = value; }
}
/// <summary>
/// The current stage of a driveDistance operation.
/// </summary>
[DataMember]
[Description("The current stage of a driveDistance operation.")]
public DriveStage DriveDistanceStage
{
get { return _driveDistanceStage; }
set { _driveDistanceStage = value; }
}
/// <summary>
/// The current stage of a rotateDegrees operation.
/// </summary>
[DataMember]
[Description("The current stage of a rotateDegrees operation.")]
public DriveStage RotateDegreesStage
{
get { return _rotateDegreesStage; }
set { _rotateDegreesStage = value; }
}
/// <summary>
/// Indicates the current state of the Drive.
/// </summary>
[DataMember]
[Description("Indicates the current state of the drive.")]
[Browsable(false)]
public DriveState DriveState;
/// <summary>
/// Default Constructor
/// </summary>
public DriveDifferentialTwoWheelState() { }
/// <summary>
/// Initialization constructor
/// </summary>
/// <param name="distanceBetweenWheels"></param>
/// <param name="leftWheel"></param>
/// <param name="rightWheel"></param>
public DriveDifferentialTwoWheelState(double distanceBetweenWheels, motor.WheeledMotorState leftWheel, motor.WheeledMotorState rightWheel)
{
_distanceBetweenWheels = distanceBetweenWheels;
_leftWheel = leftWheel;
_rightWheel = rightWheel;
}
}
/// <summary>
/// The current Drive State
/// </summary>
[DataContract]
public enum DriveState
{
/// <summary>
/// Not Specified
/// </summary>
NotSpecified = 0,
/// <summary>
/// Stopped
/// </summary>
Stopped,
/// <summary>
/// Drive Distance
/// </summary>
DriveDistance,
/// <summary>
/// Drive Power
/// </summary>
DrivePower,
/// <summary>
/// Rotate Degrees
/// </summary>
RotateDegrees,
/// <summary>
/// DriveSpeed
/// </summary>
DriveSpeed
}
/// <summary>
/// The status of the current drive operation (driveDistance or rotateDegrees)
/// Only one operation can be pending (else it is canceled).
///
/// Stage transitions:
/// InitialRequest -> Started -> Completed
/// Or:
/// InitialRequest -> Started -> Canceled
/// </summary>
[DataContract]
public enum DriveStage
{
/// <summary>
/// A request to initiate a drive distance or rotate degrees operation
/// </summary>
InitialRequest = 0,
/// <summary>
/// A drive operation (drive distance or rotate degrees) has started
/// </summary>
Started,
/// <summary>
/// The pending drive operation was canceled
/// </summary>
Canceled,
/// <summary>
/// Successful completion of a drive distance or rotate degrees operation
/// </summary>
Completed
}
/// <summary>
/// The request operation
/// </summary>
[DataContract]
public enum DriveRequestOperation
{
/// <summary>
/// Not Specified
/// </summary>
NotSpecified = 0,
/// <summary>
/// All Stop
/// </summary>
AllStop,
/// <summary>
/// Drive Distance
/// </summary>
DriveDistance,
/// <summary>
/// Drive Power
/// </summary>
SetDrivePower,
/// <summary>
/// Rotate Degrees
/// </summary>
RotateDegrees,
/// <summary>
/// Drive Speed
/// </summary>
DriveSpeed,
/// <summary>
/// Enable Drive
/// </summary>
EnableDrive
}
/// <summary>
/// Update the target power of each motor.
/// </summary>
[DataContract]
[DataMemberConstructor]
public class SetDrivePowerRequest
{
private double _leftWheelPower;
private double _rightWheelPower;
/// <summary>
/// Set Power for Left Wheel. Range is -1.0 to 1.0
/// </summary>
[DataMember]
[Description("Indicates the power setting for the left wheel; range is -1.0 to 1.0.")]
public double LeftWheelPower
{
get { return _leftWheelPower; }
set { _leftWheelPower = value; }
}
/// <summary>
/// Set Power for Right Wheel. Range is -1.0 to 1.0
/// </summary>
[DataMember]
[Description("Indicates the power setting for the right wheel; range is -1.0 to 1.0.")]
public double RightWheelPower
{
get { return _rightWheelPower; }
set { _rightWheelPower = value; }
}
/// <summary>
/// Default constructor
/// </summary>
public SetDrivePowerRequest()
{
}
/// <summary>
/// Initialization constructor
/// </summary>
/// <param name="leftWheelPower">Range is -1.0 to 1.0 (positive value is forward)</param>
/// <param name="rightWheelPower">Range is -1.0 to 1.0(positive value is forward)</param>
public SetDrivePowerRequest(double leftWheelPower, double rightWheelPower)
{
_leftWheelPower = leftWheelPower;
_rightWheelPower = rightWheelPower;
}
}
/// <summary>
/// Update the target speed of a motor.
/// <remarks>set speed for each wheel in meters per second</remarks>
/// </summary>
[DataContract]
[DataMemberConstructor]
public class SetDriveSpeedRequest
{
private double _leftWheelSpeed;
private double _rightWheelSpeed;
/// <summary>
/// Set Speed for Left Wheel (m/s)
/// </summary>
[DataMember]
[Description("Indicates the speed setting for the left wheel (in m/s).")]
public double LeftWheelSpeed
{
get { return _leftWheelSpeed; }
set { _leftWheelSpeed = value; }
}
/// <summary>
/// Set Speed for Right Wheel (m/s)
/// </summary>
[DataMember]
[Description("Indicates the speed setting for the right wheel (in m/s).")]
public double RightWheelSpeed
{
get { return _rightWheelSpeed; }
set { _rightWheelSpeed = value; }
}
/// <summary>
/// Default constructor
/// </summary>
public SetDriveSpeedRequest() { }
/// <summary>
/// Initialization Constructor
/// </summary>
/// <param name="leftWheelSpeed"></param>
/// <param name="rightWheelSpeed"></param>
public SetDriveSpeedRequest(double leftWheelSpeed, double rightWheelSpeed)
{
_leftWheelSpeed = leftWheelSpeed;
_rightWheelSpeed = rightWheelSpeed;
}
}
/// <summary>
/// Drive straight for specified distance
/// </summary>
[DataContract]
[DataMemberConstructor]
public class DriveDistanceRequest
{
double _distance;
double _power;
DriveStage _driveDistanceStage;
/// <summary>
/// Distance in meters
/// </summary>
[DataMember(IsRequired = true)]
[Description("Specifies the distance to drive (meters).")]
public double Distance
{
get { return _distance; }
set { _distance = value; }
}
/// <summary>
/// The drive's power setting (-1.0 to 1.0 -- Forward: positive value, Reverse: negative value.)
/// </summary>
[DataMember(IsRequired = true)]
[Description("Specifies the power setting for driving (-1.0 to 1.0 -- Forward: positive value, Reverse: negative value.).")]
public double Power
{
get { return _power; }
set { _power = value; }
}
/// <summary>
/// Distance stage
/// </summary>
[DataMember]
[DataMemberConstructor(Order=-1)]
[Description("Specifies the current drive distance stage.")]
public DriveStage DriveDistanceStage
{
get { return _driveDistanceStage; }
set { _driveDistanceStage = value; }
}
/// <summary>
/// Default constructor
/// </summary>
public DriveDistanceRequest() { }
/// <summary>
/// Initialization constructor
/// </summary>
/// <param name="distance"></param>
/// <param name="pow"></param>
public DriveDistanceRequest(double distance, double pow)
{
_distance = distance;
_power = pow;
_driveDistanceStage = DriveStage.InitialRequest;
}
}
/// <summary>
/// Request the drive to rotate or turn in position (positive values turn counterclockwise).
/// </summary>
[DataContract, Description("Request the drive to rotate or turn in position (positive values turn counterclockwise).")]
[DataMemberConstructor]
public class RotateDegreesRequest
{
double _degrees;
double _power;
DriveStage _rotateDegreesStage;
/// <summary>
/// Degrees of rotation (positive values turn counterclockwise).
/// </summary>
[DataMember(IsRequired = true)]
[Description("Specifies the drive setting in degrees of rotation (positive values turn counterclockwise).")]
public double Degrees
{
get { return _degrees; }
set { _degrees = value; }
}
/// <summary>
/// The drive's power setting (-1.0 to 1.0 -- Forward: positive value, Reverse: negative value.)
/// </summary>
[DataMember(IsRequired = true)]
[Description("Specifies the drive's power setting (-1.0 to 1.0 -- Forward: positive value, Reverse: negative value.")]
public double Power
{
get { return _power; }
set { _power = value; }
}
/// <summary>
/// RotateDegrees stage
/// </summary>
[DataMember(IsRequired = true)]
[DataMemberConstructor(Order = -1)]
[Description("Specifies the current rotate degrees stage.")]
public DriveStage RotateDegreesStage
{
get { return _rotateDegreesStage; }
set { _rotateDegreesStage = value; }
}
/// <summary>
/// Request the drive to rotate or turn in position (positive values turn counterclockwise).
/// </summary>
public RotateDegreesRequest() { }
/// <summary>
/// Request the drive to rotate or turn in position (positive values turn counterclockwise).
/// </summary>
/// <param name="degrees"></param>
/// <param name="power"></param>
public RotateDegreesRequest(double degrees, double power)
{
_degrees = degrees;
_power = power;
_rotateDegreesStage = DriveStage.InitialRequest;
}
}
/// <summary>
/// Enables or disables the drive
/// </summary>
[DataContract]
[DataMemberConstructor]
public class EnableDriveRequest
{
private bool _enable;
/// <summary>
/// Enable drive
/// </summary>
[DataMember]
[Description("Identifies if the drive is enabled.")]
public bool Enable
{
get { return _enable; }
set { _enable = value; }
}
/// <summary>
/// Default constructor
/// </summary>
public EnableDriveRequest()
{
_enable = true;
}
/// <summary>
/// Initialization constructor
/// </summary>
/// <param name="enable"></param>
public EnableDriveRequest(bool enable)
{
_enable = enable;
}
}
/// <summary>
/// Emergency stop
/// </summary>
[DataContract]
public class AllStopRequest
{
}
/// <summary>
/// Set Motor Uri Request
/// </summary>
[DataContract]
public class SetMotorUriRequest
{
private Uri _leftMotorUri;
private Uri _rightMotorUri;
/// <summary>
/// Left Motor Uri
/// </summary>
[DataMember]
[Description("Identifies the left motor URI setting.")]
public string LeftMotorUri
{
get { return _leftMotorUri.AbsoluteUri; }
set { _leftMotorUri = new Uri(value); }
}
/// <summary>
/// Right Motor Uri
/// </summary>
[DataMember]
[Description("Identifieis the right motor URI setting.")]
public string RightMotorUri
{
get { return _rightMotorUri.AbsoluteUri; }
set { _rightMotorUri = new Uri(value); }
}
/// <summary>
/// Default constructor
/// </summary>
public SetMotorUriRequest() { }
/// <summary>
/// Initialization constructor
/// </summary>
/// <param name="leftMotor"></param>
/// <param name="rightMotor"></param>
public SetMotorUriRequest(Uri leftMotor, Uri rightMotor)
{
_leftMotorUri = leftMotor;
_rightMotorUri = rightMotor;
}
}
#region internal to service
//==================================================================
// Internal to service
/// <summary>
/// Cancel Pending Drive Operation Request Request
/// (cancels a pending driveDistance or RotateDegrees request)
/// </summary>
[DataContract]
public class CancelPendingDriveOperationRequest
{
}
#endregion
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Thrift.Transport;
using System.Globalization;
namespace Thrift.Protocol
{
/// <summary>
/// JSON protocol implementation for thrift.
/// <para/>
/// This is a full-featured protocol supporting Write and Read.
/// <para/>
/// Please see the C++ class header for a detailed description of the
/// protocol's wire format.
/// <para/>
/// Adapted from the Java version.
/// </summary>
public class TJSONProtocol : TProtocol
{
/// <summary>
/// Factory for JSON protocol objects.
/// </summary>
public class Factory : TProtocolFactory
{
public TProtocol GetProtocol(TTransport trans)
{
return new TJSONProtocol(trans);
}
}
private static byte[] COMMA = new byte[] { (byte)',' };
private static byte[] COLON = new byte[] { (byte)':' };
private static byte[] LBRACE = new byte[] { (byte)'{' };
private static byte[] RBRACE = new byte[] { (byte)'}' };
private static byte[] LBRACKET = new byte[] { (byte)'[' };
private static byte[] RBRACKET = new byte[] { (byte)']' };
private static byte[] QUOTE = new byte[] { (byte)'"' };
private static byte[] BACKSLASH = new byte[] { (byte)'\\' };
private byte[] ESCSEQ = new byte[] { (byte)'\\', (byte)'u', (byte)'0', (byte)'0' };
private const long VERSION = 1;
private byte[] JSON_CHAR_TABLE = {
0, 0, 0, 0, 0, 0, 0, 0,(byte)'b',(byte)'t',(byte)'n', 0,(byte)'f',(byte)'r', 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1,(byte)'"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
};
private char[] ESCAPE_CHARS = "\"\\/bfnrt".ToCharArray();
private byte[] ESCAPE_CHAR_VALS = {
(byte)'"', (byte)'\\', (byte)'/', (byte)'\b', (byte)'\f', (byte)'\n', (byte)'\r', (byte)'\t',
};
private const int DEF_STRING_SIZE = 16;
private static byte[] NAME_BOOL = new byte[] { (byte)'t', (byte)'f' };
private static byte[] NAME_BYTE = new byte[] { (byte)'i', (byte)'8' };
private static byte[] NAME_I16 = new byte[] { (byte)'i', (byte)'1', (byte)'6' };
private static byte[] NAME_I32 = new byte[] { (byte)'i', (byte)'3', (byte)'2' };
private static byte[] NAME_I64 = new byte[] { (byte)'i', (byte)'6', (byte)'4' };
private static byte[] NAME_DOUBLE = new byte[] { (byte)'d', (byte)'b', (byte)'l' };
private static byte[] NAME_STRUCT = new byte[] { (byte)'r', (byte)'e', (byte)'c' };
private static byte[] NAME_STRING = new byte[] { (byte)'s', (byte)'t', (byte)'r' };
private static byte[] NAME_MAP = new byte[] { (byte)'m', (byte)'a', (byte)'p' };
private static byte[] NAME_LIST = new byte[] { (byte)'l', (byte)'s', (byte)'t' };
private static byte[] NAME_SET = new byte[] { (byte)'s', (byte)'e', (byte)'t' };
private static byte[] GetTypeNameForTypeID(TType typeID)
{
switch (typeID)
{
case TType.Bool:
return NAME_BOOL;
case TType.Byte:
return NAME_BYTE;
case TType.I16:
return NAME_I16;
case TType.I32:
return NAME_I32;
case TType.I64:
return NAME_I64;
case TType.Double:
return NAME_DOUBLE;
case TType.String:
return NAME_STRING;
case TType.Struct:
return NAME_STRUCT;
case TType.Map:
return NAME_MAP;
case TType.Set:
return NAME_SET;
case TType.List:
return NAME_LIST;
default:
throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED,
"Unrecognized type");
}
}
private static TType GetTypeIDForTypeName(byte[] name)
{
TType result = TType.Stop;
if (name.Length > 1)
{
switch (name[0])
{
case (byte)'d':
result = TType.Double;
break;
case (byte)'i':
switch (name[1])
{
case (byte)'8':
result = TType.Byte;
break;
case (byte)'1':
result = TType.I16;
break;
case (byte)'3':
result = TType.I32;
break;
case (byte)'6':
result = TType.I64;
break;
}
break;
case (byte)'l':
result = TType.List;
break;
case (byte)'m':
result = TType.Map;
break;
case (byte)'r':
result = TType.Struct;
break;
case (byte)'s':
if (name[1] == (byte)'t')
{
result = TType.String;
}
else if (name[1] == (byte)'e')
{
result = TType.Set;
}
break;
case (byte)'t':
result = TType.Bool;
break;
}
}
if (result == TType.Stop)
{
throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED,
"Unrecognized type");
}
return result;
}
/// <summary>
/// Base class for tracking JSON contexts that may require
/// inserting/Reading additional JSON syntax characters
/// This base context does nothing.
/// </summary>
protected class JSONBaseContext
{
protected TJSONProtocol proto;
public JSONBaseContext(TJSONProtocol proto)
{
this.proto = proto;
}
public virtual void Write() { }
public virtual void Read() { }
public virtual bool EscapeNumbers() { return false; }
}
/// <summary>
/// Context for JSON lists. Will insert/Read commas before each item except
/// for the first one
/// </summary>
protected class JSONListContext : JSONBaseContext
{
public JSONListContext(TJSONProtocol protocol)
: base(protocol)
{
}
private bool first = true;
public override void Write()
{
if (first)
{
first = false;
}
else
{
proto.trans.Write(COMMA);
}
}
public override void Read()
{
if (first)
{
first = false;
}
else
{
proto.ReadJSONSyntaxChar(COMMA);
}
}
}
/// <summary>
/// Context for JSON records. Will insert/Read colons before the value portion
/// of each record pair, and commas before each key except the first. In
/// addition, will indicate that numbers in the key position need to be
/// escaped in quotes (since JSON keys must be strings).
/// </summary>
protected class JSONPairContext : JSONBaseContext
{
public JSONPairContext(TJSONProtocol proto)
: base(proto)
{
}
private bool first = true;
private bool colon = true;
public override void Write()
{
if (first)
{
first = false;
colon = true;
}
else
{
proto.trans.Write(colon ? COLON : COMMA);
colon = !colon;
}
}
public override void Read()
{
if (first)
{
first = false;
colon = true;
}
else
{
proto.ReadJSONSyntaxChar(colon ? COLON : COMMA);
colon = !colon;
}
}
public override bool EscapeNumbers()
{
return colon;
}
}
/// <summary>
/// Holds up to one byte from the transport
/// </summary>
protected class LookaheadReader
{
protected TJSONProtocol proto;
public LookaheadReader(TJSONProtocol proto)
{
this.proto = proto;
}
private bool hasData;
private byte[] data = new byte[1];
/// <summary>
/// Return and consume the next byte to be Read, either taking it from the
/// data buffer if present or getting it from the transport otherwise.
/// </summary>
public byte Read()
{
if (hasData)
{
hasData = false;
}
else
{
proto.trans.ReadAll(data, 0, 1);
}
return data[0];
}
/// <summary>
/// Return the next byte to be Read without consuming, filling the data
/// buffer if it has not been filled alReady.
/// </summary>
public byte Peek()
{
if (!hasData)
{
proto.trans.ReadAll(data, 0, 1);
}
hasData = true;
return data[0];
}
}
// Default encoding
protected Encoding utf8Encoding = UTF8Encoding.UTF8;
// Stack of nested contexts that we may be in
protected Stack<JSONBaseContext> contextStack = new Stack<JSONBaseContext>();
// Current context that we are in
protected JSONBaseContext context;
// Reader that manages a 1-byte buffer
protected LookaheadReader reader;
/// <summary>
/// Push a new JSON context onto the stack.
/// </summary>
protected void PushContext(JSONBaseContext c)
{
contextStack.Push(context);
context = c;
}
/// <summary>
/// Pop the last JSON context off the stack
/// </summary>
protected void PopContext()
{
context = contextStack.Pop();
}
/// <summary>
/// TJSONProtocol Constructor
/// </summary>
public TJSONProtocol(TTransport trans)
: base(trans)
{
context = new JSONBaseContext(this);
reader = new LookaheadReader(this);
}
// Temporary buffer used by several methods
private byte[] tempBuffer = new byte[4];
/// <summary>
/// Read a byte that must match b[0]; otherwise an exception is thrown.
/// Marked protected to avoid synthetic accessor in JSONListContext.Read
/// and JSONPairContext.Read
/// </summary>
protected void ReadJSONSyntaxChar(byte[] b)
{
byte ch = reader.Read();
if (ch != b[0])
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Unexpected character:" + (char)ch);
}
}
/// <summary>
/// Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its
/// corresponding hex value
/// </summary>
private static byte HexVal(byte ch)
{
if ((ch >= '0') && (ch <= '9'))
{
return (byte)((char)ch - '0');
}
else if ((ch >= 'a') && (ch <= 'f'))
{
ch += 10;
return (byte)((char)ch - 'a');
}
else
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected hex character");
}
}
/// <summary>
/// Convert a byte containing a hex value to its corresponding hex character
/// </summary>
private static byte HexChar(byte val)
{
val &= 0x0F;
if (val < 10)
{
return (byte)((char)val + '0');
}
else
{
val -= 10;
return (byte)((char)val + 'a');
}
}
/// <summary>
/// Write the bytes in array buf as a JSON characters, escaping as needed
/// </summary>
private void WriteJSONString(byte[] b)
{
context.Write();
trans.Write(QUOTE);
int len = b.Length;
for (int i = 0; i < len; i++)
{
if ((b[i] & 0x00FF) >= 0x30)
{
if (b[i] == BACKSLASH[0])
{
trans.Write(BACKSLASH);
trans.Write(BACKSLASH);
}
else
{
trans.Write(b, i, 1);
}
}
else
{
tempBuffer[0] = JSON_CHAR_TABLE[b[i]];
if (tempBuffer[0] == 1)
{
trans.Write(b, i, 1);
}
else if (tempBuffer[0] > 1)
{
trans.Write(BACKSLASH);
trans.Write(tempBuffer, 0, 1);
}
else
{
trans.Write(ESCSEQ);
tempBuffer[0] = HexChar((byte)(b[i] >> 4));
tempBuffer[1] = HexChar(b[i]);
trans.Write(tempBuffer, 0, 2);
}
}
}
trans.Write(QUOTE);
}
/// <summary>
/// Write out number as a JSON value. If the context dictates so, it will be
/// wrapped in quotes to output as a JSON string.
/// </summary>
private void WriteJSONInteger(long num)
{
context.Write();
string str = num.ToString();
bool escapeNum = context.EscapeNumbers();
if (escapeNum)
trans.Write(QUOTE);
trans.Write(utf8Encoding.GetBytes(str));
if (escapeNum)
trans.Write(QUOTE);
}
/// <summary>
/// Write out a double as a JSON value. If it is NaN or infinity or if the
/// context dictates escaping, Write out as JSON string.
/// </summary>
private void WriteJSONDouble(double num)
{
context.Write();
string str = num.ToString("G17", CultureInfo.InvariantCulture);
bool special = false;
switch (str[0])
{
case 'N': // NaN
case 'I': // Infinity
special = true;
break;
case '-':
if (str[1] == 'I')
{ // -Infinity
special = true;
}
break;
}
bool escapeNum = special || context.EscapeNumbers();
if (escapeNum)
trans.Write(QUOTE);
trans.Write(utf8Encoding.GetBytes(str));
if (escapeNum)
trans.Write(QUOTE);
}
/// <summary>
/// Write out contents of byte array b as a JSON string with base-64 encoded
/// data
/// </summary>
private void WriteJSONBase64(byte[] b)
{
context.Write();
trans.Write(QUOTE);
int len = b.Length;
int off = 0;
while (len >= 3)
{
// Encode 3 bytes at a time
TBase64Utils.encode(b, off, 3, tempBuffer, 0);
trans.Write(tempBuffer, 0, 4);
off += 3;
len -= 3;
}
if (len > 0)
{
// Encode remainder
TBase64Utils.encode(b, off, len, tempBuffer, 0);
trans.Write(tempBuffer, 0, len + 1);
}
trans.Write(QUOTE);
}
private void WriteJSONObjectStart()
{
context.Write();
trans.Write(LBRACE);
PushContext(new JSONPairContext(this));
}
private void WriteJSONObjectEnd()
{
PopContext();
trans.Write(RBRACE);
}
private void WriteJSONArrayStart()
{
context.Write();
trans.Write(LBRACKET);
PushContext(new JSONListContext(this));
}
private void WriteJSONArrayEnd()
{
PopContext();
trans.Write(RBRACKET);
}
public override void WriteMessageBegin(TMessage message)
{
WriteJSONArrayStart();
WriteJSONInteger(VERSION);
byte[] b = utf8Encoding.GetBytes(message.Name);
WriteJSONString(b);
WriteJSONInteger((long)message.Type);
WriteJSONInteger(message.SeqID);
}
public override void WriteMessageEnd()
{
WriteJSONArrayEnd();
}
public override void WriteStructBegin(TStruct str)
{
WriteJSONObjectStart();
}
public override void WriteStructEnd()
{
WriteJSONObjectEnd();
}
public override void WriteFieldBegin(TField field)
{
WriteJSONInteger(field.ID);
WriteJSONObjectStart();
WriteJSONString(GetTypeNameForTypeID(field.Type));
}
public override void WriteFieldEnd()
{
WriteJSONObjectEnd();
}
public override void WriteFieldStop() { }
public override void WriteMapBegin(TMap map)
{
WriteJSONArrayStart();
WriteJSONString(GetTypeNameForTypeID(map.KeyType));
WriteJSONString(GetTypeNameForTypeID(map.ValueType));
WriteJSONInteger(map.Count);
WriteJSONObjectStart();
}
public override void WriteMapEnd()
{
WriteJSONObjectEnd();
WriteJSONArrayEnd();
}
public override void WriteListBegin(TList list)
{
WriteJSONArrayStart();
WriteJSONString(GetTypeNameForTypeID(list.ElementType));
WriteJSONInteger(list.Count);
}
public override void WriteListEnd()
{
WriteJSONArrayEnd();
}
public override void WriteSetBegin(TSet set)
{
WriteJSONArrayStart();
WriteJSONString(GetTypeNameForTypeID(set.ElementType));
WriteJSONInteger(set.Count);
}
public override void WriteSetEnd()
{
WriteJSONArrayEnd();
}
public override void WriteBool(bool b)
{
WriteJSONInteger(b ? (long)1 : (long)0);
}
public override void WriteByte(sbyte b)
{
WriteJSONInteger((long)b);
}
public override void WriteI16(short i16)
{
WriteJSONInteger((long)i16);
}
public override void WriteI32(int i32)
{
WriteJSONInteger((long)i32);
}
public override void WriteI64(long i64)
{
WriteJSONInteger(i64);
}
public override void WriteDouble(double dub)
{
WriteJSONDouble(dub);
}
public override void WriteString(string str)
{
byte[] b = utf8Encoding.GetBytes(str);
WriteJSONString(b);
}
public override void WriteBinary(byte[] bin)
{
WriteJSONBase64(bin);
}
/**
* Reading methods.
*/
/// <summary>
/// Read in a JSON string, unescaping as appropriate.. Skip Reading from the
/// context if skipContext is true.
/// </summary>
private byte[] ReadJSONString(bool skipContext)
{
MemoryStream buffer = new MemoryStream();
List<char> codeunits = new List<char>();
if (!skipContext)
{
context.Read();
}
ReadJSONSyntaxChar(QUOTE);
while (true)
{
byte ch = reader.Read();
if (ch == QUOTE[0])
{
break;
}
// escaped?
if (ch != ESCSEQ[0])
{
buffer.Write(new byte[] { (byte)ch }, 0, 1);
continue;
}
// distinguish between \uXXXX and \?
ch = reader.Read();
if (ch != ESCSEQ[1]) // control chars like \n
{
int off = Array.IndexOf(ESCAPE_CHARS, (char)ch);
if (off == -1)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected control char");
}
ch = ESCAPE_CHAR_VALS[off];
buffer.Write(new byte[] { (byte)ch }, 0, 1);
continue;
}
// it's \uXXXX
trans.ReadAll(tempBuffer, 0, 4);
var wch = (short)((HexVal((byte)tempBuffer[0]) << 12) +
(HexVal((byte)tempBuffer[1]) << 8) +
(HexVal((byte)tempBuffer[2]) << 4) +
HexVal(tempBuffer[3]));
if (Char.IsHighSurrogate((char)wch))
{
if (codeunits.Count > 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected low surrogate char");
}
codeunits.Add((char)wch);
}
else if (Char.IsLowSurrogate((char)wch))
{
if (codeunits.Count == 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected high surrogate char");
}
codeunits.Add((char)wch);
var tmp = utf8Encoding.GetBytes(codeunits.ToArray());
buffer.Write(tmp, 0, tmp.Length);
codeunits.Clear();
}
else
{
var tmp = utf8Encoding.GetBytes(new char[] { (char)wch });
buffer.Write(tmp, 0, tmp.Length);
}
}
if (codeunits.Count > 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected low surrogate char");
}
return buffer.ToArray();
}
/// <summary>
/// Return true if the given byte could be a valid part of a JSON number.
/// </summary>
private bool IsJSONNumeric(byte b)
{
switch (b)
{
case (byte)'+':
case (byte)'-':
case (byte)'.':
case (byte)'0':
case (byte)'1':
case (byte)'2':
case (byte)'3':
case (byte)'4':
case (byte)'5':
case (byte)'6':
case (byte)'7':
case (byte)'8':
case (byte)'9':
case (byte)'E':
case (byte)'e':
return true;
}
return false;
}
/// <summary>
/// Read in a sequence of characters that are all valid in JSON numbers. Does
/// not do a complete regex check to validate that this is actually a number.
/// </summary>
private string ReadJSONNumericChars()
{
StringBuilder strbld = new StringBuilder();
while (true)
{
byte ch = reader.Peek();
if (!IsJSONNumeric(ch))
{
break;
}
strbld.Append((char)reader.Read());
}
return strbld.ToString();
}
/// <summary>
/// Read in a JSON number. If the context dictates, Read in enclosing quotes.
/// </summary>
private long ReadJSONInteger()
{
context.Read();
if (context.EscapeNumbers())
{
ReadJSONSyntaxChar(QUOTE);
}
string str = ReadJSONNumericChars();
if (context.EscapeNumbers())
{
ReadJSONSyntaxChar(QUOTE);
}
try
{
return Int64.Parse(str);
}
catch (FormatException fex)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Bad data encounted in numeric data", fex);
}
}
/// <summary>
/// Read in a JSON double value. Throw if the value is not wrapped in quotes
/// when expected or if wrapped in quotes when not expected.
/// </summary>
private double ReadJSONDouble()
{
context.Read();
if (reader.Peek() == QUOTE[0])
{
byte[] arr = ReadJSONString(true);
double dub = Double.Parse(utf8Encoding.GetString(arr, 0, arr.Length), CultureInfo.InvariantCulture);
if (!context.EscapeNumbers() && !Double.IsNaN(dub) && !Double.IsInfinity(dub))
{
// Throw exception -- we should not be in a string in this case
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Numeric data unexpectedly quoted");
}
return dub;
}
else
{
if (context.EscapeNumbers())
{
// This will throw - we should have had a quote if escapeNum == true
ReadJSONSyntaxChar(QUOTE);
}
try
{
return Double.Parse(ReadJSONNumericChars(), CultureInfo.InvariantCulture);
}
catch (FormatException fex)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Bad data encounted in numeric data", fex);
}
}
}
/// <summary>
/// Read in a JSON string containing base-64 encoded data and decode it.
/// </summary>
private byte[] ReadJSONBase64()
{
byte[] b = ReadJSONString(false);
int len = b.Length;
int off = 0;
int size = 0;
// reduce len to ignore fill bytes
while ((len > 0) && (b[len - 1] == '='))
{
--len;
}
// read & decode full byte triplets = 4 source bytes
while (len > 4)
{
// Decode 4 bytes at a time
TBase64Utils.decode(b, off, 4, b, size); // NB: decoded in place
off += 4;
len -= 4;
size += 3;
}
// Don't decode if we hit the end or got a single leftover byte (invalid
// base64 but legal for skip of regular string type)
if (len > 1)
{
// Decode remainder
TBase64Utils.decode(b, off, len, b, size); // NB: decoded in place
size += len - 1;
}
// Sadly we must copy the byte[] (any way around this?)
byte[] result = new byte[size];
Array.Copy(b, 0, result, 0, size);
return result;
}
private void ReadJSONObjectStart()
{
context.Read();
ReadJSONSyntaxChar(LBRACE);
PushContext(new JSONPairContext(this));
}
private void ReadJSONObjectEnd()
{
ReadJSONSyntaxChar(RBRACE);
PopContext();
}
private void ReadJSONArrayStart()
{
context.Read();
ReadJSONSyntaxChar(LBRACKET);
PushContext(new JSONListContext(this));
}
private void ReadJSONArrayEnd()
{
ReadJSONSyntaxChar(RBRACKET);
PopContext();
}
public override TMessage ReadMessageBegin()
{
TMessage message = new TMessage();
ReadJSONArrayStart();
if (ReadJSONInteger() != VERSION)
{
throw new TProtocolException(TProtocolException.BAD_VERSION,
"Message contained bad version.");
}
var buf = ReadJSONString(false);
message.Name = utf8Encoding.GetString(buf, 0, buf.Length);
message.Type = (TMessageType)ReadJSONInteger();
message.SeqID = (int)ReadJSONInteger();
return message;
}
public override void ReadMessageEnd()
{
ReadJSONArrayEnd();
}
public override TStruct ReadStructBegin()
{
ReadJSONObjectStart();
return new TStruct();
}
public override void ReadStructEnd()
{
ReadJSONObjectEnd();
}
public override TField ReadFieldBegin()
{
TField field = new TField();
byte ch = reader.Peek();
if (ch == RBRACE[0])
{
field.Type = TType.Stop;
}
else
{
field.ID = (short)ReadJSONInteger();
ReadJSONObjectStart();
field.Type = GetTypeIDForTypeName(ReadJSONString(false));
}
return field;
}
public override void ReadFieldEnd()
{
ReadJSONObjectEnd();
}
public override TMap ReadMapBegin()
{
TMap map = new TMap();
ReadJSONArrayStart();
map.KeyType = GetTypeIDForTypeName(ReadJSONString(false));
map.ValueType = GetTypeIDForTypeName(ReadJSONString(false));
map.Count = (int)ReadJSONInteger();
ReadJSONObjectStart();
return map;
}
public override void ReadMapEnd()
{
ReadJSONObjectEnd();
ReadJSONArrayEnd();
}
public override TList ReadListBegin()
{
TList list = new TList();
ReadJSONArrayStart();
list.ElementType = GetTypeIDForTypeName(ReadJSONString(false));
list.Count = (int)ReadJSONInteger();
return list;
}
public override void ReadListEnd()
{
ReadJSONArrayEnd();
}
public override TSet ReadSetBegin()
{
TSet set = new TSet();
ReadJSONArrayStart();
set.ElementType = GetTypeIDForTypeName(ReadJSONString(false));
set.Count = (int)ReadJSONInteger();
return set;
}
public override void ReadSetEnd()
{
ReadJSONArrayEnd();
}
public override bool ReadBool()
{
return (ReadJSONInteger() == 0 ? false : true);
}
public override sbyte ReadByte()
{
return (sbyte)ReadJSONInteger();
}
public override short ReadI16()
{
return (short)ReadJSONInteger();
}
public override int ReadI32()
{
return (int)ReadJSONInteger();
}
public override long ReadI64()
{
return (long)ReadJSONInteger();
}
public override double ReadDouble()
{
return ReadJSONDouble();
}
public override string ReadString()
{
var buf = ReadJSONString(false);
return utf8Encoding.GetString(buf, 0, buf.Length);
}
public override byte[] ReadBinary()
{
return ReadJSONBase64();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.