context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
Copyright (c) 2010 by Genstein
This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper.
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.Diagnostics;
using System.Collections.Generic;
namespace Trizbort
{
/// <summary>
/// A abstract point on the compass rose.
/// </summary>
internal enum CompassPoint
{
North,
NorthNorthEast,
NorthEast,
EastNorthEast,
East,
EastSouthEast,
SouthEast,
SouthSouthEast,
South,
SouthSouthWest,
SouthWest,
WestSouthWest,
West,
WestNorthWest,
NorthWest,
NorthNorthWest,
Min = North,
Max = NorthNorthWest,
}
internal static class CompassPointHelper
{
private static readonly string[] Names =
{
"n",
"nne",
"ne",
"ene",
"e",
"ese",
"se",
"sse",
"s",
"ssw",
"sw",
"wsw",
"w",
"wnw",
"nw",
"nnw",
};
public static bool ToName(CompassPoint point, out string name)
{
int index = (int)point;
if (index >= 0 && index < Names.Length)
{
name = Names[index];
return true;
}
name = string.Empty;
return false;
}
public static bool FromName(string name, out CompassPoint point)
{
for (int index = 0; index < Names.Length; ++index)
{
if (StringComparer.InvariantCultureIgnoreCase.Compare(name ?? string.Empty, Names[index]) == 0)
{
point = (CompassPoint)index;
return true;
}
}
point = CompassPoint.North;
return false;
}
/// <summary>
/// Rotate a point clockwise to find its neighbour on that side.
/// </summary>
public static CompassPoint RotateClockwise(CompassPoint point)
{
point = (CompassPoint)((int)point + 1);
if (point > CompassPoint.Max)
{
point = CompassPoint.Min;
}
return point;
}
/// <summary>
/// Rotate a point anti-clockwise to find its neighbour on that side.
/// </summary>
public static CompassPoint RotateAntiClockwise(CompassPoint point)
{
point = (CompassPoint)((int)point - 1);
if (point < CompassPoint.Min)
{
point = CompassPoint.Max;
}
return point;
}
/// <summary>
/// Get the geometric opposite of a compass point on the compass rose.
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
public static CompassPoint GetOpposite(CompassPoint point)
{
for (int index = 0; index < (int)(CompassPoint.Max - CompassPoint.Min + 1) / 2; ++index)
{
point = RotateClockwise(point);
}
return point;
}
/// <summary>
/// Get the compass point which is the opposite of the given point,
/// for the purpose of connecting rooms during automapping.
/// </summary>
/// <remarks>
/// Treating the room as a box, and mapping compass points onto it,
/// the automap opposite is the corresponding point on the opposite
/// side of the box.
/// </remarks>
public static CompassPoint GetAutomapOpposite(CompassPoint point)
{
switch (point)
{
case CompassPoint.North:
return CompassPoint.South;
case CompassPoint.NorthNorthEast:
return CompassPoint.SouthSouthEast; // vertical
case CompassPoint.NorthEast:
return CompassPoint.SouthWest;
case CompassPoint.EastNorthEast:
return CompassPoint.WestNorthWest; // horizontal
case CompassPoint.East:
return CompassPoint.West;
case CompassPoint.EastSouthEast:
return CompassPoint.WestSouthWest; // horizontal
case CompassPoint.SouthEast:
return CompassPoint.NorthWest;
case CompassPoint.SouthSouthEast:
return CompassPoint.NorthNorthEast; // vertical
case CompassPoint.South:
return CompassPoint.North;
case CompassPoint.SouthSouthWest:
return CompassPoint.NorthNorthWest; // vertical
case CompassPoint.SouthWest:
return CompassPoint.NorthEast;
case CompassPoint.WestSouthWest:
return CompassPoint.EastSouthEast; // horizontal
case CompassPoint.West:
return CompassPoint.East;
case CompassPoint.WestNorthWest:
return CompassPoint.EastNorthEast; // horizontal
case CompassPoint.NorthWest:
return CompassPoint.SouthEast;
case CompassPoint.NorthNorthWest:
return CompassPoint.SouthSouthWest; // vertical
default:
Debug.Assert(false, "Opposite compass point not found.");
return CompassPoint.North;
}
}
/// <summary>
/// Get the direction delta (where x and y are range -1 to 1) in which
/// we would place a new room given a connection in the given direction.
/// </summary>
/// <remarks>
/// Two compass points have the same direction vector if they are mapped
/// onto the the same side of a box drawn to represent the room.
/// </remarks>
public static Vector GetAutomapDirectionVector(CompassPoint compassPoint)
{
switch (compassPoint)
{
case CompassPoint.NorthNorthWest:
case CompassPoint.North:
case CompassPoint.NorthNorthEast:
return new Vector(0, -1);
case CompassPoint.NorthEast:
return new Vector(1, -1);
case CompassPoint.EastNorthEast:
case CompassPoint.East:
case CompassPoint.EastSouthEast:
return new Vector(1, 0);
case CompassPoint.SouthEast:
return new Vector(1, 1);
case CompassPoint.SouthSouthEast:
case CompassPoint.South:
case CompassPoint.SouthSouthWest:
return new Vector(0, 1);
case CompassPoint.SouthWest:
return new Vector(-1, 1);
case CompassPoint.WestSouthWest:
case CompassPoint.West:
case CompassPoint.WestNorthWest:
return new Vector(-1, 0);
case CompassPoint.NorthWest:
return new Vector(-1, -1);
default:
Debug.Assert(false, "Direction vector not found.");
return new Vector(0, -1);
}
}
public static CompassPoint GetCompassPointFromAutomapDirectionVector(Vector vector)
{
if (vector.X < 0)
{
if (vector.Y < 0)
{
return CompassPoint.NorthWest;
}
if (vector.Y > 0)
{
return CompassPoint.SouthWest;
}
return CompassPoint.West;
}
else if (vector.X > 0)
{
if (vector.Y < 0)
{
return CompassPoint.NorthEast;
}
if (vector.Y > 0)
{
return CompassPoint.SouthEast;
}
return CompassPoint.East;
}
else
{
if (vector.Y < 0)
{
return CompassPoint.North;
}
if (vector.Y > 0)
{
return CompassPoint.South;
}
Debug.Assert(false, "Automap direction vector should not be zero.");
return CompassPoint.North;
}
}
/// <summary>
/// Convert an automap direction into a compass point.
/// Compass directions map directly; up/down/in/out are assigned specific other diretions.
/// </summary>
public static CompassPoint GetCompassDirection(AutomapDirection direction)
{
switch (direction)
{
case AutomapDirection.Up:
return CompassPoint.NorthNorthWest;
case AutomapDirection.Down:
return CompassPoint.SouthSouthWest;
case AutomapDirection.In:
return CompassPoint.EastNorthEast;
case AutomapDirection.Out:
return CompassPoint.WestNorthWest;
case AutomapDirection.North:
return CompassPoint.North;
case AutomapDirection.South:
return CompassPoint.South;
case AutomapDirection.East:
return CompassPoint.East;
case AutomapDirection.West:
return CompassPoint.West;
case AutomapDirection.NorthEast:
return CompassPoint.NorthEast;
case AutomapDirection.NorthWest:
return CompassPoint.NorthWest;
case AutomapDirection.SouthEast:
return CompassPoint.SouthEast;
case AutomapDirection.SouthWest:
return CompassPoint.SouthWest;
default:
Debug.Assert(false, "Couldn't work out the compass direction for the given automap direction.");
return CompassPoint.North;
}
}
/// <summary>
/// "Round" the compass point to the nearest cardinal or ordinal direction.
/// </summary>
public static CompassPoint GetNearestCardinalOrOrdinal(CompassPoint compassPoint)
{
return GetCompassPointFromAutomapDirectionVector(GetAutomapDirectionVector(compassPoint));
}
/// <summary>
/// Get the literal opposite of any direction.
/// </summary>
public static AutomapDirection GetOpposite(AutomapDirection direction)
{
switch (direction)
{
case AutomapDirection.North:
return AutomapDirection.South;
case AutomapDirection.South:
return AutomapDirection.North;
case AutomapDirection.East:
return AutomapDirection.West;
case AutomapDirection.West:
return AutomapDirection.East;
case AutomapDirection.NorthEast:
return AutomapDirection.SouthWest;
case AutomapDirection.NorthWest:
return AutomapDirection.SouthEast;
case AutomapDirection.SouthEast:
return AutomapDirection.NorthWest;
case AutomapDirection.SouthWest:
return AutomapDirection.NorthEast;
case AutomapDirection.Up:
return AutomapDirection.Down;
case AutomapDirection.Down:
return AutomapDirection.Up;
case AutomapDirection.In:
return AutomapDirection.Out;
case AutomapDirection.Out:
return AutomapDirection.In;
default:
Debug.Assert(false, "Couldn't work out the opposite of the given direction.");
return AutomapDirection.North;
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, the libsecondlife development team
* 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.
* - Neither the name of the Second Life Reverse Engineering Team 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.Collections.Generic;
using System.ComponentModel;
namespace libsecondlife
{
/// <summary>
/// Particle system specific enumerators, flags and methods.
/// </summary>
public partial class Primitive
{
/// <summary>
/// Complete structure for the particle system
/// </summary>
public struct ParticleSystem
{
/// <summary>
/// Particle source pattern
/// </summary>
public enum SourcePattern : byte
{
/// <summary>None</summary>
None = 0,
/// <summary>Drop particles from source position with no force</summary>
Drop = 0x01,
/// <summary>"Explode" particles in all directions</summary>
Explode = 0x02,
/// <summary>Particles shoot across a 2D area</summary>
Angle = 0x04,
/// <summary>Particles shoot across a 3D Cone</summary>
AngleCone = 0x08,
/// <summary>Inverse of AngleCone (shoot particles everywhere except the 3D cone defined</summary>
AngleConeEmpty = 0x10
}
/// <summary>
/// Particle Data Flags
/// </summary>
[Flags]
public enum ParticleDataFlags : uint
{
/// <summary>None</summary>
None = 0,
/// <summary>Interpolate color and alpha from start to end</summary>
InterpColor = 0x001,
/// <summary>Interpolate scale from start to end</summary>
InterpScale = 0x002,
/// <summary>Bounce particles off particle sources Z height</summary>
Bounce = 0x004,
/// <summary>velocity of particles is dampened toward the simulators wind</summary>
Wind = 0x008,
/// <summary>Particles follow the source</summary>
FollowSrc = 0x010,
/// <summary>Particles point towards the direction of source's velocity</summary>
FollowVelocity = 0x020,
/// <summary>Target of the particles</summary>
TargetPos = 0x040,
/// <summary>Particles are sent in a straight line</summary>
TargetLinear = 0x080,
/// <summary>Particles emit a glow</summary>
Emissive = 0x100,
/// <summary>used for point/grab/touch</summary>
Beam = 0x200
}
/// <summary>
/// Particle Flags Enum
/// </summary>
[Flags]
public enum ParticleFlags : uint
{
/// <summary>None</summary>
None = 0,
/// <summary>Acceleration and velocity for particles are
/// relative to the object rotation</summary>
ObjectRelative = 0x01,
/// <summary>Particles use new 'correct' angle parameters</summary>
UseNewAngle = 0x02
}
public uint CRC;
/// <summary>Particle Flags</summary>
/// <remarks>There appears to be more data packed in to this area
/// for many particle systems. It doesn't appear to be flag values
/// and serialization breaks unless there is a flag for every
/// possible bit so it is left as an unsigned integer</remarks>
public uint PartFlags;
/// <summary><seealso cref="T:SourcePattern"/> pattern of particles</summary>
public SourcePattern Pattern;
/// <summary>A <see langword="float"/> representing the maximimum age (in seconds) particle will be displayed</summary>
/// <remarks>Maximum value is 30 seconds</remarks>
public float MaxAge;
/// <summary>A <see langword="float"/> representing the number of seconds,
/// from when the particle source comes into view,
/// or the particle system's creation, that the object will emits particles;
/// after this time period no more particles are emitted</summary>
public float StartAge;
/// <summary>A <see langword="float"/> in radians that specifies where particles will not be created</summary>
public float InnerAngle;
/// <summary>A <see langword="float"/> in radians that specifies where particles will be created</summary>
public float OuterAngle;
/// <summary>A <see langword="float"/> representing the number of seconds between burts.</summary>
public float BurstRate;
/// <summary>A <see langword="float"/> representing the number of meters
/// around the center of the source where particles will be created.</summary>
public float BurstRadius;
/// <summary>A <see langword="float"/> representing in seconds, the minimum speed between bursts of new particles
/// being emitted</summary>
public float BurstSpeedMin;
/// <summary>A <see langword="float"/> representing in seconds the maximum speed of new particles being emitted.</summary>
public float BurstSpeedMax;
/// <summary>A <see langword="byte"/> representing the maximum number of particles emitted per burst</summary>
public byte BurstPartCount;
/// <summary>A <see cref="T:LLVector3"/> which represents the velocity (speed) from the source which particles are emitted</summary>
public LLVector3 AngularVelocity;
/// <summary>A <see cref="T:LLVector3"/> which represents the Acceleration from the source which particles are emitted</summary>
public LLVector3 PartAcceleration;
/// <summary>The <see cref="T:LLUUID"/> Key of the texture displayed on the particle</summary>
public LLUUID Texture;
/// <summary>The <see cref="T:LLUUID"/> Key of the specified target object or avatar particles will follow</summary>
public LLUUID Target;
/// <summary>Flags of particle from <seealso cref="T:ParticleDataFlags"/></summary>
public ParticleDataFlags PartDataFlags;
/// <summary>Max Age particle system will emit particles for</summary>
public float PartMaxAge;
/// <summary>The <see cref="T:LLColor"/> the particle has at the beginning of its lifecycle</summary>
public LLColor PartStartColor;
/// <summary>The <see cref="T:LLColor"/> the particle has at the ending of its lifecycle</summary>
public LLColor PartEndColor;
/// <summary>A <see langword="float"/> that represents the starting X size of the particle</summary>
/// <remarks>Minimum value is 0, maximum value is 4</remarks>
public float PartStartScaleX;
/// <summary>A <see langword="float"/> that represents the starting Y size of the particle</summary>
/// <remarks>Minimum value is 0, maximum value is 4</remarks>
public float PartStartScaleY;
/// <summary>A <see langword="float"/> that represents the ending X size of the particle</summary>
/// <remarks>Minimum value is 0, maximum value is 4</remarks>
public float PartEndScaleX;
/// <summary>A <see langword="float"/> that represents the ending Y size of the particle</summary>
/// <remarks>Minimum value is 0, maximum value is 4</remarks>
public float PartEndScaleY;
/// <summary>
/// Decodes a byte[] array into a ParticleSystem Object
/// </summary>
/// <param name="data">ParticleSystem object</param>
/// <param name="pos">Start position for BitPacker</param>
public ParticleSystem(byte[] data, int pos)
{
// TODO: Not sure exactly how many bytes we need here, so partial
// (truncated) data will cause an exception to be thrown
if (data.Length > 0)
{
BitPack pack = new BitPack(data, pos);
CRC = pack.UnpackUBits(32);
PartFlags = pack.UnpackUBits(32);
Pattern = (SourcePattern)pack.UnpackByte();
MaxAge = pack.UnpackFixed(false, 8, 8);
StartAge = pack.UnpackFixed(false, 8, 8);
InnerAngle = pack.UnpackFixed(false, 3, 5);
OuterAngle = pack.UnpackFixed(false, 3, 5);
BurstRate = pack.UnpackFixed(false, 8, 8);
BurstRadius = pack.UnpackFixed(false, 8, 8);
BurstSpeedMin = pack.UnpackFixed(false, 8, 8);
BurstSpeedMax = pack.UnpackFixed(false, 8, 8);
BurstPartCount = pack.UnpackByte();
float x = pack.UnpackFixed(true, 8, 7);
float y = pack.UnpackFixed(true, 8, 7);
float z = pack.UnpackFixed(true, 8, 7);
AngularVelocity = new LLVector3(x, y, z);
x = pack.UnpackFixed(true, 8, 7);
y = pack.UnpackFixed(true, 8, 7);
z = pack.UnpackFixed(true, 8, 7);
PartAcceleration = new LLVector3(x, y, z);
Texture = pack.UnpackUUID();
Target = pack.UnpackUUID();
PartDataFlags = (ParticleDataFlags)pack.UnpackUBits(32);
PartMaxAge = pack.UnpackFixed(false, 8, 8);
byte r = pack.UnpackByte();
byte g = pack.UnpackByte();
byte b = pack.UnpackByte();
byte a = pack.UnpackByte();
PartStartColor = new LLColor(r, g, b, a);
r = pack.UnpackByte();
g = pack.UnpackByte();
b = pack.UnpackByte();
a = pack.UnpackByte();
PartEndColor = new LLColor(r, g, b, a);
PartStartScaleX = pack.UnpackFixed(false, 3, 5);
PartStartScaleY = pack.UnpackFixed(false, 3, 5);
PartEndScaleX = pack.UnpackFixed(false, 3, 5);
PartEndScaleY = pack.UnpackFixed(false, 3, 5);
}
else
{
CRC = PartFlags = 0;
Pattern = SourcePattern.None;
MaxAge = StartAge = InnerAngle = OuterAngle = BurstRate = BurstRadius = BurstSpeedMin =
BurstSpeedMax = 0.0f;
BurstPartCount = 0;
AngularVelocity = PartAcceleration = LLVector3.Zero;
Texture = Target = LLUUID.Zero;
PartDataFlags = ParticleDataFlags.None;
PartMaxAge = 0.0f;
PartStartColor = PartEndColor = LLColor.Black;
PartStartScaleX = PartStartScaleY = PartEndScaleX = PartEndScaleY = 0.0f;
}
}
/// <summary>
/// Generate byte[] array from particle data
/// </summary>
/// <returns>Byte array</returns>
public byte[] GetBytes()
{
byte[] bytes = new byte[86];
BitPack pack = new BitPack(bytes, 0);
pack.PackBits(CRC, 32);
pack.PackBits((uint)PartFlags, 32);
pack.PackBits((uint)Pattern, 8);
pack.PackFixed(MaxAge, false, 8, 8);
pack.PackFixed(StartAge, false, 8, 8);
pack.PackFixed(InnerAngle, false, 3, 5);
pack.PackFixed(OuterAngle, false, 3, 5);
pack.PackFixed(BurstRate, false, 8, 8);
pack.PackFixed(BurstRadius, false, 8, 8);
pack.PackFixed(BurstSpeedMin, false, 8, 8);
pack.PackFixed(BurstSpeedMax, false, 8, 8);
pack.PackBits(BurstPartCount, 8);
pack.PackFixed(AngularVelocity.X, true, 8, 7);
pack.PackFixed(AngularVelocity.Y, true, 8, 7);
pack.PackFixed(AngularVelocity.Z, true, 8, 7);
pack.PackFixed(PartAcceleration.X, true, 8, 7);
pack.PackFixed(PartAcceleration.Y, true, 8, 7);
pack.PackFixed(PartAcceleration.Z, true, 8, 7);
pack.PackUUID(Texture);
pack.PackUUID(Target);
pack.PackBits((uint)PartDataFlags, 32);
pack.PackFixed(PartMaxAge, false, 8, 8);
pack.PackColor(PartStartColor);
pack.PackColor(PartEndColor);
pack.PackFixed(PartStartScaleX, false, 3, 5);
pack.PackFixed(PartStartScaleY, false, 3, 5);
pack.PackFixed(PartEndScaleX, false, 3, 5);
pack.PackFixed(PartEndScaleY, false, 3, 5);
return bytes;
}
}
}
}
| |
/*
* Copyright (c) 2009 Jim Radford http://www.jimradford.com
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Microsoft.Win32;
using WeifenLuo.WinFormsUI.Docking;
using log4net;
using System.Xml.Serialization;
using System.IO;
using System.Collections;
using System.Reflection;
namespace SuperPutty.Data
{
public enum ConnectionProtocol
{
SSH,
SSH2,
Telnet,
Rlogin,
Raw,
Serial,
Cygterm,
Mintty
}
/// <summary>The main class containing configuration settings for a session</summary>
public class SessionData : IComparable, ICloneable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(SessionData));
/// <summary>Full session id (includes path for session tree)e.g. FolderName/SessionName</summary>
private string _SessionId;
[XmlAttribute]
public string SessionId
{
get { return this._SessionId; }
set
{
this.OldSessionId = SessionId;
this._SessionId = value;
}
}
internal string OldSessionId { get; set; }
private string _OldName;
[XmlIgnore]
public string OldName
{
get { return _OldName; }
set { _OldName = value; }
}
private string _SessionName;
[XmlAttribute]
public string SessionName
{
get { return _SessionName; }
set { OldName = _SessionName;
_SessionName = value;
if (SessionId == null)
{
SessionId = value;
}
}
}
private string _ImageKey;
/// <summary>A string containing the key of the image associated with this session</summary>
[XmlAttribute]
public string ImageKey
{
get { return _ImageKey; }
set { _ImageKey = value; }
}
private string _Host;
[XmlAttribute]
public string Host
{
get { return _Host; }
set { _Host = value; }
}
private int _Port;
[XmlAttribute]
public int Port
{
get { return _Port; }
set { _Port = value; }
}
private ConnectionProtocol _Proto;
[XmlAttribute]
public ConnectionProtocol Proto
{
get { return _Proto; }
set { _Proto = value; }
}
private string _PuttySession;
[XmlAttribute]
public string PuttySession
{
get { return _PuttySession; }
set { _PuttySession = value; }
}
private string _Username;
[XmlAttribute]
public string Username
{
get { return _Username; }
set { _Username = value; }
}
private string _Password;
[XmlIgnore]
public string Password
{
get { return _Password; }
set { _Password = value; }
}
private string _ExtraArgs;
[XmlAttribute]
public string ExtraArgs
{
get { return _ExtraArgs; }
set { _ExtraArgs = value; }
}
private DockState m_LastDockstate = DockState.Document;
[XmlIgnore]
public DockState LastDockstate
{
get { return m_LastDockstate; }
set { m_LastDockstate = value; }
}
private bool m_AutoStartSession = false;
[XmlIgnore]
public bool AutoStartSession
{
get { return m_AutoStartSession; }
set { m_AutoStartSession = value; }
}
/// <summary>Construct a new session data object</summary>
/// <param name="sessionName">A string representing the name of the session</param>
/// <param name="hostName">The hostname or ip address of the remote host</param>
/// <param name="port">The port on the remote host</param>
/// <param name="protocol">The protocol to use when connecting to the remote host</param>
/// <param name="sessionConfig">the name of the saved configuration settings from putty to use</param>
public SessionData(string sessionName, string hostName, int port, ConnectionProtocol protocol, string sessionConfig)
{
SessionName = sessionName;
Host = hostName;
Port = port;
Proto = protocol;
PuttySession = sessionConfig;
}
/// <summary>Default constructor, instantiate a new <seealso cref="SessionData"/> object</summary>
public SessionData()
{
}
/// <summary>Read any existing saved sessions from the registry, decode and populate a list containing the data</summary>
/// <returns>A list containing the configuration entries retrieved from the registry</returns>
public static List<SessionData> LoadSessionsFromRegistry()
{
Log.Info("LoadSessionsFromRegistry...");
List<SessionData> sessionList = new List<SessionData>();
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Jim Radford\SuperPuTTY\Sessions");
if (key != null)
{
string[] sessionKeys = key.GetSubKeyNames();
foreach (string session in sessionKeys)
{
SessionData sessionData = new SessionData();
RegistryKey itemKey = key.OpenSubKey(session);
if (itemKey != null)
{
sessionData.Host = (string)itemKey.GetValue("Host", "");
sessionData.Port = (int)itemKey.GetValue("Port", 22);
sessionData.Proto = (ConnectionProtocol)Enum.Parse(typeof(ConnectionProtocol), (string)itemKey.GetValue("Proto", "SSH"));
sessionData.PuttySession = (string)itemKey.GetValue("PuttySession", "Default Session");
sessionData.SessionName = session;
sessionData.SessionId = (string)itemKey.GetValue("SessionId", session);
sessionData.Username = (string)itemKey.GetValue("Login", "");
sessionData.LastDockstate = (DockState)itemKey.GetValue("Last Dock", DockState.Document);
sessionData.AutoStartSession = bool.Parse((string)itemKey.GetValue("Auto Start", "False"));
sessionList.Add(sessionData);
}
}
}
return sessionList;
}
/// <summary>Load session configuration data from the specified XML file</summary>
/// <param name="fileName">The filename containing the settings</param>
/// <returns>A <seealso cref="List"/> containing the session configuration data</returns>
public static List<SessionData> LoadSessionsFromFile(string fileName)
{
List<SessionData> sessions = new List<SessionData>();
if (File.Exists(fileName))
{
WorkaroundCygwinBug();
XmlSerializer s = new XmlSerializer(sessions.GetType());
using (TextReader r = new StreamReader(fileName))
{
sessions = (List<SessionData>)s.Deserialize(r);
}
Log.InfoFormat("Loaded {0} sessions from {1}", sessions.Count, fileName);
}
else
{
Log.WarnFormat("Could not load sessions, file doesn't exist. file={0}", fileName);
}
return sessions;
}
static void WorkaroundCygwinBug()
{
try
{
// work around known bug with cygwin
Dictionary<string, string> envVars = new Dictionary<string, string>();
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
{
string envVar = (string) de.Key;
if (envVars.ContainsKey(envVar.ToUpper()))
{
// duplicate found... (e.g. TMP and tmp)
Log.DebugFormat("Clearing duplicate envVariable, {0}", envVar);
Environment.SetEnvironmentVariable(envVar, null);
continue;
}
envVars.Add(envVar.ToUpper(), envVar);
}
}
catch (Exception ex)
{
Log.WarnFormat("Error working around cygwin issue: {0}", ex.Message);
}
}
/// <summary>Save session configuration to the specified XML file</summary>
/// <param name="sessions">A <seealso cref="List"/> containing the session configuration data</param>
/// <param name="fileName">A path to a filename to save the data in</param>
public static void SaveSessionsToFile(List<SessionData> sessions, string fileName)
{
Log.InfoFormat("Saving {0} sessions to {1}", sessions.Count, fileName);
BackUpFiles(fileName, 20);
// sort and save file
sessions.Sort();
XmlSerializer s = new XmlSerializer(sessions.GetType());
using (TextWriter w = new StreamWriter(fileName))
{
s.Serialize(w, sessions);
}
}
private static void BackUpFiles(string fileName, int count)
{
if (File.Exists(fileName) && count > 0)
{
try
{
// backup
string fileBaseName = Path.GetFileNameWithoutExtension(fileName);
string dirName = Path.GetDirectoryName(fileName);
string backupName = Path.Combine(dirName, string.Format("{0}.{1:yyyyMMdd_hhmmss}.XML", fileBaseName, DateTime.Now));
File.Copy(fileName, backupName, true);
// limit last count saves
List<string> oldFiles = new List<string>(Directory.GetFiles(dirName, fileBaseName + ".*.XML"));
oldFiles.Sort();
oldFiles.Reverse();
if (oldFiles.Count > count)
{
for (int i = 20; i < oldFiles.Count; i++)
{
Log.InfoFormat("Cleaning up old file, {0}", oldFiles[i]);
File.Delete(oldFiles[i]);
}
}
}
catch (Exception ex)
{
Log.Error("Error backing up files", ex);
}
}
}
public int CompareTo(object obj)
{
SessionData s = obj as SessionData;
return s == null ? 1 : this.SessionId.CompareTo(s.SessionId);
}
public static string CombineSessionIds(string parent, string child)
{
if (parent == null && child == null)
{
return null;
}
else if (child == null)
{
return parent;
}
else if (parent == null)
{
return child;
}
else
{
return parent + "/" + child;
}
}
public static string GetSessionNameFromId(string sessionId)
{
string[] parts = GetSessionNameParts(sessionId);
return parts.Length > 0 ? parts[parts.Length - 1] : sessionId;
}
/// <summary>Split the SessionID into its parent/child parts</summary>
/// <param name="sessionId">The SessionID</param>
/// <returns>A string array containing the individual path components</returns>
public static string[] GetSessionNameParts(string sessionId)
{
return sessionId.Split('/');
}
/// <summary>Get the parent ID of the specified session</summary>
/// <param name="sessionId">the ID of the session</param>
/// <returns>A string containing the parent sessions ID</returns>
public static string GetSessionParentId(string sessionId)
{
string parentPath = null;
if (sessionId != null)
{
int idx = sessionId.LastIndexOf('/');
if (idx != -1)
{
parentPath = sessionId.Substring(0, idx);
}
}
return parentPath;
}
/// <summary>Create a deep copy of the SessionData object</summary>
/// <returns>A clone of the <seealso cref="SessionData"/> object</returns>
public object Clone()
{
SessionData session = new SessionData();
foreach (PropertyInfo pi in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (pi.CanWrite)
{
pi.SetValue(session, pi.GetValue(this, null), null);
}
}
return session;
}
/// <summary>Return a string containing a uri to the protocol://host:port of this sesssions defined host</summary>
/// <returns>A string in uri format containing connection information to this sessions host</returns>
public override string ToString()
{
if (this.Proto == ConnectionProtocol.Cygterm || this.Proto == ConnectionProtocol.Mintty)
{
return string.Format("{0}://{1}", this.Proto.ToString().ToLower(), this.Host);
}
else
{
return string.Format("{0}://{1}:{2}", this.Proto.ToString().ToLower(), this.Host, this.Port);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
internal sealed unsafe class SocketAsyncEngine
{
//
// Encapsulates a particular SocketAsyncContext object's access to a SocketAsyncEngine.
//
public readonly struct Token
{
private readonly SocketAsyncEngine _engine;
private readonly IntPtr _handle;
public Token(SocketAsyncContext context)
{
AllocateToken(context, out _engine, out _handle);
}
public bool WasAllocated
{
get { return _engine != null; }
}
public void Free()
{
if (WasAllocated)
{
_engine.FreeHandle(_handle);
}
}
public bool TryRegister(SafeCloseSocket socket, out Interop.Error error)
{
Debug.Assert(WasAllocated, "Expected WasAllocated to be true");
return _engine.TryRegister(socket, _handle, out error);
}
}
private const int EventBufferCount =
#if DEBUG
32;
#else
1024;
#endif
private static readonly object s_lock = new object();
// In debug builds, force there to be 2 engines. In release builds, use half the number of processors when
// there are at least 6. The lower bound is to avoid using multiple engines on systems which aren't servers.
private static readonly int EngineCount =
#if DEBUG
2;
#else
Environment.ProcessorCount >= 6 ? Environment.ProcessorCount / 2 : 1;
#endif
//
// The current engines. We replace an engine when it runs out of "handle" values.
// Must be accessed under s_lock.
//
private static readonly SocketAsyncEngine[] s_currentEngines = new SocketAsyncEngine[EngineCount];
private static int s_allocateFromEngine = 0;
private readonly IntPtr _port;
private readonly Interop.Sys.SocketEvent* _buffer;
//
// The read and write ends of a native pipe, used to signal that this instance's event loop should stop
// processing events.
//
private readonly int _shutdownReadPipe;
private readonly int _shutdownWritePipe;
//
// Each SocketAsyncContext is associated with a particular "handle" value, used to identify that
// SocketAsyncContext when events are raised. These handle values are never reused, because we do not have
// a way to ensure that we will never see an event for a socket/handle that has been freed. Instead, we
// allocate monotonically increasing handle values up to some limit; when we would exceed that limit,
// we allocate a new SocketAsyncEngine (and thus a new event port) and start the handle values over at zero.
// Thus we can uniquely identify a given SocketAsyncContext by the *pair* {SocketAsyncEngine, handle},
// and avoid any issues with misidentifying the target of an event we read from the port.
//
#if DEBUG
//
// In debug builds, force rollover to new SocketAsyncEngine instances so that code doesn't go untested, since
// it's very unlikely that the "real" limits will ever be reached in test code.
//
private static readonly IntPtr MaxHandles = (IntPtr)(EventBufferCount * 2);
#else
//
// In release builds, we use *very* high limits. No 64-bit process running on release builds should ever
// reach the handle limit for a single event port, and even 32-bit processes should see this only very rarely.
//
private static readonly IntPtr MaxHandles = IntPtr.Size == 4 ? (IntPtr)int.MaxValue : (IntPtr)long.MaxValue;
#endif
private static readonly IntPtr MinHandlesForAdditionalEngine = EngineCount == 1 ? MaxHandles : (IntPtr)32;
//
// Sentinel handle value to identify events from the "shutdown pipe," used to signal an event loop to stop
// processing events.
//
private static readonly IntPtr ShutdownHandle = (IntPtr)(-1);
//
// The next handle value to be allocated for this event port.
// Must be accessed under s_lock.
//
private IntPtr _nextHandle;
//
// Count of handles that have been allocated for this event port, but not yet freed.
// Must be accessed under s_lock.
//
private IntPtr _outstandingHandles;
//
// Maps handle values to SocketAsyncContext instances.
// Must be accessed under s_lock.
//
private readonly Dictionary<IntPtr, SocketAsyncContext> _handleToContextMap = new Dictionary<IntPtr, SocketAsyncContext>();
//
// True if we've reached the handle value limit for this event port, and thus must allocate a new event port
// on the next handle allocation.
//
private bool IsFull { get { return _nextHandle == MaxHandles; } }
// True if we've don't have sufficient active sockets to allow allocating a new engine.
private bool HasLowNumberOfSockets
{
get
{
return IntPtr.Size == 4 ? _outstandingHandles.ToInt32() < MinHandlesForAdditionalEngine.ToInt32() :
_outstandingHandles.ToInt64() < MinHandlesForAdditionalEngine.ToInt64();
}
}
//
// Allocates a new {SocketAsyncEngine, handle} pair.
//
private static void AllocateToken(SocketAsyncContext context, out SocketAsyncEngine engine, out IntPtr handle)
{
lock (s_lock)
{
engine = s_currentEngines[s_allocateFromEngine];
if (engine == null)
{
// We minimize the number of engines on applications that have a low number of concurrent sockets.
for (int i = 0; i < s_allocateFromEngine; i++)
{
var previousEngine = s_currentEngines[i];
if (previousEngine == null || previousEngine.HasLowNumberOfSockets)
{
s_allocateFromEngine = i;
engine = previousEngine;
break;
}
}
if (engine == null)
{
s_currentEngines[s_allocateFromEngine] = engine = new SocketAsyncEngine();
}
}
handle = engine.AllocateHandle(context);
if (engine.IsFull)
{
// We'll need to create a new event port for the next handle.
s_currentEngines[s_allocateFromEngine] = null;
}
// Round-robin to the next engine once we have sufficient sockets on this one.
if (!engine.HasLowNumberOfSockets)
{
s_allocateFromEngine = (s_allocateFromEngine + 1) % EngineCount;
}
}
}
private IntPtr AllocateHandle(SocketAsyncContext context)
{
Debug.Assert(Monitor.IsEntered(s_lock), "Expected s_lock to be held");
Debug.Assert(!IsFull, "Expected !IsFull");
IntPtr handle = _nextHandle;
_handleToContextMap.Add(handle, context);
_nextHandle = IntPtr.Add(_nextHandle, 1);
_outstandingHandles = IntPtr.Add(_outstandingHandles, 1);
Debug.Assert(handle != ShutdownHandle, $"Expected handle != ShutdownHandle: {handle}");
return handle;
}
private void FreeHandle(IntPtr handle)
{
Debug.Assert(handle != ShutdownHandle, $"Expected handle != ShutdownHandle: {handle}");
bool shutdownNeeded = false;
lock (s_lock)
{
if (_handleToContextMap.Remove(handle))
{
_outstandingHandles = IntPtr.Subtract(_outstandingHandles, 1);
Debug.Assert(_outstandingHandles.ToInt64() >= 0, $"Unexpected _outstandingHandles: {_outstandingHandles}");
//
// If we've allocated all possible handles for this instance, and freed them all, then
// we don't need the event loop any more, and can reclaim resources.
//
if (IsFull && _outstandingHandles == IntPtr.Zero)
{
shutdownNeeded = true;
}
}
}
//
// Signal shutdown outside of the lock to reduce contention.
//
if (shutdownNeeded)
{
RequestEventLoopShutdown();
}
}
private SocketAsyncContext GetContextFromHandle(IntPtr handle)
{
Debug.Assert(handle != ShutdownHandle, $"Expected handle != ShutdownHandle: {handle}");
Debug.Assert(handle.ToInt64() < MaxHandles.ToInt64(), $"Unexpected values: handle={handle}, MaxHandles={MaxHandles}");
lock (s_lock)
{
SocketAsyncContext context;
_handleToContextMap.TryGetValue(handle, out context);
return context;
}
}
private SocketAsyncEngine()
{
_port = (IntPtr)(-1);
_shutdownReadPipe = -1;
_shutdownWritePipe = -1;
try
{
//
// Create the event port and buffer
//
if (Interop.Sys.CreateSocketEventPort(out _port) != Interop.Error.SUCCESS)
{
throw new InternalException();
}
if (Interop.Sys.CreateSocketEventBuffer(EventBufferCount, out _buffer) != Interop.Error.SUCCESS)
{
throw new InternalException();
}
//
// Create the pipe for signaling shutdown, and register for "read" events for the pipe. Now writing
// to the pipe will send an event to the event loop.
//
int* pipeFds = stackalloc int[2];
if (Interop.Sys.Pipe(pipeFds, Interop.Sys.PipeFlags.O_CLOEXEC) != 0)
{
throw new InternalException();
}
_shutdownReadPipe = pipeFds[Interop.Sys.ReadEndOfPipe];
_shutdownWritePipe = pipeFds[Interop.Sys.WriteEndOfPipe];
if (Interop.Sys.TryChangeSocketEventRegistration(_port, (IntPtr)_shutdownReadPipe, Interop.Sys.SocketEvents.None, Interop.Sys.SocketEvents.Read, ShutdownHandle) != Interop.Error.SUCCESS)
{
throw new InternalException();
}
//
// Start the event loop on its own thread.
//
Task.Factory.StartNew(
EventLoop,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
catch
{
FreeNativeResources();
throw;
}
}
private void EventLoop()
{
try
{
bool shutdown = false;
while (!shutdown)
{
int numEvents = EventBufferCount;
Interop.Error err = Interop.Sys.WaitForSocketEvents(_port, _buffer, &numEvents);
if (err != Interop.Error.SUCCESS)
{
throw new InternalException();
}
// The native shim is responsible for ensuring this condition.
Debug.Assert(numEvents > 0, $"Unexpected numEvents: {numEvents}");
for (int i = 0; i < numEvents; i++)
{
IntPtr handle = _buffer[i].Data;
if (handle == ShutdownHandle)
{
shutdown = true;
}
else
{
SocketAsyncContext context = GetContextFromHandle(handle);
if (context != null)
{
context.HandleEvents(_buffer[i].Events);
}
}
}
}
FreeNativeResources();
}
catch (Exception e)
{
Environment.FailFast("Exception thrown from SocketAsyncEngine event loop: " + e.ToString(), e);
}
}
private void RequestEventLoopShutdown()
{
//
// Write to the pipe, which will wake up the event loop and cause it to exit.
//
byte b = 1;
int bytesWritten = Interop.Sys.Write(_shutdownWritePipe, &b, 1);
if (bytesWritten != 1)
{
throw new InternalException();
}
}
private void FreeNativeResources()
{
if (_shutdownReadPipe != -1)
{
Interop.Sys.Close((IntPtr)_shutdownReadPipe);
}
if (_shutdownWritePipe != -1)
{
Interop.Sys.Close((IntPtr)_shutdownWritePipe);
}
if (_buffer != null)
{
Interop.Sys.FreeSocketEventBuffer(_buffer);
}
if (_port != (IntPtr)(-1))
{
Interop.Sys.CloseSocketEventPort(_port);
}
}
private bool TryRegister(SafeCloseSocket socket, IntPtr handle, out Interop.Error error)
{
error = Interop.Sys.TryChangeSocketEventRegistration(_port, socket, Interop.Sys.SocketEvents.None,
Interop.Sys.SocketEvents.Read | Interop.Sys.SocketEvents.Write, handle);
return error == Interop.Error.SUCCESS;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using com.calitha.goldparser;
using System.Data;
using Epi.Data;
using EpiInfo.Plugin;
namespace Epi.Core.AnalysisInterpreter.Rules
{
public class Rule_Relate : AnalysisRule
{
// <Relate_Epi_Table_Statement>
// ::= RELATE <Qualified ID> <JoinOpt>
// <Relate_Table_Statement>
// ::= RELATE <Qualified ID> <KeyDef> <JoinOpt>
// | RELATE File ':' <Qualified ID> <JoinOpt>
// | RELATE BraceString ':' <Qualified ID> <JoinOpt>
// | RELATE File ':' <Qualified ID> <KeyDef> <JoinOpt>
// | RELATE BraceString ':' <Qualified ID> <KeyDef> <JoinOpt>
// <Relate_Db_Table_Statement>
// ::= RELATE <ReadOpt> File <LinkName> <KeyDef> <JoinOpt>
// <Relate_Db_Table_With_Identifier_Statement>
// ::= RELATE <ReadOpt> File ':' Identifier <LinkName> <KeyDef> <JoinOpt>
// <Relate_File_Statement>
// ::= RELATE <ReadOpt> File <LinkName> <KeyDef> <JoinOpt> <FileSpec>
// <Relate_Excel_File_Statement>
// ::= RELATE <ReadOpt> File ExcelRange <LinkName> <KeyDef> <JoinOpt> <FileSpec>
// <JoinOpt>
// ::= MATCHING
// | ALL
// | !Null
private bool _hasRun = false;
private string _readOpts = string.Empty;
private string _filePath = string.Empty;
private string _identifier = string.Empty;
private string _linkName = string.Empty;
private string _keyDef = string.Empty;
private List<string> _joinOpts = new List<string>();
public Rule_Relate(Rule_Context context, NonterminalToken nonterminal)
: base(context)
{
foreach (Token token in nonterminal.Tokens)
{
if (token is NonterminalToken)
{
NonterminalToken nextNonterminal = (NonterminalToken)token;
switch (nextNonterminal.Symbol.ToString())
{
case "<Qualified ID>":
_identifier = SetQualifiedId(nextNonterminal);
break;
case "<KeyDef>":
case "<KeyExprIdentifier>":
_keyDef = ExtractTokens(nextNonterminal.Tokens).Trim();
break;
case "<JoinOpt>":
_joinOpts.AddRange(ExtractTokens(nextNonterminal.Tokens).ToUpperInvariant().Split(StringLiterals.SPACE.ToCharArray()));
break;
}
}
else
{
TerminalToken nextTerminal = (TerminalToken)token;
switch (nextTerminal.Symbol.ToString())
{
case "BraceString":
_filePath = nextTerminal.Text.Trim(new char[] { '{', '}' });
break;
case "File":
_filePath = nextTerminal.Text.Trim(new char[] { '\'', '"' });
break;
}
}
}
}
/// <summary>
/// performs execution of the RELATE command
/// </summary>
/// <returns>object</returns>
public override object Execute()
{
object result = null;
if (false == _hasRun)
{
try
{
if (string.IsNullOrEmpty(_filePath))
{
_filePath = Context.CurrentRead.File;
}
string[] keySet = _keyDef.Replace(" . ", ".").Split(new string[] { " AND " }, StringSplitOptions.RemoveEmptyEntries);
List<string> outputKeys = new List<string>();
List<string> relatedKeys = new List<string>();
foreach (string key in keySet)
{
string[] temp = key.Split(new string[] { " :: " }, StringSplitOptions.RemoveEmptyEntries);
outputKeys.Add(temp[0].Trim(new char[] { '[', ']' }));
relatedKeys.Add(temp[1].Trim(new char[] { '[', ']' }));
}
Context.GetOutput();
DataTable outputTable = Context.DataSet.Tables["output"];
DataTable relatedTable = GetDataTable(_filePath, _identifier);
Context.ReadDataSource(relatedTable);
relatedTable.TableName = "related";
DataTable combinedTable = JoinRelatedTables(outputTable, relatedTable, outputKeys, relatedKeys, _joinOpts);
Context.DataSet.Tables.Remove("Output");
Context.DataSet.Tables.Add(combinedTable);
if (Context.DataSet.Tables.Contains("datasource"))
{
Context.DataSet.Tables.Remove("datasource");
}
DataTable datasouceTable = new DataTable("datasource");
foreach (DataColumn column in combinedTable.Columns)
{
if (!Context.DataSet.Tables["variables"].Columns.Contains(column.ColumnName))
{
DataColumn newColumn = new DataColumn(column.ColumnName);
newColumn.DataType = column.DataType;
datasouceTable.Columns.Add(newColumn);
}
}
Context.DataSet.Tables.Add(datasouceTable);
Dictionary<string, string> args = new Dictionary<string, string>();
args.Add("COMMANDNAME", CommandNames.RELATE);
args.Add("FILENAME", Context.CurrentRead.File);
args.Add("TABLENAME", Context.CurrentRead.Identifier);
Context.CurrentRead.RelatedTables.Add(_identifier);
args.Add("ROWCOUNT", combinedTable.Rows.Count.ToString());
Context.AnalysisCheckCodeInterface.Display(args);
}
catch (DuplicateNameException exception)
{
throw new Exception(exception.Message);
}
catch (GeneralException exception)
{
throw new GeneralException(exception.Message);
}
catch
{
throw new Exception(SharedStrings.CANNOT_DETERMINE_RELATIONSHIP);
}
_hasRun = true;
}
return result;
}
private int GetRecordCount(string filePath, string identifier)
{
int recordCount = 0;
if (filePath.ToUpperInvariant().StartsWith("CONFIG:"))
{
string[] datakey = filePath.Split(':');
string ConnectionString = null;
Configuration config = Configuration.GetNewInstance();
for (int i = 0; i < config.RecentDataSources.Count; i++)
{
Epi.DataSets.Config.RecentDataSourceRow row = config.RecentDataSources[i];
if (row.Name.ToUpperInvariant() == datakey[1].ToUpperInvariant())
{
ConnectionString = Configuration.Decrypt(row.ConnectionString);
break;
}
}
filePath = ConnectionString;
}
string[] Identifiers = identifier.Split('.');
StringBuilder IdentifierBuilder = new StringBuilder();
for (int i = 0; i < Identifiers.Length; i++)
{
IdentifierBuilder.Append("[");
IdentifierBuilder.Append(Identifiers[i]);
IdentifierBuilder.Append("].");
}
IdentifierBuilder.Length = IdentifierBuilder.Length - 1;
if (DBReadExecute.ProjectFileName != "")
{
if (Context.CurrentProject.Views.Exists(identifier))
{
recordCount = (int)DBReadExecute.GetScalar(filePath, "SELECT COUNT(*) FROM " + Context.CurrentProject.Views[identifier].TableName);
}
else
{
recordCount = (int)DBReadExecute.GetScalar(filePath, "SELECT COUNT(*) FROM " + IdentifierBuilder.ToString());
}
}
else
{
recordCount = (int)DBReadExecute.GetScalar(filePath, "SELECT COUNT(*) FROM " + IdentifierBuilder.ToString());
}
return recordCount;
}
private DataTable GetDataTable(string filePath, string identifier)
{
System.Data.DataTable table;
if (filePath.ToUpperInvariant().StartsWith("CONFIG:"))
{
string[] datakey = filePath.Split(':');
string connectionString = null;
Configuration config = Configuration.GetNewInstance();
for (int i = 0; i < config.RecentDataSources.Count; i++)
{
Epi.DataSets.Config.RecentDataSourceRow row = config.RecentDataSources[i];
if (row.Name.ToUpperInvariant() == datakey[1].ToUpperInvariant())
{
connectionString = Configuration.Decrypt(row.ConnectionString);
break;
}
}
filePath = connectionString;
}
string[] Identifiers = identifier.Split('.');
StringBuilder IdentifierBuilder = new StringBuilder();
for (int i = 0; i < Identifiers.Length; i++)
{
IdentifierBuilder.Append("[");
IdentifierBuilder.Append(Identifiers[i]);
IdentifierBuilder.Append("].");
}
IdentifierBuilder.Length = IdentifierBuilder.Length - 1;
if (DBReadExecute.ProjectFileName != "")
{
if (Context.CurrentProject.Views.Exists(identifier))
{
string selectStatement = "Select * From [" + identifier + "]";
table = DBReadExecute.GetDataTable(Context.CurrentRead.File, selectStatement);
foreach (Page page in Context.CurrentProject.Views[identifier].Pages)
{
DataTable pageTable = DBReadExecute.GetDataTable(Context.CurrentRead.File, "Select * From [" + page.TableName + "]");
table = JoinPagesTables(table, pageTable);
}
}
else
{
if (filePath.EndsWith(".prj"))
{
Epi.Data.IDbDriver driver = DBReadExecute.GetDataDriver(filePath);
table = driver.GetTableData(identifier);
DataTable pageTables = DBReadExecute.GetDataTable(driver, "Select DISTINCT PageId FROM metaFields Where DataTableName = '" + identifier + "' AND PageId <> null");
foreach (DataRow row in pageTables.Rows)
{
DataTable pageTable = driver.GetTableData(identifier + row["PageId"]);
table = JoinPagesTables(table, pageTable);
}
}
else
table = DBReadExecute.GetDataTable(filePath, "Select * FROM " + IdentifierBuilder.ToString());
}
}
else
{
if (filePath.EndsWith(".prj"))
{
Epi.Data.IDbDriver driver = DBReadExecute.GetDataDriver(filePath);
table = driver.GetTableData(identifier);
DataTable pageTables = DBReadExecute.GetDataTable(driver, "Select DISTINCT PageId FROM metaFields Where DataTableName = '" + identifier + "' AND PageId <> null");
foreach (DataRow row in pageTables.Rows)
{
DataTable pageTable = driver.GetTableData(identifier + row["PageId"]);
table = JoinPagesTables(table, pageTable);
}
}
else
{
table = DBReadExecute.GetDataTable(filePath, "Select * from " + IdentifierBuilder.ToString());
}
}
return table;
}
public DataTable JoinPagesTables(DataTable recStatusTable, DataTable pageTable)
{
DataTable result = new DataTable("Output");
using (DataSet set = new DataSet())
{
set.Tables.AddRange(new DataTable[] { recStatusTable.Copy(), pageTable.Copy() });
DataColumn parentColumn = set.Tables[0].Columns["GlobalRecordId"];
DataColumn childColumn = set.Tables[1].Columns["GlobalRecordId"];
DataRelation dataRelation = new DataRelation(string.Empty, parentColumn, childColumn, false);
set.Relations.Add(dataRelation);
for (int i = 0; i < recStatusTable.Columns.Count; i++)
{
result.Columns.Add(recStatusTable.Columns[i].ColumnName, recStatusTable.Columns[i].DataType);
}
for (int i = 0; i < pageTable.Columns.Count; i++)
{
bool isDataField = (
pageTable.Columns[i].ColumnName.Equals("RecStatus", StringComparison.CurrentCultureIgnoreCase) ||
pageTable.Columns[i].ColumnName.Equals("FKEY", StringComparison.CurrentCultureIgnoreCase) ||
pageTable.Columns[i].ColumnName.Equals("GlobalRecordId", StringComparison.CurrentCultureIgnoreCase
)) == false;
if ( isDataField )
{
if (result.Columns.Contains(pageTable.Columns[i].ColumnName) == false)
{
result.Columns.Add(pageTable.Columns[i].ColumnName, pageTable.Columns[i].DataType);
}
else
{
int count = 0;
foreach (DataColumn column in result.Columns)
{
if (column.ColumnName.StartsWith(pageTable.Columns[i].ColumnName))
{
count++;
}
}
result.Columns.Add(pageTable.Columns[i].ColumnName + count.ToString(), recStatusTable.Columns[i].DataType);
}
}
}
foreach (DataRow parentRow in set.Tables[0].Rows)
{
DataRow resultRow = result.NewRow();
DataRow[] childRow = parentRow.GetChildRows(dataRelation);
if (childRow != null && childRow.Length > 0)
{
foreach (DataColumn dataColumn in pageTable.Columns)
{
resultRow[dataColumn.ColumnName] = childRow[0][dataColumn.ColumnName];
}
foreach (DataColumn dataColumn in recStatusTable.Columns)
{
resultRow[dataColumn.ColumnName] = parentRow[dataColumn.ColumnName];
}
result.Rows.Add(resultRow);
}
}
result.AcceptChanges();
}
return result;
}
private Type ReturnWideDataType(object objOne, object objTwo)
{
Type returnType = objOne.GetType();
return returnType;
}
private static Type ResolveType(string typeString)
{
int commaIndex = typeString.IndexOf(",");
string className = typeString.Substring(0, commaIndex).Trim();
string assemblyName = typeString.Substring(commaIndex + 1).Trim();
System.Reflection.Assembly assembly = null;
try
{
assembly = System.Reflection.Assembly.Load(assemblyName);
}
catch
{
try
{
assembly = System.Reflection.Assembly.LoadWithPartialName(assemblyName);
}
catch
{
throw new ArgumentException("Can't load assembly " + assemblyName);
}
}
return assembly.GetType(className, false, false);
}
private bool ColumnDataTypesMatch(DataTable parentTable, DataTable childTable, List<string> parentKeys, List<string> childKeys)
{
bool[] dataColumTypesSame = new bool[parentKeys.Count];
List<string> nameDashType = new List<string>();
using (DataSet ds = new DataSet())
{
ds.Tables.AddRange(new DataTable[] { parentTable.Copy(), childTable.Copy() });
DataColumn[] parentColumns = new DataColumn[parentKeys.Count];
DataColumn[] childColumns = new DataColumn[childKeys.Count];
for (int i = 0; i < parentColumns.Length; i++)
{
if (false == parentTable.Columns.Contains(parentKeys[i]))
{
throw new GeneralException(string.Format("The table does not contain the column ({0}).", parentKeys[i]));
}
parentColumns[i] = ds.Tables[0].Columns[parentKeys[i]];
childColumns[i] = ds.Tables[1].Columns[childKeys[i]];
dataColumTypesSame[i] = ((DataColumn)parentColumns[i]).DataType == ((DataColumn)childColumns[i]).DataType;
nameDashType.Add(string.Format("{0} is a(n) {1}", parentColumns[i], ((DataColumn)parentColumns[i]).DataType.Name));
}
for (int i = 0; i < dataColumTypesSame.Length; i++)
{
if (dataColumTypesSame[i] == false)
{
string items = string.Empty;
foreach (string item in nameDashType)
{
items += item + Environment.NewLine;
}
string message = string.Format("The data types of the columns selected in the relate command are too dissimilar to join with.{0}{0}{1}", Environment.NewLine, items);
throw new GeneralException(message);
}
}
return true;
}
}
protected DataTable JoinRelatedTables(DataTable parentTable, DataTable childTable, List<string> parentKeys, List<string> childKeys, List<string> options)
{
DataTable result = new DataTable("Output");
using (DataSet dataSet = new DataSet())
{
dataSet.Tables.AddRange(new DataTable[] { parentTable.Copy(), childTable.Copy() });
DataColumn[] parentColumns = new DataColumn[parentKeys.Count];
DataColumn[] childColumns = new DataColumn[childKeys.Count];
for (int i = 0; i < parentColumns.Length; i++)
{
parentColumns[i] = dataSet.Tables[0].Columns[parentKeys[i]];
}
for (int i = 0; i < childColumns.Length; i++)
{
childColumns[i] = dataSet.Tables[1].Columns[childKeys[i]];
}
if (false == ColumnDataTypesMatch( parentTable, childTable, parentKeys, childKeys))
{
}
DataRelation relation = new DataRelation(string.Empty, parentColumns, childColumns, false);
dataSet.Relations.Add(relation);
for (int i = 0; i < parentTable.Columns.Count; i++)
{
bool isDataField = (
parentTable.Columns[i].ColumnName.Equals("FirstSaveLogonName", StringComparison.CurrentCultureIgnoreCase) ||
parentTable.Columns[i].ColumnName.Equals("FirstSaveTime", StringComparison.CurrentCultureIgnoreCase) ||
parentTable.Columns[i].ColumnName.Equals("LastSaveLogonName", StringComparison.CurrentCultureIgnoreCase) ||
parentTable.Columns[i].ColumnName.Equals("LastSaveTime", StringComparison.CurrentCultureIgnoreCase) ||
parentTable.Columns[i].ColumnName.Equals("RecStatus", StringComparison.CurrentCultureIgnoreCase) ||
parentTable.Columns[i].ColumnName.Equals("FKEY", StringComparison.CurrentCultureIgnoreCase) ||
parentTable.Columns[i].ColumnName.Equals("GlobalRecordId", StringComparison.CurrentCultureIgnoreCase
)) == false;
if (isDataField)
{
result.Columns.Add(parentTable.Columns[i].ColumnName, parentTable.Columns[i].DataType);
}
else
{
if (Context.CurrentRead.RelatedTables.Count == 0)
{
result.Columns.Add(Context.CurrentRead.Identifier + "_" + parentTable.Columns[i].ColumnName, parentTable.Columns[i].DataType);
}
else
{
result.Columns.Add(Context.CurrentRead.RelatedTables[Context.CurrentRead.RelatedTables.Count - 1] + "_" + parentTable.Columns[i].ColumnName, parentTable.Columns[i].DataType);
}
}
}
for (int i = 0; i < childTable.Columns.Count; i++)
{
bool isDataField = (
childTable.Columns[i].ColumnName.Equals("FirstSaveLogonName", StringComparison.CurrentCultureIgnoreCase) ||
childTable.Columns[i].ColumnName.Equals("FirstSaveTime", StringComparison.CurrentCultureIgnoreCase) ||
childTable.Columns[i].ColumnName.Equals("LastSaveLogonName", StringComparison.CurrentCultureIgnoreCase) ||
childTable.Columns[i].ColumnName.Equals("LastSaveTime", StringComparison.CurrentCultureIgnoreCase) ||
childTable.Columns[i].ColumnName.Equals("RecStatus", StringComparison.CurrentCultureIgnoreCase) ||
childTable.Columns[i].ColumnName.Equals("FKEY", StringComparison.CurrentCultureIgnoreCase) ||
childTable.Columns[i].ColumnName.Equals("GlobalRecordId", StringComparison.CurrentCultureIgnoreCase
)) == false;
if (isDataField)
{
if (!result.Columns.Contains(childTable.Columns[i].ColumnName))
{
result.Columns.Add(childTable.Columns[i].ColumnName, childTable.Columns[i].DataType);
}
else
{
int count = 1;
foreach (DataColumn column in result.Columns)
{
if (column.ColumnName.StartsWith(childTable.Columns[i].ColumnName))
{
count++;
}
if (false == result.Columns.Contains(childTable.Columns[i].ColumnName + count.ToString()))
{
break;
}
}
result.Columns.Add(childTable.Columns[i].ColumnName + count.ToString(), childTable.Columns[i].DataType);
}
}
else
{
result.Columns.Add(_identifier + "_" + childTable.Columns[i].ColumnName, childTable.Columns[i].DataType);
}
}
result.BeginLoadData();
foreach (DataRow parentRow in dataSet.Tables[0].Rows)
{
DataRow[] childRows = parentRow.GetChildRows(relation);
if (childRows != null && childRows.Length > 0)
{
object[] parentArray = parentRow.ItemArray;
foreach (DataRow childRow in childRows)
{
object[] childArray = childRow.ItemArray;
object[] joinArray = new object[parentArray.Length + childArray.Length];
Array.Copy(parentArray, 0, joinArray, 0, parentArray.Length);
Array.Copy(childArray, 0, joinArray, parentArray.Length, childArray.Length);
result.LoadDataRow(joinArray, true);
}
}
else if (options.Contains("ALL"))
{
object[] parentArray = parentRow.ItemArray;
object[] joinArray = new object[parentArray.Length];
Array.Copy(parentArray, 0, joinArray, 0, parentArray.Length);
result.LoadDataRow(joinArray, true);
}
}
result.EndLoadData();
}
return result;
}
void worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
Context.AnalysisCheckCodeInterface.ReportIndeterminateTaskEnded();
}
void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
Context.AnalysisCheckCodeInterface.ReportIndeterminateTaskStarted("Buffering data...");
currentDataTable = Context.GetOutput();
}
private List<DataRow> currentDataTable;
}
}
| |
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
#if ENABLE_RAYTRACING
public class HDRaytracingAmbientOcclusion
{
// External structures
RenderPipelineResources m_PipelineResources = null;
RenderPipelineSettings m_PipelineSettings;
HDRaytracingManager m_RaytracingManager = null;
SharedRTManager m_SharedRTManager = null;
// The target denoising kernel
static int m_KernelFilter;
// Intermediate buffer that stores the ambient occlusion pre-denoising
RTHandleSystem.RTHandle m_IntermediateBuffer = null;
RTHandleSystem.RTHandle m_HitDistanceBuffer = null;
RTHandleSystem.RTHandle m_ViewSpaceNormalBuffer = null;
// String values
const string m_RayGenShaderName = "RayGenAmbientOcclusion";
const string m_MissShaderName = "MissShaderAmbientOcclusion";
const string m_ClosestHitShaderName = "ClosestHitMain";
public HDRaytracingAmbientOcclusion()
{
}
public void Init(RenderPipelineResources pipelineResources, RenderPipelineSettings pipelineSettings, HDRaytracingManager raytracingManager, SharedRTManager sharedRTManager)
{
// Keep track of the pipeline asset
m_PipelineSettings = pipelineSettings;
m_PipelineResources = pipelineResources;
// keep track of the ray tracing manager
m_RaytracingManager = raytracingManager;
// Keep track of the shared rt manager
m_SharedRTManager = sharedRTManager;
// Intermediate buffer that holds the pre-denoised texture
m_IntermediateBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite: true, xrInstancing: true, useDynamicScale: true, useMipMap: false, autoGenerateMips: false, name: "IntermediateAOBuffer");
// Buffer that holds the average distance of the rays
m_HitDistanceBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R32_SFloat, enableRandomWrite: true, xrInstancing: true, useDynamicScale: true, useMipMap: false, autoGenerateMips: false, name: "HitDistanceBuffer");
// Buffer that holds the uncompressed normal buffer
m_ViewSpaceNormalBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite: true, xrInstancing: true, useDynamicScale: true, useMipMap: false, autoGenerateMips: false, name: "ViewSpaceNormalBuffer");
}
public void Release()
{
RTHandles.Release(m_ViewSpaceNormalBuffer);
RTHandles.Release(m_HitDistanceBuffer);
RTHandles.Release(m_IntermediateBuffer);
}
static RTHandleSystem.RTHandle AmbientOcclusionHistoryBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem)
{
return rtHandleSystem.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R16_SFloat,
enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, xrInstancing: true,
name: string.Format("AmbientOcclusionHistoryBuffer{0}", frameIndex));
}
public void SetDefaultAmbientOcclusionTexture(CommandBuffer cmd)
{
cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, Texture2D.blackTexture);
cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, Vector4.zero);
}
public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandleSystem.RTHandle outputTexture, ScriptableRenderContext renderContext, uint frameCount)
{
// Let's check all the resources
HDRaytracingEnvironment rtEnvironement = m_RaytracingManager.CurrentEnvironment();
ComputeShader aoFilter = m_PipelineResources.shaders.raytracingAOFilterCS;
RaytracingShader aoShader = m_PipelineResources.shaders.aoRaytracing;
var aoSettings = VolumeManager.instance.stack.GetComponent<AmbientOcclusion>();
// Check if the state is valid for evaluating ambient occlusion
bool invalidState = rtEnvironement == null
|| aoFilter == null || aoShader == null
|| m_PipelineResources.textures.owenScrambledTex == null || m_PipelineResources.textures.scramblingTex == null
|| !(hdCamera.frameSettings.IsEnabled(FrameSettingsField.SSAO) && aoSettings.intensity.value > 0f);
// If any of the previous requirements is missing, the effect is not requested or no acceleration structure, set the default one and leave right away
if (invalidState)
{
SetDefaultAmbientOcclusionTexture(cmd);
return;
}
// Grab the acceleration structure for the target camera
RaytracingAccelerationStructure accelerationStructure = m_RaytracingManager.RequestAccelerationStructure(rtEnvironement.aoLayerMask);
// Define the shader pass to use for the reflection pass
cmd.SetRaytracingShaderPass(aoShader, "VisibilityDXR");
// Set the acceleration structure for the pass
cmd.SetRaytracingAccelerationStructure(aoShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure);
// Inject the ray-tracing sampling data
cmd.SetRaytracingTextureParam(aoShader, m_RayGenShaderName, HDShaderIDs._OwenScrambledTexture, m_PipelineResources.textures.owenScrambledTex);
cmd.SetRaytracingTextureParam(aoShader, m_RayGenShaderName, HDShaderIDs._ScramblingTexture, m_PipelineResources.textures.scramblingTex);
// Inject the ray generation data
cmd.SetRaytracingFloatParams(aoShader, HDShaderIDs._RaytracingRayBias, rtEnvironement.rayBias);
cmd.SetRaytracingFloatParams(aoShader, HDShaderIDs._RaytracingRayMaxLength, rtEnvironement.aoRayLength);
cmd.SetRaytracingIntParams(aoShader, HDShaderIDs._RaytracingNumSamples, rtEnvironement.aoNumSamples);
// Set the data for the ray generation
cmd.SetRaytracingTextureParam(aoShader, m_RayGenShaderName, HDShaderIDs._RaytracingHitDistanceTexture, m_HitDistanceBuffer);
cmd.SetRaytracingTextureParam(aoShader, m_RayGenShaderName, HDShaderIDs._RaytracingVSNormalTexture, m_ViewSpaceNormalBuffer);
cmd.SetRaytracingTextureParam(aoShader, m_RayGenShaderName, HDShaderIDs._AmbientOcclusionTextureRW, m_IntermediateBuffer);
cmd.SetRaytracingTextureParam(aoShader, m_RayGenShaderName, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetRaytracingTextureParam(aoShader, m_RayGenShaderName, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
int frameIndex = hdCamera.IsTAAEnabled() ? hdCamera.taaFrameIndex : (int)frameCount % 8;
cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex);
// Value used to scale the ao intensity
cmd.SetRaytracingFloatParam(aoShader, HDShaderIDs._RaytracingAOIntensity, aoSettings.intensity.value);
cmd.SetRaytracingIntParam(aoShader, HDShaderIDs._RayCountEnabled, m_RaytracingManager.rayCountManager.RayCountIsEnabled());
cmd.SetRaytracingTextureParam(aoShader, m_RayGenShaderName, HDShaderIDs._RayCountTexture, m_RaytracingManager.rayCountManager.rayCountTexture);
// Run the calculus
cmd.DispatchRays(aoShader, m_RayGenShaderName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, 1);
using (new ProfilingSample(cmd, "Filter Reflection", CustomSamplerId.RaytracingAmbientOcclusion.GetSampler()))
{
switch(rtEnvironement.aoFilterMode)
{
case HDRaytracingEnvironment.AOFilterMode.Nvidia:
{
cmd.DenoiseAmbientOcclusionTexture(m_IntermediateBuffer, m_HitDistanceBuffer, m_SharedRTManager.GetDepthStencilBuffer(), m_ViewSpaceNormalBuffer, outputTexture, hdCamera.mainViewConstants.viewMatrix, hdCamera.mainViewConstants.projMatrix, (uint)rtEnvironement.maxFilterWidthInPixels, rtEnvironement.filterRadiusInMeters, rtEnvironement.normalSharpness, 1.0f, 0.0f);
}
break;
case HDRaytracingEnvironment.AOFilterMode.SpatioTemporal:
{
m_KernelFilter = aoFilter.FindKernel("AOCopyTAAHistory");
// Grab the history buffer
RTHandleSystem.RTHandle ambientOcclusionHistory = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RaytracedAmbientOcclusion)
?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedAmbientOcclusion, AmbientOcclusionHistoryBufferAllocatorFunction, 1);
// Texture dimensions
int texWidth = hdCamera.actualWidth;
int texHeight = hdCamera.actualHeight;
// Evaluate the dispatch parameters
int areaTileSize = 8;
int numTilesX = (texWidth + (areaTileSize - 1)) / areaTileSize;
int numTilesY = (texHeight + (areaTileSize - 1)) / areaTileSize;
// Given that we can't read and write into the same buffer, we store the current frame value and the history in the denoisebuffer1
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._AOHistorybufferRW, ambientOcclusionHistory);
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, m_IntermediateBuffer);
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseOutputTextureRW, m_ViewSpaceNormalBuffer);
cmd.DispatchCompute(aoFilter, m_KernelFilter, numTilesX, numTilesY, 1);
m_KernelFilter = aoFilter.FindKernel("AOApplyTAA");
// Apply a vectorized temporal filtering pass and store it back in the denoisebuffer0 with the analytic value in the third channel
var historyScale = new Vector2(hdCamera.actualWidth / (float)ambientOcclusionHistory.rt.width, hdCamera.actualHeight / (float)ambientOcclusionHistory.rt.height);
cmd.SetComputeVectorParam(aoFilter, HDShaderIDs._RTHandleScaleHistory, historyScale);
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, m_ViewSpaceNormalBuffer);
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseOutputTextureRW, m_IntermediateBuffer);
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._AOHistorybufferRW, ambientOcclusionHistory);
cmd.DispatchCompute(aoFilter, m_KernelFilter, numTilesX, numTilesY, 1);
m_KernelFilter = aoFilter.FindKernel("AOBilateralFilterH");
// Horizontal pass of the bilateral filter
cmd.SetComputeIntParam(aoFilter, HDShaderIDs._RaytracingDenoiseRadius, rtEnvironement.aoBilateralRadius);
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, m_IntermediateBuffer);
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseOutputTextureRW, m_ViewSpaceNormalBuffer);
cmd.DispatchCompute(aoFilter, m_KernelFilter, numTilesX, numTilesY, 1);
m_KernelFilter = aoFilter.FindKernel("AOBilateralFilterV");
// Horizontal pass of the bilateral filter
cmd.SetComputeIntParam(aoFilter, HDShaderIDs._RaytracingDenoiseRadius, rtEnvironement.aoBilateralRadius);
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, m_ViewSpaceNormalBuffer);
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
cmd.SetComputeTextureParam(aoFilter, m_KernelFilter, HDShaderIDs._DenoiseOutputTextureRW, outputTexture);
cmd.DispatchCompute(aoFilter, m_KernelFilter, numTilesX, numTilesY, 1);
}
break;
case HDRaytracingEnvironment.AOFilterMode.None:
{
HDUtils.BlitCameraTexture(cmd, m_IntermediateBuffer, outputTexture);
}
break;
}
}
// Bind the textures and the params
cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, outputTexture);
cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, new Vector4(0f, 0f, 0f, VolumeManager.instance.stack.GetComponent<AmbientOcclusion>().directLightingStrength.value));
// TODO: All the push-debug stuff should be centralized somewhere
(RenderPipelineManager.currentPipeline as HDRenderPipeline).PushFullScreenDebugTexture(hdCamera, cmd, outputTexture, FullScreenDebugMode.SSAO);
}
}
#endif
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using DeadCode.WME.HtmlParser;
using System.Web;
namespace hhc2html
{
class Program
{
static int Main(string[] args)
{
if(args.Length < 2)
{
Console.WriteLine("hhc2html, (c) 2013 dead:code");
Console.WriteLine("");
Console.WriteLine("usage:");
Console.WriteLine(" hhc2html path_to_hhc path_to_html [base_path]");
return 1;
}
Program P = new Program();
//if (P.Generate("wme.hhc", @"web\contents.html", "../")) return 0;
if (P.Generate(args[0], args[1], args.Length > 2 ? "../" : ""))
{
Console.WriteLine("File {0} has been generated.", args[1]);
return 0;
}
else return 1;
}
//////////////////////////////////////////////////////////////////////////
private bool Generate(string HHCPath, string HtmlPath, string BasePath)
{
if(!File.Exists(HHCPath))
{
Console.WriteLine("File {0} doesn't exit.", HHCPath);
return false;
}
try
{
Directory.CreateDirectory(Path.GetDirectoryName(HtmlPath));
}
catch(Exception e)
{
Console.WriteLine("Error creating output directory.");
Console.WriteLine(e.Message);
return false;
}
try
{
HtmlParser Parser = new HtmlParser();
HtmlElement[] Elements = Parser.ParseHtml(HHCPath);
Topic RootTopic = ParseHHC(Elements);
GenerateContentsHtml(RootTopic, HtmlPath, BasePath);
}
catch (Exception e)
{
Console.WriteLine("Error parsing file {0}.", HHCPath);
Console.WriteLine(e.Message);
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
private void GenerateContentsHtml(Topic RootTopic, string HtmlPath, string BasePath)
{
using(StreamWriter sw = new StreamWriter(HtmlPath, false, Encoding.UTF8))
{
sw.WriteLine(@"<html>");
sw.WriteLine(@" <head>");
sw.WriteLine(@" <META http-equiv='Content-Type' content='text/html; charset=utf-8'>");
sw.WriteLine(@" <title>Contents</title>");
sw.WriteLine(@" <meta name='GENERATOR' content='hhc2html'>");
sw.WriteLine(@" <link rel='stylesheet' type='text/css' href='tree.css'>");
sw.WriteLine(@" <script src='tree.js' language='javascript' type='text/javascript'>");
sw.WriteLine(@" </script>");
sw.WriteLine(@" </head>");
sw.WriteLine(@" <body id='docBody' style='background-color: #f1f1f1; color: White; margin: 0px 0px 0px 0px;' onload='resizeTree()' onresize='resizeTree()' onselectstart='return false;'>");
//sw.WriteLine(@" <div id='synctoc'><div style='font-family: verdana; font-size: 8pt; cursor: pointer; margin: 6 4 8 2; text-align: right' onmouseover='this.style.textDecoration='underline'' onmouseout='this.style.textDecoration='none'' onclick='syncTree(window.parent.frames[1].document.URL)'>sync toc</div></div>");
sw.WriteLine(@" <div id=""synctoc""><div style=""font-family: verdana; font-size: 8pt; cursor: pointer; text-align: right"" onmouseover=""this.style.textDecoration='underline'"" onmouseout=""this.style.textDecoration='none'"" onclick=""syncTree(window.parent.frames[1].document.URL)"">sync toc</div></div>");
sw.WriteLine(@" <div id='tree' style='top: 35px; left: 0px;' class='treeDiv'>");
sw.WriteLine(@" <div id='treeRoot' onselectstart='return false' ondragstart='return false'>");
foreach(Topic SubTopic in RootTopic.SubTopics)
{
GenerateNode(sw, SubTopic, BasePath, 8);
}
sw.WriteLine(@" </div>");
sw.WriteLine(@" </div>");
sw.WriteLine(@" </body>");
sw.WriteLine(@"</html>");
}
}
//////////////////////////////////////////////////////////////////////////
private void GenerateNode(StreamWriter sw, Topic SubTopic, string BasePath, int Nest)
{
string N = "";
for(int i=0; i<Nest; i++) N += " ";
string Link = SubTopic.Link.Replace('\\', '/');
if (!Link.StartsWith("http://")) Link = BasePath + Link;
sw.WriteLine(N + @"<div class='treeNode'>");
if(SubTopic.SubTopics.Count > 0)
{
sw.WriteLine(N + @" <img src='treenodeplus.gif' class='treeLinkImage' onclick='expandCollapse(this.parentNode)'>");
sw.WriteLine(N + @" <a href='" + Link + "' target='main' class='treeUnselected' onclick='clickAnchor(this)'>" + SubTopic.Name + "</a>");
sw.WriteLine(N + @" <div class='treeSubnodesHidden'>");
foreach(Topic SubSubTopic in SubTopic.SubTopics)
{
GenerateNode(sw, SubSubTopic, BasePath, Nest + 4);
}
sw.WriteLine(N + @" </div>");
}
else
{
sw.WriteLine(N + @" <img src='treenodedot.gif' class='treeNoLinkImage'>");
sw.WriteLine(N + @" <a href='" + Link + "' target='main' class='treeUnselected' onclick='clickAnchor(this)'>" + SubTopic.Name + "</a>");
}
sw.WriteLine(N + @"</div>");
}
//////////////////////////////////////////////////////////////////////////
private Topic ParseHHC(HtmlElement[] Elements)
{
Topic Root = new Topic();
Topic LastTopic = Root;
Topic Parent = null;
foreach(HtmlElement El in Elements)
{
HtmlTag Tag = El as HtmlTag;
if (Tag == null) continue;
// go down one level
if(Tag.Name.ToUpper() == "UL")
{
Parent = LastTopic;
}
// go up one level
if (Tag.Name.ToUpper() == "/UL")
{
Parent = Parent.Parent;
if (Parent == null) break;
}
// current item
if(Tag.Name.ToUpper() == "LI")
{
LastTopic = new Topic();
LastTopic.Parent = Parent;
}
if (Tag.Name.ToUpper() == "/OBJECT")
{
if (LastTopic.Parent != null && LastTopic.Name != "")
LastTopic.Parent.SubTopics.Add(LastTopic);
}
// topic param
if(Tag.Name.ToUpper() == "PARAM")
{
string Name = Tag.GetParamValue("Name");
string Value = Tag.GetParamValue("Value");
switch(Name.ToUpper())
{
case "NAME":
//LastTopic.Name = Value;
LastTopic.Name = HttpUtility.HtmlDecode(Value);
break;
case "LOCAL":
LastTopic.Link = Value;
break;
case "IMAGENUMBER":
LastTopic.Image = int.Parse(Value);
break;
}
}
}
return Root;
}
class Topic
{
public string Name = "";
public string Link = "";
public int Image = -1;
public Topic Parent = null;
public List<Topic> SubTopics = new List<Topic>();
};
}
}
| |
//
// 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 System.IO;
using System.Text;
using Encog.App.Analyst.CSV.Basic;
using Encog.App.Quant;
using Encog.ML;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.Util.CSV;
namespace Encog.App.Analyst.CSV
{
/// <summary>
/// Used by non-analyst programs to evaluate a CSV file.
/// </summary>
public class EvaluateRawCSV : BasicFile
{
/// <summary>
/// The ideal count.
/// </summary>
private int _idealCount;
/// <summary>
/// The input count.
/// </summary>
private int _inputCount;
/// <summary>
/// The output count.
/// </summary>
private int _outputCount;
/// <summary>
/// Analyze the data. This counts the records and prepares the data to be
/// processed.
/// </summary>
/// <param name="inputFile">The input file.</param>
/// <param name="headers">True if headers are present.</param>
/// <param name="format">The format the file is in.</param>
public void Analyze(IMLRegression method, FileInfo inputFile, bool headers, CSVFormat format)
{
InputFilename = inputFile;
ExpectInputHeaders = headers;
Format = format;
Analyzed = true;
PerformBasicCounts();
_inputCount = method.InputCount;
_outputCount = method.OutputCount;
_idealCount = Math.Max(InputHeadings.Length - _inputCount, 0);
if ((InputHeadings.Length != _inputCount)
&& (InputHeadings.Length != (_inputCount + _outputCount)))
{
throw new AnalystError("Invalid number of columns("
+ InputHeadings.Length + "), must match input("
+ _inputCount + ") count or input+output("
+ (_inputCount + _outputCount) + ") count.");
}
}
/// <summary>
/// Prepare the output file, write headers if needed.
/// </summary>
/// <param name="outputFile">The name of the output file.</param>
/// <returns>The output stream for the text file.</returns>
private StreamWriter AnalystPrepareOutputFile(FileInfo outputFile)
{
try
{
var tw = new StreamWriter(outputFile.OpenWrite());
// write headers, if needed
if (ProduceOutputHeaders)
{
var line = new StringBuilder();
// first, handle any input fields
if (_inputCount > 0)
{
for (int i = 0; i < _inputCount; i++)
{
AppendSeparator(line, Format);
line.Append("\"");
line.Append("input:" + i);
line.Append("\"");
}
}
// now, handle the ideal fields
if (_idealCount > 0)
{
for (int i = 0; i < _idealCount; i++)
{
AppendSeparator(line, Format);
line.Append("\"");
line.Append("ideal:" + i);
line.Append("\"");
}
}
// now, handle the output fields
if (_outputCount > 0)
{
for (int i = 0; i < _outputCount; i++)
{
AppendSeparator(line, Format);
line.Append("\"");
line.Append("output:" + i);
line.Append("\"");
}
}
tw.WriteLine(line.ToString());
}
return tw;
}
catch (IOException e)
{
throw new QuantError(e);
}
}
/// <summary>
/// Process the file.
/// </summary>
/// <param name="outputFile">The output file.</param>
/// <param name="method">The method to use.</param>
public void Process(FileInfo outputFile, IMLRegression method)
{
var csv = new ReadCSV(InputFilename.ToString(),
ExpectInputHeaders, Format);
if (method.InputCount > _inputCount)
{
throw new AnalystError("This machine learning method has "
+ method.InputCount
+ " inputs, however, the data has " + _inputCount
+ " inputs.");
}
var input = new BasicMLData(method.InputCount);
StreamWriter tw = AnalystPrepareOutputFile(outputFile);
ResetStatus();
while (csv.Next())
{
UpdateStatus(false);
var row = new LoadedRow(csv, _idealCount);
int dataIndex = 0;
// load the input data
for (int i = 0; i < _inputCount; i++)
{
String str = row.Data[i];
double d = Format.Parse(str);
input[i] = d;
dataIndex++;
}
// do we need to skip the ideal values?
dataIndex += _idealCount;
// compute the result
IMLData output = method.Compute(input);
// display the computed result
for (int i = 0; i < _outputCount; i++)
{
double d = output[i];
row.Data[dataIndex++] = Format.Format(d, Precision);
}
WriteRow(tw, row);
}
ReportDone(false);
tw.Close();
csv.Close();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Text;
using Xunit;
namespace System.Tests
{
public static partial class BitConverterTests
{
[Fact]
public static unsafe void IsLittleEndian()
{
short s = 1;
Assert.Equal(BitConverter.IsLittleEndian, *((byte*)&s) == 1);
}
[Fact]
public static void ValueArgumentNull()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToBoolean(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToChar(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToDouble(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToInt16(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToInt32(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToInt64(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToSingle(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt16(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt32(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt64(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null, 0));
AssertExtensions.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null, 0, 0));
}
[Fact]
public static void StartIndexBeyondLength()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], 8));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], 9));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], 4));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], 5));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], 8));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], 9));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], 4));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], 5));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], 4));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], 5));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], 8));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], 9));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 2, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => BitConverter.ToString(new byte[1], 0, -1));
}
[Fact]
public static void StartIndexPlusNeededLengthTooLong()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[0], 0));
AssertExtensions.Throws<ArgumentException>("value", () => BitConverter.ToChar(new byte[2], 1));
AssertExtensions.Throws<ArgumentException>("value", () => BitConverter.ToDouble(new byte[8], 1));
AssertExtensions.Throws<ArgumentException>("value", () => BitConverter.ToInt16(new byte[2], 1));
AssertExtensions.Throws<ArgumentException>("value", () => BitConverter.ToInt32(new byte[4], 1));
AssertExtensions.Throws<ArgumentException>("value", () => BitConverter.ToInt64(new byte[8], 1));
AssertExtensions.Throws<ArgumentException>("value", () => BitConverter.ToSingle(new byte[4], 1));
AssertExtensions.Throws<ArgumentException>("value", () => BitConverter.ToUInt16(new byte[2], 1));
AssertExtensions.Throws<ArgumentException>("value", () => BitConverter.ToUInt32(new byte[4], 1));
AssertExtensions.Throws<ArgumentException>("value", () => BitConverter.ToUInt64(new byte[8], 1));
AssertExtensions.Throws<ArgumentException>("value", () => BitConverter.ToString(new byte[2], 1, 2));
}
[Fact]
public static void DoubleToInt64Bits()
{
Double input = 123456.3234;
Int64 result = BitConverter.DoubleToInt64Bits(input);
Assert.Equal(4683220267154373240L, result);
Double roundtripped = BitConverter.Int64BitsToDouble(result);
Assert.Equal(input, roundtripped);
}
[Fact]
public static void RoundtripBoolean()
{
Byte[] bytes = BitConverter.GetBytes(true);
Assert.Equal(1, bytes.Length);
Assert.Equal(1, bytes[0]);
Assert.True(BitConverter.ToBoolean(bytes, 0));
bytes = BitConverter.GetBytes(false);
Assert.Equal(1, bytes.Length);
Assert.Equal(0, bytes[0]);
Assert.False(BitConverter.ToBoolean(bytes, 0));
}
[Fact]
public static void RoundtripChar()
{
Char input = 'A';
Byte[] expected = { 0x41, 0 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToChar, input, expected);
}
[Fact]
public static void RoundtripDouble()
{
Double input = 123456.3234;
Byte[] expected = { 0x78, 0x7a, 0xa5, 0x2c, 0x05, 0x24, 0xfe, 0x40 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToDouble, input, expected);
}
[Fact]
public static void RoundtripSingle()
{
Single input = 8392.34f;
Byte[] expected = { 0x5c, 0x21, 0x03, 0x46 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToSingle, input, expected);
}
[Fact]
public static void RoundtripInt16()
{
Int16 input = 0x1234;
Byte[] expected = { 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt16, input, expected);
}
[Fact]
public static void RoundtripInt32()
{
Int32 input = 0x12345678;
Byte[] expected = { 0x78, 0x56, 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt32, input, expected);
}
[Fact]
public static void RoundtripInt64()
{
Int64 input = 0x0123456789abcdef;
Byte[] expected = { 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt64, input, expected);
}
[Fact]
public static void RoundtripUInt16()
{
UInt16 input = 0x1234;
Byte[] expected = { 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt16, input, expected);
}
[Fact]
public static void RoundtripUInt32()
{
UInt32 input = 0x12345678;
Byte[] expected = { 0x78, 0x56, 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt32, input, expected);
}
[Fact]
public static void RoundtripUInt64()
{
UInt64 input = 0x0123456789abcdef;
Byte[] expected = { 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt64, input, expected);
}
[Fact]
public static void RoundtripString()
{
Byte[] bytes = { 0x12, 0x34, 0x56, 0x78, 0x9a };
Assert.Equal("12-34-56-78-9A", BitConverter.ToString(bytes));
Assert.Equal("56-78-9A", BitConverter.ToString(bytes, 2));
Assert.Equal("56", BitConverter.ToString(bytes, 2, 1));
Assert.Same(string.Empty, BitConverter.ToString(new byte[0]));
Assert.Same(string.Empty, BitConverter.ToString(new byte[3], 1, 0));
}
[Fact]
public static void ToString_ByteArray_Long()
{
byte[] bytes = Enumerable.Range(0, 256 * 4).Select(i => unchecked((byte)i)).ToArray();
string expected = string.Join("-", bytes.Select(b => b.ToString("X2")));
Assert.Equal(expected, BitConverter.ToString(bytes));
Assert.Equal(expected.Substring(3, expected.Length - 6), BitConverter.ToString(bytes, 1, bytes.Length - 2));
}
[Fact]
public static void ToString_ByteArrayTooLong_Throws()
{
byte[] arr;
try
{
arr = new byte[int.MaxValue / 3 + 1];
}
catch (OutOfMemoryException)
{
// Exit out of the test if we don't have an enough contiguous memory
// available to create a big enough array.
return;
}
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => BitConverter.ToString(arr));
}
private static void VerifyRoundtrip<TInput>(Func<TInput, Byte[]> getBytes, Func<Byte[], int, TInput> convertBack, TInput input, Byte[] expectedBytes)
{
Byte[] bytes = getBytes(input);
Assert.Equal(expectedBytes.Length, bytes.Length);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(expectedBytes);
}
Assert.Equal(expectedBytes, bytes);
Assert.Equal(input, convertBack(bytes, 0));
// Also try unaligned startIndex
byte[] longerBytes = new byte[bytes.Length + 1];
longerBytes[0] = 0;
Array.Copy(bytes, 0, longerBytes, 1, bytes.Length);
Assert.Equal(input, convertBack(longerBytes, 1));
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/duration.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.WellKnownTypes {
/// <summary>Holder for reflection information generated from google/protobuf/duration.proto</summary>
public static partial class DurationReflection {
#region Descriptor
/// <summary>File descriptor for google/protobuf/duration.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DurationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8SD2dvb2dsZS5wcm90",
"b2J1ZiIqCghEdXJhdGlvbhIPCgdzZWNvbmRzGAEgASgDEg0KBW5hbm9zGAIg",
"ASgFQnwKE2NvbS5nb29nbGUucHJvdG9idWZCDUR1cmF0aW9uUHJvdG9QAVoq",
"Z2l0aHViLmNvbS9nb2xhbmcvcHJvdG9idWYvcHR5cGVzL2R1cmF0aW9u+AEB",
"ogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90",
"bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Duration), global::Google.Protobuf.WellKnownTypes.Duration.Parser, new[]{ "Seconds", "Nanos" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A Duration represents a signed, fixed-length span of time represented
/// as a count of seconds and fractions of seconds at nanosecond
/// resolution. It is independent of any calendar and concepts like "day"
/// or "month". It is related to Timestamp in that the difference between
/// two Timestamp values is a Duration and it can be added or subtracted
/// from a Timestamp. Range is approximately +-10,000 years.
///
/// # Examples
///
/// Example 1: Compute Duration from two Timestamps in pseudo code.
///
/// Timestamp start = ...;
/// Timestamp end = ...;
/// Duration duration = ...;
///
/// duration.seconds = end.seconds - start.seconds;
/// duration.nanos = end.nanos - start.nanos;
///
/// if (duration.seconds < 0 && duration.nanos > 0) {
/// duration.seconds += 1;
/// duration.nanos -= 1000000000;
/// } else if (durations.seconds > 0 && duration.nanos < 0) {
/// duration.seconds -= 1;
/// duration.nanos += 1000000000;
/// }
///
/// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
///
/// Timestamp start = ...;
/// Duration duration = ...;
/// Timestamp end = ...;
///
/// end.seconds = start.seconds + duration.seconds;
/// end.nanos = start.nanos + duration.nanos;
///
/// if (end.nanos < 0) {
/// end.seconds -= 1;
/// end.nanos += 1000000000;
/// } else if (end.nanos >= 1000000000) {
/// end.seconds += 1;
/// end.nanos -= 1000000000;
/// }
///
/// Example 3: Compute Duration from datetime.timedelta in Python.
///
/// td = datetime.timedelta(days=3, minutes=10)
/// duration = Duration()
/// duration.FromTimedelta(td)
///
/// # JSON Mapping
///
/// In JSON format, the Duration type is encoded as a string rather than an
/// object, where the string ends in the suffix "s" (indicating seconds) and
/// is preceded by the number of seconds, with nanoseconds expressed as
/// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
/// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
/// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
/// microsecond should be expressed in JSON format as "3.000001s".
/// </summary>
public sealed partial class Duration : pb::IMessage<Duration> {
private static readonly pb::MessageParser<Duration> _parser = new pb::MessageParser<Duration>(() => new Duration());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Duration> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Duration() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Duration(Duration other) : this() {
seconds_ = other.seconds_;
nanos_ = other.nanos_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Duration Clone() {
return new Duration(this);
}
/// <summary>Field number for the "seconds" field.</summary>
public const int SecondsFieldNumber = 1;
private long seconds_;
/// <summary>
/// Signed seconds of the span of time. Must be from -315,576,000,000
/// to +315,576,000,000 inclusive. Note: these bounds are computed from:
/// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Seconds {
get { return seconds_; }
set {
seconds_ = value;
}
}
/// <summary>Field number for the "nanos" field.</summary>
public const int NanosFieldNumber = 2;
private int nanos_;
/// <summary>
/// Signed fractions of a second at nanosecond resolution of the span
/// of time. Durations less than one second are represented with a 0
/// `seconds` field and a positive or negative `nanos` field. For durations
/// of one second or more, a non-zero value for the `nanos` field must be
/// of the same sign as the `seconds` field. Must be from -999,999,999
/// to +999,999,999 inclusive.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Nanos {
get { return nanos_; }
set {
nanos_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Duration);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Duration other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Seconds != other.Seconds) return false;
if (Nanos != other.Nanos) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Seconds != 0L) hash ^= Seconds.GetHashCode();
if (Nanos != 0) hash ^= Nanos.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Seconds != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Seconds);
}
if (Nanos != 0) {
output.WriteRawTag(16);
output.WriteInt32(Nanos);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Seconds != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Seconds);
}
if (Nanos != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Duration other) {
if (other == null) {
return;
}
if (other.Seconds != 0L) {
Seconds = other.Seconds;
}
if (other.Nanos != 0) {
Nanos = other.Nanos;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Seconds = input.ReadInt64();
break;
}
case 16: {
Nanos = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.ReplacePropertyWithMethods;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ReplacePropertyWithMethods
{
public class ReplacePropertyWithMethodsTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace)
=> new ReplacePropertyWithMethodsCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestGetWithBody()
{
await TestAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestPublicProperty()
{
await TestAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAnonyousType1()
{
await TestAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void M()
{
var v = new { P = this.Prop } }
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void M()
{
var v = new { P = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAnonyousType2()
{
await TestAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void M()
{
var v = new { this.Prop } }
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void M()
{
var v = new { Prop = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestPassedToRef1()
{
await TestAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void RefM(ref int i)
{
}
public void M()
{
RefM(ref this.Prop);
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void RefM(ref int i)
{
}
public void M()
{
RefM(ref this.{|Conflict:GetProp|}());
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestPassedToOut1()
{
await TestAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void OutM(out int i)
{
}
public void M()
{
OutM(out this.Prop);
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void OutM(out int i)
{
}
public void M()
{
OutM(out this.{|Conflict:GetProp|}());
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUsedInAttribute1()
{
await TestAsync(
@"using System;
class CAttribute : Attribute
{
public int [||]Prop
{
get
{
return 0;
}
}
}
[C(Prop = 1)]
class D
{
}",
@"using System;
class CAttribute : Attribute
{
public int GetProp()
{
return 0;
}
}
[C({|Conflict:Prop|} = 1)]
class D
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestSetWithBody1()
{
await TestAsync(
@"class C
{
int [||]Prop
{
set
{
var v = value;
}
}
}",
@"class C
{
private void SetProp(int value)
{
var v = value;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestSetReference1()
{
await TestAsync(
@"class C
{
int [||]Prop
{
set
{
var v = value;
}
}
void M()
{
this.Prop = 1;
}
}",
@"class C
{
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestGetterAndSetter()
{
await TestAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestGetterAndSetterAccessibilityChange()
{
await TestAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
private set
{
var v = value;
}
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestIncrement1()
{
await TestAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop++;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() + 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestDecrement2()
{
await TestAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop--;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() - 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestRecursiveGet()
{
await TestAsync(
@"class C
{
int [||]Prop
{
get
{
return this.Prop + 1;
}
}
}",
@"class C
{
private int GetProp()
{
return this.GetProp() + 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestRecursiveSet()
{
await TestAsync(
@"class C
{
int [||]Prop
{
set
{
this.Prop = value + 1;
}
}
}",
@"class C
{
private void SetProp(int value)
{
this.SetProp(value + 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCompoundAssign1()
{
await TestAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop *= x;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() * x);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCompoundAssign2()
{
await TestAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop *= x + y;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() * (x + y));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestMissingAccessors()
{
await TestAsync(
@"class C
{
int [||]Prop { }
void M()
{
var v = this.Prop;
}
}",
@"class C
{
void M()
{
var v = this.GetProp();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestComputedProp()
{
await TestAsync(
@"class C
{
int [||]Prop => 1;
}",
@"class C
{
private int GetProp()
{
return 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestComputedPropWithTrailingTrivia()
{
await TestAsync(
@"class C
{
int [||]Prop => 1; // Comment
}",
@"class C
{
private int GetProp()
{
return 1; // Comment
}
}", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIndentation()
{
await TestAsync(
@"class C
{
int [||]Foo
{
get
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}
}",
@"class C
{
private int GetFoo()
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestComputedPropWithTrailingTriviaAfterArrow()
{
await TestAsync(
@"class C
{
public int [||]Prop => /* return 42 */ 42;
}",
@"class C
{
public int GetProp()
{
return /* return 42 */ 42;
}
}", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAbstractProperty()
{
await TestAsync(
@"class C
{
public abstract int [||]Prop { get; }
public void M()
{
var v = new { P = this.Prop } }
}",
@"class C
{
public abstract int GetProp();
public void M()
{
var v = new { P = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestVirtualProperty()
{
await TestAsync(
@"class C
{
public virtual int [||]Prop
{
get
{
return 1;
}
}
public void M()
{
var v = new { P = this.Prop } }
}",
@"class C
{
public virtual int GetProp()
{
return 1;
}
public void M()
{
var v = new { P = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestInterfaceProperty()
{
await TestAsync(
@"interface I
{
int [||]Prop { get; }
}",
@"interface I
{
int GetProp();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty1()
{
await TestAsync(
@"class C
{
public int [||]Prop { get; }
}",
@"class C
{
private readonly int prop;
public int GetProp()
{
return prop;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty2()
{
await TestAsync(
@"class C
{
public int [||]Prop { get; }
public C()
{
this.Prop++;
}
}",
@"class C
{
private readonly int prop;
public int GetProp()
{
return prop;
}
public C()
{
this.prop = this.GetProp() + 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty3()
{
await TestAsync(
@"class C
{
public int [||]Prop { get; }
public C()
{
this.Prop *= x + y;
}
}",
@"class C
{
private readonly int prop;
public int GetProp()
{
return prop;
}
public C()
{
this.prop = this.GetProp() * (x + y);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty4()
{
await TestAsync(
@"class C
{
public int [||]Prop { get; } = 1;
}",
@"class C
{
private readonly int prop = 1;
public int GetProp()
{
return prop;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty5()
{
await TestAsync(
@"class C
{
private int prop;
public int [||]Prop { get; } = 1;
}",
@"class C
{
private int prop;
private readonly int prop1 = 1;
public int GetProp()
{
return prop1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty6()
{
await TestAsync(
@"class C
{
public int [||]PascalCase { get; }
}",
@"class C
{
private readonly int pascalCase;
public int GetPascalCase()
{
return pascalCase;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUniqueName1()
{
await TestAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public abstract int GetProp();
}",
@"class C
{
public int GetProp1()
{
return 0;
}
public abstract int GetProp();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUniqueName2()
{
await TestAsync(
@"class C
{
public int [||]Prop
{
set
{
}
}
public abstract void SetProp(int i);
}",
@"class C
{
public void SetProp1(int value)
{
}
public abstract void SetProp(int i);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUniqueName3()
{
await TestAsync(
@"class C
{
public object [||]Prop
{
set
{
}
}
public abstract void SetProp(dynamic i);
}",
@"class C
{
public void SetProp1(object value)
{
}
public abstract void SetProp(dynamic i);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestTrivia1()
{
await TestAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
Prop++;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
SetProp(GetProp() + 1);
}
}", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestTrivia2()
{
await TestAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
/* Leading */
Prop++; /* Trailing */
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
/* Leading */
SetProp(GetProp() + 1); /* Trailing */
}
}", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestTrivia3()
{
await TestAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
/* Leading */
Prop += 1 /* Trailing */ ;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
/* Leading */
SetProp(GetProp() + 1 /* Trailing */ );
}
}", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task ReplaceReadInsideWrite1()
{
await TestAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
Prop = Prop + 1;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
SetProp(GetProp() + 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task ReplaceReadInsideWrite2()
{
await TestAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
Prop *= Prop + 1;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
SetProp(GetProp() * (GetProp() + 1));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
[WorkItem(16157, "https://github.com/dotnet/roslyn/issues/16157")]
public async Task TestWithConditionalBinding1()
{
await TestAsync(
@"public class Foo
{
public bool [||]Any { get; } // Replace 'Any' with method
public static void Bar()
{
var foo = new Foo();
bool f = foo?.Any == true;
}
}",
@"public class Foo
{
private readonly bool any;
public bool GetAny()
{
return any;
}
public static void Bar()
{
var foo = new Foo();
bool f = foo?.GetAny() == true;
}
}");
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tenancy_config/foreign_property.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.TenancyConfig {
/// <summary>Holder for reflection information generated from tenancy_config/foreign_property.proto</summary>
public static partial class ForeignPropertyReflection {
#region Descriptor
/// <summary>File descriptor for tenancy_config/foreign_property.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ForeignPropertyReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiV0ZW5hbmN5X2NvbmZpZy9mb3JlaWduX3Byb3BlcnR5LnByb3RvEhpob2xt",
"cy50eXBlcy50ZW5hbmN5X2NvbmZpZxoUcHJpbWl0aXZlL3V1aWQucHJvdG8a",
"OnRlbmFuY3lfY29uZmlnL2luZGljYXRvcnMvZm9yZWlnbl9wcm9wZXJ0eV9p",
"bmRpY2F0b3IucHJvdG8i5AEKD0ZvcmVpZ25Qcm9wZXJ0eRIVCg1wcm9wZXJ0",
"eV9uYW1lGAEgASgJEkAKG3Byb3BlcnR5X2ZvcmVpZ25fdGVuYW5jeV9pZBgC",
"IAEoCzIbLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5VdWlkEg8KB2FwaV91cmwY",
"AyABKAkSUgoJZW50aXR5X2lkGAQgASgLMj8uaG9sbXMudHlwZXMudGVuYW5j",
"eV9jb25maWcuaW5kaWNhdG9ycy5Gb3JlaWduUHJvcGVydHlJbmRpY2F0b3IS",
"EwoLd2Vic2l0ZV91cmwYBSABKAlCHKoCGUhPTE1TLlR5cGVzLlRlbmFuY3lD",
"b25maWdiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.UuidReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.ForeignPropertyIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.ForeignProperty), global::HOLMS.Types.TenancyConfig.ForeignProperty.Parser, new[]{ "PropertyName", "PropertyForeignTenancyId", "ApiUrl", "EntityId", "WebsiteUrl" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ForeignProperty : pb::IMessage<ForeignProperty> {
private static readonly pb::MessageParser<ForeignProperty> _parser = new pb::MessageParser<ForeignProperty>(() => new ForeignProperty());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ForeignProperty> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.TenancyConfig.ForeignPropertyReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ForeignProperty() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ForeignProperty(ForeignProperty other) : this() {
propertyName_ = other.propertyName_;
PropertyForeignTenancyId = other.propertyForeignTenancyId_ != null ? other.PropertyForeignTenancyId.Clone() : null;
apiUrl_ = other.apiUrl_;
EntityId = other.entityId_ != null ? other.EntityId.Clone() : null;
websiteUrl_ = other.websiteUrl_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ForeignProperty Clone() {
return new ForeignProperty(this);
}
/// <summary>Field number for the "property_name" field.</summary>
public const int PropertyNameFieldNumber = 1;
private string propertyName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string PropertyName {
get { return propertyName_; }
set {
propertyName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "property_foreign_tenancy_id" field.</summary>
public const int PropertyForeignTenancyIdFieldNumber = 2;
private global::HOLMS.Types.Primitive.Uuid propertyForeignTenancyId_;
/// <summary>
/// UUID is used instead of an indicator for foreign property because the id does not exist in the tenancy
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.Uuid PropertyForeignTenancyId {
get { return propertyForeignTenancyId_; }
set {
propertyForeignTenancyId_ = value;
}
}
/// <summary>Field number for the "api_url" field.</summary>
public const int ApiUrlFieldNumber = 3;
private string apiUrl_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ApiUrl {
get { return apiUrl_; }
set {
apiUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "entity_id" field.</summary>
public const int EntityIdFieldNumber = 4;
private global::HOLMS.Types.TenancyConfig.Indicators.ForeignPropertyIndicator entityId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.TenancyConfig.Indicators.ForeignPropertyIndicator EntityId {
get { return entityId_; }
set {
entityId_ = value;
}
}
/// <summary>Field number for the "website_url" field.</summary>
public const int WebsiteUrlFieldNumber = 5;
private string websiteUrl_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string WebsiteUrl {
get { return websiteUrl_; }
set {
websiteUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ForeignProperty);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ForeignProperty other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (PropertyName != other.PropertyName) return false;
if (!object.Equals(PropertyForeignTenancyId, other.PropertyForeignTenancyId)) return false;
if (ApiUrl != other.ApiUrl) return false;
if (!object.Equals(EntityId, other.EntityId)) return false;
if (WebsiteUrl != other.WebsiteUrl) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (PropertyName.Length != 0) hash ^= PropertyName.GetHashCode();
if (propertyForeignTenancyId_ != null) hash ^= PropertyForeignTenancyId.GetHashCode();
if (ApiUrl.Length != 0) hash ^= ApiUrl.GetHashCode();
if (entityId_ != null) hash ^= EntityId.GetHashCode();
if (WebsiteUrl.Length != 0) hash ^= WebsiteUrl.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (PropertyName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(PropertyName);
}
if (propertyForeignTenancyId_ != null) {
output.WriteRawTag(18);
output.WriteMessage(PropertyForeignTenancyId);
}
if (ApiUrl.Length != 0) {
output.WriteRawTag(26);
output.WriteString(ApiUrl);
}
if (entityId_ != null) {
output.WriteRawTag(34);
output.WriteMessage(EntityId);
}
if (WebsiteUrl.Length != 0) {
output.WriteRawTag(42);
output.WriteString(WebsiteUrl);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (PropertyName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PropertyName);
}
if (propertyForeignTenancyId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PropertyForeignTenancyId);
}
if (ApiUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ApiUrl);
}
if (entityId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId);
}
if (WebsiteUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(WebsiteUrl);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ForeignProperty other) {
if (other == null) {
return;
}
if (other.PropertyName.Length != 0) {
PropertyName = other.PropertyName;
}
if (other.propertyForeignTenancyId_ != null) {
if (propertyForeignTenancyId_ == null) {
propertyForeignTenancyId_ = new global::HOLMS.Types.Primitive.Uuid();
}
PropertyForeignTenancyId.MergeFrom(other.PropertyForeignTenancyId);
}
if (other.ApiUrl.Length != 0) {
ApiUrl = other.ApiUrl;
}
if (other.entityId_ != null) {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.TenancyConfig.Indicators.ForeignPropertyIndicator();
}
EntityId.MergeFrom(other.EntityId);
}
if (other.WebsiteUrl.Length != 0) {
WebsiteUrl = other.WebsiteUrl;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
PropertyName = input.ReadString();
break;
}
case 18: {
if (propertyForeignTenancyId_ == null) {
propertyForeignTenancyId_ = new global::HOLMS.Types.Primitive.Uuid();
}
input.ReadMessage(propertyForeignTenancyId_);
break;
}
case 26: {
ApiUrl = input.ReadString();
break;
}
case 34: {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.TenancyConfig.Indicators.ForeignPropertyIndicator();
}
input.ReadMessage(entityId_);
break;
}
case 42: {
WebsiteUrl = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Performance;
using osu.Framework.Graphics.Shaders;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Visualisation;
using osu.Framework.Graphics.Visualisation.Audio;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.IO.Stores;
using osu.Framework.Localisation;
using osu.Framework.Platform;
using osuTK;
namespace osu.Framework
{
public abstract class Game : Container, IKeyBindingHandler<FrameworkAction>, IKeyBindingHandler<PlatformAction>, IHandleGlobalKeyboardInput
{
public IWindow Window => Host?.Window;
public ResourceStore<byte[]> Resources { get; private set; }
public TextureStore Textures { get; private set; }
protected GameHost Host { get; private set; }
private readonly Bindable<bool> isActive = new Bindable<bool>(true);
/// <summary>
/// Whether the game is active (in the foreground).
/// </summary>
public IBindable<bool> IsActive => isActive;
public AudioManager Audio { get; private set; }
public ShaderManager Shaders { get; private set; }
/// <summary>
/// A store containing fonts accessible game-wide.
/// </summary>
/// <remarks>
/// It is recommended to use <see cref="AddFont"/> when adding new fonts.
/// </remarks>
public FontStore Fonts { get; private set; }
private FontStore localFonts;
protected LocalisationManager Localisation { get; private set; }
private readonly Container content;
private DrawVisualiser drawVisualiser;
private TextureVisualiser textureVisualiser;
private LogOverlay logOverlay;
private AudioMixerVisualiser audioMixerVisualiser;
protected override Container<Drawable> Content => content;
protected internal virtual UserInputManager CreateUserInputManager() => new UserInputManager();
/// <summary>
/// Provide <see cref="FrameworkSetting"/> defaults which should override those provided by osu-framework.
/// <remarks>
/// Please check https://github.com/ppy/osu-framework/blob/master/osu.Framework/Configuration/FrameworkConfigManager.cs for expected types.
/// </remarks>
/// </summary>
protected internal virtual IDictionary<FrameworkSetting, object> GetFrameworkConfigDefaults() => null;
/// <summary>
/// Creates the <see cref="Storage"/> where this <see cref="Game"/> will reside.
/// </summary>
/// <param name="host">The <see cref="GameHost"/>.</param>
/// <param name="defaultStorage">The default <see cref="Storage"/> to be used if a custom <see cref="Storage"/> isn't desired.</param>
/// <returns>The <see cref="Storage"/>.</returns>
protected internal virtual Storage CreateStorage(GameHost host, Storage defaultStorage) => defaultStorage;
protected Game()
{
RelativeSizeAxes = Axes.Both;
AddRangeInternal(new Drawable[]
{
content = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
},
});
}
/// <summary>
/// As Load is run post host creation, you can override this method to alter properties of the host before it makes itself visible to the user.
/// </summary>
/// <param name="host"></param>
public virtual void SetHost(GameHost host)
{
Host = host;
host.Exiting += OnExiting;
host.Activated += () => isActive.Value = true;
host.Deactivated += () => isActive.Value = false;
}
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) =>
dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
[BackgroundDependencyLoader]
private void load(FrameworkConfigManager config)
{
Resources = new ResourceStore<byte[]>();
Resources.AddStore(new NamespacedResourceStore<byte[]>(new DllResourceStore(typeof(Game).Assembly), @"Resources"));
Textures = new TextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore<byte[]>(Resources, @"Textures")));
Textures.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
dependencies.Cache(Textures);
var tracks = new ResourceStore<byte[]>();
tracks.AddStore(new NamespacedResourceStore<byte[]>(Resources, @"Tracks"));
tracks.AddStore(new OnlineStore());
var samples = new ResourceStore<byte[]>();
samples.AddStore(new NamespacedResourceStore<byte[]>(Resources, @"Samples"));
samples.AddStore(new OnlineStore());
Audio = new AudioManager(Host.AudioThread, tracks, samples) { EventScheduler = Scheduler };
dependencies.Cache(Audio);
dependencies.CacheAs(Audio.Tracks);
dependencies.CacheAs(Audio.Samples);
// attach our bindables to the audio subsystem.
config.BindWith(FrameworkSetting.AudioDevice, Audio.AudioDevice);
config.BindWith(FrameworkSetting.VolumeUniversal, Audio.Volume);
config.BindWith(FrameworkSetting.VolumeEffect, Audio.VolumeSample);
config.BindWith(FrameworkSetting.VolumeMusic, Audio.VolumeTrack);
Shaders = new ShaderManager(new NamespacedResourceStore<byte[]>(Resources, @"Shaders"));
dependencies.Cache(Shaders);
var cacheStorage = Host.CacheStorage.GetStorageForDirectory("fonts");
// base store is for user fonts
Fonts = new FontStore(useAtlas: true, cacheStorage: cacheStorage);
// nested store for framework provided fonts.
// note that currently this means there could be two async font load operations.
Fonts.AddStore(localFonts = new FontStore(useAtlas: false));
// Roboto (FrameworkFont.Regular)
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-Regular");
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-RegularItalic");
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-Bold");
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-BoldItalic");
// RobotoCondensed (FrameworkFont.Condensed)
addFont(localFonts, Resources, @"Fonts/RobotoCondensed/RobotoCondensed-Regular");
addFont(localFonts, Resources, @"Fonts/RobotoCondensed/RobotoCondensed-Bold");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Solid");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Regular");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Brands");
dependencies.Cache(Fonts);
Localisation = new LocalisationManager(config);
dependencies.Cache(Localisation);
frameSyncMode = config.GetBindable<FrameSync>(FrameworkSetting.FrameSync);
executionMode = config.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
logOverlayVisibility = config.GetBindable<bool>(FrameworkSetting.ShowLogOverlay);
logOverlayVisibility.BindValueChanged(visibility =>
{
if (visibility.NewValue)
{
if (logOverlay == null)
{
LoadComponentAsync(logOverlay = new LogOverlay
{
Depth = float.MinValue / 2,
}, AddInternal);
}
logOverlay.Show();
}
else
{
logOverlay?.Hide();
}
}, true);
}
/// <summary>
/// Add a font to be globally accessible to the game.
/// </summary>
/// <param name="store">The backing store with font resources.</param>
/// <param name="assetName">The base name of the font.</param>
/// <param name="target">An optional target store to add the font to. If not specified, <see cref="Fonts"/> is used.</param>
public void AddFont(ResourceStore<byte[]> store, string assetName = null, FontStore target = null)
=> addFont(target ?? Fonts, store, assetName);
private void addFont(FontStore target, ResourceStore<byte[]> store, string assetName = null)
=> target.AddStore(new RawCachingGlyphStore(store, assetName, Host.CreateTextureLoaderStore(store)));
protected override void LoadComplete()
{
base.LoadComplete();
PerformanceOverlay performanceOverlay;
LoadComponentAsync(performanceOverlay = new PerformanceOverlay(Host.Threads)
{
Margin = new MarginPadding(5),
Direction = FillDirection.Vertical,
Spacing = new Vector2(10, 10),
AutoSizeAxes = Axes.Both,
Alpha = 0,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
Depth = float.MinValue
}, AddInternal);
FrameStatistics.BindValueChanged(e => performanceOverlay.State = e.NewValue, true);
}
protected readonly Bindable<FrameStatisticsMode> FrameStatistics = new Bindable<FrameStatisticsMode>();
private GlobalStatisticsDisplay globalStatistics;
private Bindable<bool> logOverlayVisibility;
private Bindable<FrameSync> frameSyncMode;
private Bindable<ExecutionMode> executionMode;
public bool OnPressed(KeyBindingPressEvent<FrameworkAction> e)
{
switch (e.Action)
{
case FrameworkAction.CycleFrameStatistics:
switch (FrameStatistics.Value)
{
case FrameStatisticsMode.None:
FrameStatistics.Value = FrameStatisticsMode.Minimal;
break;
case FrameStatisticsMode.Minimal:
FrameStatistics.Value = FrameStatisticsMode.Full;
break;
case FrameStatisticsMode.Full:
FrameStatistics.Value = FrameStatisticsMode.None;
break;
}
return true;
case FrameworkAction.ToggleDrawVisualiser:
if (drawVisualiser == null)
{
LoadComponentAsync(drawVisualiser = new DrawVisualiser
{
ToolPosition = getCascadeLocation(0),
Depth = float.MinValue / 2,
}, AddInternal);
}
drawVisualiser.ToggleVisibility();
return true;
case FrameworkAction.ToggleGlobalStatistics:
if (globalStatistics == null)
{
LoadComponentAsync(globalStatistics = new GlobalStatisticsDisplay
{
Depth = float.MinValue / 2,
Position = getCascadeLocation(1),
}, AddInternal);
}
globalStatistics.ToggleVisibility();
return true;
case FrameworkAction.ToggleAtlasVisualiser:
if (textureVisualiser == null)
{
LoadComponentAsync(textureVisualiser = new TextureVisualiser
{
Position = getCascadeLocation(2),
Depth = float.MinValue / 2,
}, AddInternal);
}
textureVisualiser.ToggleVisibility();
return true;
case FrameworkAction.ToggleAudioMixerVisualiser:
if (audioMixerVisualiser == null)
{
LoadComponentAsync(audioMixerVisualiser = new AudioMixerVisualiser
{
Position = getCascadeLocation(3),
Depth = float.MinValue / 2,
}, AddInternal);
}
audioMixerVisualiser.ToggleVisibility();
return true;
case FrameworkAction.ToggleLogOverlay:
logOverlayVisibility.Value = !logOverlayVisibility.Value;
return true;
case FrameworkAction.ToggleFullscreen:
Window?.CycleMode();
return true;
case FrameworkAction.CycleFrameSync:
var nextFrameSync = frameSyncMode.Value + 1;
if (nextFrameSync > FrameSync.Unlimited)
nextFrameSync = FrameSync.VSync;
frameSyncMode.Value = nextFrameSync;
break;
case FrameworkAction.CycleExecutionMode:
var nextExecutionMode = executionMode.Value + 1;
if (nextExecutionMode > ExecutionMode.MultiThreaded)
nextExecutionMode = ExecutionMode.SingleThread;
executionMode.Value = nextExecutionMode;
break;
}
return false;
Vector2 getCascadeLocation(int index)
=> new Vector2(100 + index * (TitleBar.HEIGHT + 10));
}
public void OnReleased(KeyBindingReleaseEvent<FrameworkAction> e)
{
}
public virtual bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
{
switch (e.Action)
{
case PlatformAction.Exit:
Host.Window?.Close();
return true;
}
return false;
}
public virtual void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
{
}
public void Exit()
{
if (Host == null)
throw new InvalidOperationException("Attempted to exit a game which has not yet been run");
Host.Exit();
}
protected virtual bool OnExiting() => false;
protected override void Dispose(bool isDisposing)
{
// ensure any async disposals are completed before we begin to rip components out.
// if we were to not wait, async disposals may throw unexpected exceptions.
AsyncDisposalQueue.WaitForEmpty();
base.Dispose(isDisposing);
// call a second time to protect against anything being potentially async disposed in the base.Dispose call.
AsyncDisposalQueue.WaitForEmpty();
Audio?.Dispose();
Audio = null;
Fonts?.Dispose();
Fonts = null;
localFonts?.Dispose();
localFonts = null;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudio.Project.Automation
{
/// <summary>
/// This can navigate a collection object only (partial implementation of ProjectItems interface)
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[ComVisible(true), CLSCompliant(false)]
public class OANavigableProjectItems : EnvDTE.ProjectItems
{
#region fields
private OAProject project;
private IList<EnvDTE.ProjectItem> items;
private HierarchyNode nodeWithItems;
#endregion
#region properties
/// <summary>
/// Defines an internal list of project items
/// </summary>
internal IList<EnvDTE.ProjectItem> Items
{
get
{
return this.items;
}
}
/// <summary>
/// Defines a relationship to the associated project.
/// </summary>
internal OAProject Project
{
get
{
return this.project;
}
}
/// <summary>
/// Defines the node that contains the items
/// </summary>
internal HierarchyNode NodeWithItems
{
get
{
return this.nodeWithItems;
}
}
#endregion
#region ctor
/// <summary>
/// Constructor.
/// </summary>
/// <param name="project">The associated project.</param>
/// <param name="nodeWithItems">The node that defines the items.</param>
public OANavigableProjectItems(OAProject project, HierarchyNode nodeWithItems)
{
this.project = project;
this.nodeWithItems = nodeWithItems;
this.items = this.GetListOfProjectItems();
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="project">The associated project.</param>
/// <param name="items">A list of items that will make up the items defined by this object.</param>
/// <param name="nodeWithItems">The node that defines the items.</param>
public OANavigableProjectItems(OAProject project, IList<EnvDTE.ProjectItem> items, HierarchyNode nodeWithItems)
{
this.items = items;
this.project = project;
this.nodeWithItems = nodeWithItems;
}
#endregion
#region EnvDTE.ProjectItems
/// <summary>
/// Gets a value indicating the number of objects in the collection.
/// </summary>
public virtual int Count
{
get
{
return items.Count;
}
}
/// <summary>
/// Gets the immediate parent object of a ProjectItems collection.
/// </summary>
public virtual object Parent
{
get
{
return this.nodeWithItems.GetAutomationObject();
}
}
/// <summary>
/// Gets an enumeration indicating the type of object.
/// </summary>
public virtual string Kind
{
get
{
// TODO: Add OAProjectItems.Kind getter implementation
return null;
}
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual EnvDTE.DTE DTE
{
get
{
return (EnvDTE.DTE)this.project.DTE;
}
}
/// <summary>
/// Gets the project hosting the project item or items.
/// </summary>
public virtual EnvDTE.Project ContainingProject
{
get
{
return this.project;
}
}
/// <summary>
/// Adds one or more ProjectItem objects from a directory to the ProjectItems collection.
/// </summary>
/// <param name="directory">The directory from which to add the project item.</param>
/// <returns>A ProjectItem object.</returns>
public virtual EnvDTE.ProjectItem AddFromDirectory(string directory)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a new project item from an existing item template file and adds it to the project.
/// </summary>
/// <param name="fileName">The full path and file name of the template project file.</param>
/// <param name="name">The file name to use for the new project item.</param>
/// <returns>A ProjectItem object. </returns>
public virtual EnvDTE.ProjectItem AddFromTemplate(string fileName, string name)
{
throw new NotImplementedException();
}
/// <summary>
/// Creates a new folder in Solution Explorer.
/// </summary>
/// <param name="name">The name of the folder node in Solution Explorer.</param>
/// <param name="kind">The type of folder to add. The available values are based on vsProjectItemsKindConstants and vsProjectItemKindConstants</param>
/// <returns>A ProjectItem object.</returns>
public virtual EnvDTE.ProjectItem AddFolder(string name, string kind)
{
throw new NotImplementedException();
}
/// <summary>
/// Copies a source file and adds it to the project.
/// </summary>
/// <param name="filePath">The path and file name of the project item to be added.</param>
/// <returns>A ProjectItem object. </returns>
public virtual EnvDTE.ProjectItem AddFromFileCopy(string filePath)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a project item from a file that is installed in a project directory structure.
/// </summary>
/// <param name="fileName">The file name of the item to add as a project item. </param>
/// <returns>A ProjectItem object. </returns>
public virtual EnvDTE.ProjectItem AddFromFile(string fileName)
{
throw new NotImplementedException();
}
/// <summary>
/// Get Project Item from index
/// </summary>
/// <param name="index">Either index by number (1-based) or by name can be used to get the item</param>
/// <returns>Project Item. ArgumentException if invalid index is specified</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public virtual EnvDTE.ProjectItem Item(object index)
{
// Changed from MPFProj: throws ArgumentException instead of returning null (http://mpfproj10.codeplex.com/workitem/9158)
if(index is int)
{
int realIndex = (int)index - 1;
if(realIndex >= 0 && realIndex < this.items.Count)
{
return (EnvDTE.ProjectItem)items[realIndex];
}
}
else if(index is string)
{
string name = (string)index;
foreach(EnvDTE.ProjectItem item in items)
{
if(String.Compare(item.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
return item;
}
}
}
throw new ArgumentException();
}
/// <summary>
/// Returns an enumeration for items in a collection.
/// </summary>
/// <returns>An IEnumerator for this object.</returns>
public virtual IEnumerator GetEnumerator()
{
if(this.items == null)
{
yield return null;
}
int count = items.Count;
for(int i = 0; i < count; i++)
{
yield return items[i];
}
}
#endregion
#region virtual methods
/// <summary>
/// Retrives a list of items associated with the current node.
/// </summary>
/// <returns>A List of project items</returns>
protected IList<EnvDTE.ProjectItem> GetListOfProjectItems()
{
List<EnvDTE.ProjectItem> list = new List<EnvDTE.ProjectItem>();
for(HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling)
{
EnvDTE.ProjectItem item = child.GetAutomationObject() as EnvDTE.ProjectItem;
if(null != item)
{
list.Add(item);
}
}
return list;
}
#endregion
}
}
| |
// <copyright file="RemoteWebDriver.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Html5;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// Provides a way to use the driver through
/// </summary>
/// /// <example>
/// <code>
/// [TestFixture]
/// public class Testing
/// {
/// private IWebDriver driver;
/// <para></para>
/// [SetUp]
/// public void SetUp()
/// {
/// driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"),DesiredCapabilities.InternetExplorer());
/// }
/// <para></para>
/// [Test]
/// public void TestGoogle()
/// {
/// driver.Navigate().GoToUrl("http://www.google.co.uk");
/// /*
/// * Rest of the test
/// */
/// }
/// <para></para>
/// [TearDown]
/// public void TearDown()
/// {
/// driver.Quit();
/// }
/// }
/// </code>
/// </example>
public class RemoteWebDriver : IWebDriver, ISearchContext, IJavaScriptExecutor, IFindsById, IFindsByClassName, IFindsByLinkText, IFindsByName, IFindsByTagName, IFindsByXPath, IFindsByPartialLinkText, IFindsByCssSelector, ITakesScreenshot, IHasCapabilities, IHasWebStorage, IHasLocationContext, IHasApplicationCache, IAllowsFileDetection, IHasSessionId, IActionExecutor
{
/// <summary>
/// The default command timeout for HTTP requests in a RemoteWebDriver instance.
/// </summary>
protected static readonly TimeSpan DefaultCommandTimeout = TimeSpan.FromSeconds(60);
private const string DefaultRemoteServerUrl = "http://127.0.0.1:4444/wd/hub";
private ICommandExecutor executor;
private ICapabilities capabilities;
private SessionId sessionId;
private IWebStorage storage;
private IApplicationCache appCache;
private ILocationContext locationContext;
private IFileDetector fileDetector = new DefaultFileDetector();
private RemoteWebElementFactory elementFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub
/// </summary>
/// <param name="options">An <see cref="DriverOptions"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(DriverOptions options)
: this(ConvertOptionsToCapabilities(options))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub
/// </summary>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(ICapabilities desiredCapabilities)
: this(new Uri(DefaultRemoteServerUrl), desiredCapabilities)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub
/// </summary>
/// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param>
/// <param name="options">An <see cref="DriverOptions"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(Uri remoteAddress, DriverOptions options)
: this(remoteAddress, ConvertOptionsToCapabilities(options))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class
/// </summary>
/// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(Uri remoteAddress, ICapabilities desiredCapabilities)
: this(remoteAddress, desiredCapabilities, RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class using the specified remote address, desired capabilities, and command timeout.
/// </summary>
/// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
public RemoteWebDriver(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout)
: this(new HttpCommandExecutor(remoteAddress, commandTimeout), desiredCapabilities)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class
/// </summary>
/// <param name="commandExecutor">An <see cref="ICommandExecutor"/> object which executes commands for the driver.</param>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
{
this.executor = commandExecutor;
this.StartClient();
this.StartSession(desiredCapabilities);
this.elementFactory = new RemoteWebElementFactory(this);
if (this.capabilities.HasCapability(CapabilityType.SupportsApplicationCache))
{
object appCacheCapability = this.capabilities.GetCapability(CapabilityType.SupportsApplicationCache);
if (appCacheCapability is bool && (bool)appCacheCapability)
{
this.appCache = new RemoteApplicationCache(this);
}
}
if (this.capabilities.HasCapability(CapabilityType.SupportsLocationContext))
{
object locationContextCapability = this.capabilities.GetCapability(CapabilityType.SupportsLocationContext);
if (locationContextCapability is bool && (bool)locationContextCapability)
{
this.locationContext = new RemoteLocationContext(this);
}
}
if (this.capabilities.HasCapability(CapabilityType.SupportsWebStorage))
{
object webContextCapability = this.capabilities.GetCapability(CapabilityType.SupportsWebStorage);
if (webContextCapability is bool && (bool)webContextCapability)
{
this.storage = new RemoteWebStorage(this);
}
}
}
/// <summary>
/// Gets or sets the URL the browser is currently displaying.
/// </summary>
/// <seealso cref="IWebDriver.Url"/>
/// <seealso cref="INavigation.GoToUrl(string)"/>
/// <seealso cref="INavigation.GoToUrl(System.Uri)"/>
public string Url
{
get
{
Response commandResponse = this.Execute(DriverCommand.GetCurrentUrl, null);
return commandResponse.Value.ToString();
}
set
{
if (value == null)
{
throw new ArgumentNullException("value", "Argument 'url' cannot be null.");
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("url", value);
this.Execute(DriverCommand.Get, parameters);
}
}
/// <summary>
/// Gets the title of the current browser window.
/// </summary>
public string Title
{
get
{
Response commandResponse = this.Execute(DriverCommand.GetTitle, null);
object returnedTitle = commandResponse != null ? commandResponse.Value : string.Empty;
return returnedTitle.ToString();
}
}
/// <summary>
/// Gets the source of the page last loaded by the browser.
/// </summary>
public string PageSource
{
get
{
string pageSource = string.Empty;
Response commandResponse = this.Execute(DriverCommand.GetPageSource, null);
pageSource = commandResponse.Value.ToString();
return pageSource;
}
}
/// <summary>
/// Gets the current window handle, which is an opaque handle to this
/// window that uniquely identifies it within this driver instance.
/// </summary>
public string CurrentWindowHandle
{
get
{
Response commandResponse = this.Execute(DriverCommand.GetCurrentWindowHandle, null);
return commandResponse.Value.ToString();
}
}
/// <summary>
/// Gets the window handles of open browser windows.
/// </summary>
public ReadOnlyCollection<string> WindowHandles
{
get
{
Response commandResponse = this.Execute(DriverCommand.GetWindowHandles, null);
object[] handles = (object[])commandResponse.Value;
List<string> handleList = new List<string>();
foreach (object handle in handles)
{
handleList.Add(handle.ToString());
}
return handleList.AsReadOnly();
}
}
/// <summary>
/// Gets a value indicating whether web storage is supported for this driver.
/// </summary>
public bool HasWebStorage
{
get { return this.storage != null; }
}
/// <summary>
/// Gets an <see cref="IWebStorage"/> object for managing web storage.
/// </summary>
public IWebStorage WebStorage
{
get
{
if (this.storage == null)
{
throw new InvalidOperationException("Driver does not support manipulating HTML5 web storage. Use the HasWebStorage property to test for the driver capability");
}
return this.storage;
}
}
/// <summary>
/// Gets a value indicating whether manipulating the application cache is supported for this driver.
/// </summary>
public bool HasApplicationCache
{
get { return this.appCache != null; }
}
/// <summary>
/// Gets an <see cref="IApplicationCache"/> object for managing application cache.
/// </summary>
public IApplicationCache ApplicationCache
{
get
{
if (this.appCache == null)
{
throw new InvalidOperationException("Driver does not support manipulating the HTML5 application cache. Use the HasApplicationCache property to test for the driver capability");
}
return this.appCache;
}
}
/// <summary>
/// Gets a value indicating whether manipulating geolocation is supported for this driver.
/// </summary>
public bool HasLocationContext
{
get { return this.locationContext != null; }
}
/// <summary>
/// Gets an <see cref="ILocationContext"/> object for managing browser location.
/// </summary>
public ILocationContext LocationContext
{
get
{
if (this.locationContext == null)
{
throw new InvalidOperationException("Driver does not support setting HTML5 geolocation information. Use the HasLocationContext property to test for the driver capability");
}
return this.locationContext;
}
}
/// <summary>
/// Gets the capabilities that the RemoteWebDriver instance is currently using
/// </summary>
public ICapabilities Capabilities
{
get { return this.capabilities; }
}
/// <summary>
/// Gets or sets the <see cref="IFileDetector"/> responsible for detecting
/// sequences of keystrokes representing file paths and names.
/// </summary>
public virtual IFileDetector FileDetector
{
get
{
return this.fileDetector;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value", "FileDetector cannot be null");
}
this.fileDetector = value;
}
}
/// <summary>
/// Gets the <see cref="SessionId"/> for the current session of this driver.
/// </summary>
public SessionId SessionId
{
get { return this.sessionId; }
}
/// <summary>
/// Gets a value indicating whether this object is a valid action executor.
/// </summary>
public bool IsActionExecutor
{
get { return true; }
}
/// <summary>
/// Gets the <see cref="ICommandExecutor"/> which executes commands for this driver.
/// </summary>
protected ICommandExecutor CommandExecutor
{
get { return this.executor; }
}
/// <summary>
/// Gets or sets the factory object used to create instances of <see cref="RemoteWebElement"/>
/// or its subclasses.
/// </summary>
protected RemoteWebElementFactory ElementFactory
{
get { return this.elementFactory; }
set { this.elementFactory = value; }
}
/// <summary>
/// Finds the first element in the page that matches the <see cref="By"/> object
/// </summary>
/// <param name="by">By mechanism to find the object</param>
/// <returns>IWebElement object so that you can interact with that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new InternetExplorerDriver();
/// IWebElement elem = driver.FindElement(By.Name("q"));
/// </code>
/// </example>
public IWebElement FindElement(By by)
{
if (by == null)
{
throw new ArgumentNullException("by", "by cannot be null");
}
return by.FindElement(this);
}
/// <summary>
/// Finds the elements on the page by using the <see cref="By"/> object and returns a ReadOnlyCollection of the Elements on the page
/// </summary>
/// <param name="by">By mechanism to find the element</param>
/// <returns>ReadOnlyCollection of IWebElement</returns>
/// <example>
/// <code>
/// IWebDriver driver = new InternetExplorerDriver();
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> classList = driver.FindElements(By.ClassName("class"));
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
if (by == null)
{
throw new ArgumentNullException("by", "by cannot be null");
}
return by.FindElements(this);
}
/// <summary>
/// Closes the Browser
/// </summary>
public void Close()
{
this.Execute(DriverCommand.Close, null);
}
/// <summary>
/// Close the Browser and Dispose of WebDriver
/// </summary>
public void Quit()
{
this.Dispose();
}
/// <summary>
/// Method For getting an object to set the Speed
/// </summary>
/// <returns>Returns an IOptions object that allows the driver to set the speed and cookies and getting cookies</returns>
/// <seealso cref="IOptions"/>
/// <example>
/// <code>
/// IWebDriver driver = new InternetExplorerDriver();
/// driver.Manage().GetCookies();
/// </code>
/// </example>
public IOptions Manage()
{
return new RemoteOptions(this);
}
/// <summary>
/// Method to allow you to Navigate with WebDriver
/// </summary>
/// <returns>Returns an INavigation Object that allows the driver to navigate in the browser</returns>
/// <example>
/// <code>
/// IWebDriver driver = new InternetExplorerDriver();
/// driver.Navigate().GoToUrl("http://www.google.co.uk");
/// </code>
/// </example>
public INavigation Navigate()
{
return new RemoteNavigator(this);
}
/// <summary>
/// Method to give you access to switch frames and windows
/// </summary>
/// <returns>Returns an Object that allows you to Switch Frames and Windows</returns>
/// <example>
/// <code>
/// IWebDriver driver = new InternetExplorerDriver();
/// driver.SwitchTo().Frame("FrameName");
/// </code>
/// </example>
public ITargetLocator SwitchTo()
{
return new RemoteTargetLocator(this);
}
/// <summary>
/// Executes JavaScript in the context of the currently selected frame or window
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
public object ExecuteScript(string script, params object[] args)
{
return this.ExecuteScriptCommand(script, DriverCommand.ExecuteScript, args);
}
/// <summary>
/// Executes JavaScript asynchronously in the context of the currently selected frame or window.
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
public object ExecuteAsyncScript(string script, params object[] args)
{
return this.ExecuteScriptCommand(script, DriverCommand.ExecuteAsyncScript, args);
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the element</param>
/// <returns>IWebElement object so that you can interact with that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementById("id")
/// </code>
/// </example>
public IWebElement FindElementById(string id)
{
return this.FindElement("css selector", "#" + EscapeCssSelector(id));
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the Element</param>
/// <returns>ReadOnlyCollection of Elements that match the object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsById("id")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsById(string id)
{
string selector = EscapeCssSelector(id);
if (string.IsNullOrEmpty(selector))
{
// Finding multiple elements with an empty ID will return
// an empty list. However, finding by a CSS selector of '#'
// throws an exception, even in the multiple elements case,
// which means we need to short-circuit that behavior.
return new List<IWebElement>().AsReadOnly();
}
return this.FindElements("css selector", "#" + selector);
}
/// <summary>
/// Finds the first element in the page that matches the CSS Class supplied
/// </summary>
/// <param name="className">className of the</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementByClassName("classname")
/// </code>
/// </example>
public IWebElement FindElementByClassName(string className)
{
string selector = EscapeCssSelector(className);
if (selector.Contains(" "))
{
// Finding elements by class name with whitespace is not allowed.
// However, converting the single class name to a valid CSS selector
// by prepending a '.' may result in a still-valid, but incorrect
// selector. Thus, we short-ciruit that behavior here.
throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
}
return this.FindElement("css selector", "." + selector);
}
/// <summary>
/// Finds a list of elements that match the class name supplied
/// </summary>
/// <param name="className">CSS class Name on the element</param>
/// <returns>ReadOnlyCollection of IWebElement object so that you can interact with those objects</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByClassName(string className)
{
string selector = EscapeCssSelector(className);
if (selector.Contains(" "))
{
// Finding elements by class name with whitespace is not allowed.
// However, converting the single class name to a valid CSS selector
// by prepending a '.' may result in a still-valid, but incorrect
// selector. Thus, we short-ciruit that behavior here.
throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
}
return this.FindElements("css selector", "." + selector);
}
/// <summary>
/// Finds the first of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element </param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByLinkText("linktext")
/// </code>
/// </example>
public IWebElement FindElementByLinkText(string linkText)
{
return this.FindElement("link text", linkText);
}
/// <summary>
/// Finds a list of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element</param>
/// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> object so that you can interact with those objects</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByLinkText(string linkText)
{
return this.FindElements("link text", linkText);
}
/// <summary>
/// Finds the first of elements that match the part of the link text supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByPartialLinkText("partOfLink")
/// </code>
/// </example>
public IWebElement FindElementByPartialLinkText(string partialLinkText)
{
return this.FindElement("partial link text", partialLinkText);
}
/// <summary>
/// Finds a list of elements that match the class name supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByPartialLinkText("partOfTheLink")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByPartialLinkText(string partialLinkText)
{
return this.FindElements("partial link text", partialLinkText);
}
/// <summary>
/// Finds the first of elements that match the name supplied
/// </summary>
/// <param name="name">Name of the element on the page</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public IWebElement FindElementByName(string name)
{
return this.FindElement("css selector", "*[name=\"" + name + "\"]");
}
/// <summary>
/// Finds a list of elements that match the name supplied
/// </summary>
/// <param name="name">Name of element</param>
/// <returns>ReadOnlyCollect of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByName(string name)
{
return this.FindElements("css selector", "*[name=\"" + name + "\"]");
}
/// <summary>
/// Finds the first of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">DOM tag Name of the element being searched</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public IWebElement FindElementByTagName(string tagName)
{
return this.FindElement("css selector", tagName);
}
/// <summary>
/// Finds a list of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">DOM tag Name of element being searched</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByTagName(string tagName)
{
return this.FindElements("css selector", tagName);
}
/// <summary>
/// Finds the first of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByXPath("//table/tbody/tr/td/a");
/// </code>
/// </example>
public IWebElement FindElementByXPath(string xpath)
{
return this.FindElement("xpath", xpath);
}
/// <summary>
/// Finds a list of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to the element</param>
/// <returns>ReadOnlyCollection of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByXpath("//tr/td/a")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByXPath(string xpath)
{
return this.FindElements("xpath", xpath);
}
/// <summary>
/// Finds the first element matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The CSS selector to match.</param>
/// <returns>The first <see cref="IWebElement"/> matching the criteria.</returns>
public IWebElement FindElementByCssSelector(string cssSelector)
{
return this.FindElement("css selector", cssSelector);
}
/// <summary>
/// Finds all elements matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The CSS selector to match.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> containing all
/// <see cref="IWebElement">IWebElements</see> matching the criteria.</returns>
public ReadOnlyCollection<IWebElement> FindElementsByCssSelector(string cssSelector)
{
return this.FindElements("css selector", cssSelector);
}
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public Screenshot GetScreenshot()
{
// Get the screenshot as base64.
Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null);
string base64 = screenshotResponse.Value.ToString();
// ... and convert it.
return new Screenshot(base64);
}
/// <summary>
/// Dispose the RemoteWebDriver Instance
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Performs the specified list of actions with this action executor.
/// </summary>
/// <param name="actionSequenceList">The list of action sequences to perform.</param>
public void PerformActions(IList<ActionSequence> actionSequenceList)
{
if (actionSequenceList == null)
{
throw new ArgumentNullException("actionSequenceList", "List of action sequences must not be null");
}
List<object> objectList = new List<object>();
foreach (ActionSequence sequence in actionSequenceList)
{
objectList.Add(sequence.ToDictionary());
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["actions"] = objectList;
this.Execute(DriverCommand.Actions, parameters);
}
/// <summary>
/// Resets the input state of the action executor.
/// </summary>
public void ResetInputState()
{
this.Execute(DriverCommand.CancelActions, null);
}
/// <summary>
/// Escapes invalid characters in a CSS selector.
/// </summary>
/// <param name="selector">The selector to escape.</param>
/// <returns>The selector with invalid characters escaped.</returns>
internal static string EscapeCssSelector(string selector)
{
string escaped = Regex.Replace(selector, @"([ '""\\#.:;,!?+<>=~*^$|%&@`{}\-/\[\]\(\)])", @"\$1");
if (selector.Length > 0 && char.IsDigit(selector[0]))
{
escaped = @"\" + (30 + int.Parse(selector.Substring(0, 1), CultureInfo.InvariantCulture)).ToString(CultureInfo.InvariantCulture) + " " + selector.Substring(1);
}
return escaped;
}
/// <summary>
/// Executes commands with the driver
/// </summary>
/// <param name="driverCommandToExecute">Command that needs executing</param>
/// <param name="parameters">Parameters needed for the command</param>
/// <returns>WebDriver Response</returns>
internal Response InternalExecute(string driverCommandToExecute, Dictionary<string, object> parameters)
{
return this.Execute(driverCommandToExecute, parameters);
}
/// <summary>
/// Find the element in the response
/// </summary>
/// <param name="response">Response from the browser</param>
/// <returns>Element from the page</returns>
internal IWebElement GetElementFromResponse(Response response)
{
if (response == null)
{
throw new NoSuchElementException();
}
RemoteWebElement element = null;
Dictionary<string, object> elementDictionary = response.Value as Dictionary<string, object>;
if (elementDictionary != null)
{
element = this.elementFactory.CreateElement(elementDictionary);
}
return element;
}
/// <summary>
/// Finds the elements that are in the response
/// </summary>
/// <param name="response">Response from the browser</param>
/// <returns>Collection of elements</returns>
internal ReadOnlyCollection<IWebElement> GetElementsFromResponse(Response response)
{
List<IWebElement> toReturn = new List<IWebElement>();
object[] elements = response.Value as object[];
if (elements != null)
{
foreach (object elementObject in elements)
{
Dictionary<string, object> elementDictionary = elementObject as Dictionary<string, object>;
if (elementDictionary != null)
{
RemoteWebElement element = this.elementFactory.CreateElement(elementDictionary);
toReturn.Add(element);
}
}
}
return toReturn.AsReadOnly();
}
/// <summary>
/// Stops the client from running
/// </summary>
/// <param name="disposing">if its in the process of disposing</param>
protected virtual void Dispose(bool disposing)
{
try
{
this.Execute(DriverCommand.Quit, null);
}
catch (NotImplementedException)
{
}
catch (InvalidOperationException)
{
}
catch (WebDriverException)
{
}
finally
{
this.StopClient();
this.sessionId = null;
}
}
/// <summary>
/// Starts a session with the driver
/// </summary>
/// <param name="desiredCapabilities">Capabilities of the browser</param>
protected void StartSession(ICapabilities desiredCapabilities)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
// If the object passed into the RemoteWebDriver constructor is a
// RemoteSessionSettings object, it is expected that all intermediate
// and end nodes are compliant with the W3C WebDriver Specification,
// and therefore will already contain all of the appropriate values
// for establishing a session.
RemoteSessionSettings remoteSettings = desiredCapabilities as RemoteSessionSettings;
if (remoteSettings == null)
{
Dictionary<string, object> matchCapabilities = this.GetCapabilitiesDictionary(desiredCapabilities);
List<object> firstMatchCapabilitiesList = new List<object>();
firstMatchCapabilitiesList.Add(matchCapabilities);
Dictionary<string, object> specCompliantCapabilitiesDictionary = new Dictionary<string, object>();
specCompliantCapabilitiesDictionary["firstMatch"] = firstMatchCapabilitiesList;
parameters.Add("capabilities", specCompliantCapabilitiesDictionary);
}
else
{
parameters.Add("capabilities", remoteSettings.ToDictionary());
}
Response response = this.Execute(DriverCommand.NewSession, parameters);
Dictionary<string, object> rawCapabilities = (Dictionary<string, object>)response.Value;
ReturnedCapabilities returnedCapabilities = new ReturnedCapabilities(rawCapabilities);
this.capabilities = returnedCapabilities;
this.sessionId = new SessionId(response.SessionId);
}
/// <summary>
/// Gets the capabilities as a dictionary.
/// </summary>
/// <param name="capabilitiesToConvert">The dictionary to return.</param>
/// <returns>A Dictionary consisting of the capabilities requested.</returns>
/// <remarks>This method is only transitional. Do not rely on it. It will be removed
/// once browser driver capability formats stabilize.</remarks>
protected virtual Dictionary<string, object> GetCapabilitiesDictionary(ICapabilities capabilitiesToConvert)
{
Dictionary<string, object> capabilitiesDictionary = new Dictionary<string, object>();
IHasCapabilitiesDictionary capabilitiesObject = capabilitiesToConvert as IHasCapabilitiesDictionary;
foreach (KeyValuePair<string, object> entry in capabilitiesObject.CapabilitiesDictionary)
{
if (CapabilityType.IsSpecCompliantCapabilityName(entry.Key))
{
capabilitiesDictionary.Add(entry.Key, entry.Value);
}
}
return capabilitiesDictionary;
}
/// <summary>
/// Executes a command with this driver .
/// </summary>
/// <param name="driverCommandToExecute">A <see cref="DriverCommand"/> value representing the command to execute.</param>
/// <param name="parameters">A <see cref="Dictionary{K, V}"/> containing the names and values of the parameters of the command.</param>
/// <returns>A <see cref="Response"/> containing information about the success or failure of the command and any data returned by the command.</returns>
protected virtual Response Execute(string driverCommandToExecute, Dictionary<string, object> parameters)
{
Command commandToExecute = new Command(this.sessionId, driverCommandToExecute, parameters);
Response commandResponse = new Response();
try
{
commandResponse = this.executor.Execute(commandToExecute);
}
catch (System.Net.WebException e)
{
commandResponse.Status = WebDriverResult.UnhandledError;
commandResponse.Value = e;
}
if (commandResponse.Status != WebDriverResult.Success)
{
UnpackAndThrowOnError(commandResponse);
}
return commandResponse;
}
/// <summary>
/// Starts the command executor, enabling communication with the browser.
/// </summary>
protected virtual void StartClient()
{
}
/// <summary>
/// Stops the command executor, ending further communication with the browser.
/// </summary>
protected virtual void StopClient()
{
}
/// <summary>
/// Finds an element matching the given mechanism and value.
/// </summary>
/// <param name="mechanism">The mechanism by which to find the element.</param>
/// <param name="value">The value to use to search for the element.</param>
/// <returns>The first <see cref="IWebElement"/> matching the given criteria.</returns>
protected IWebElement FindElement(string mechanism, string value)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("using", mechanism);
parameters.Add("value", value);
Response commandResponse = this.Execute(DriverCommand.FindElement, parameters);
return this.GetElementFromResponse(commandResponse);
}
/// <summary>
/// Finds all elements matching the given mechanism and value.
/// </summary>
/// <param name="mechanism">The mechanism by which to find the elements.</param>
/// <param name="value">The value to use to search for the elements.</param>
/// <returns>A collection of all of the <see cref="IWebElement">IWebElements</see> matching the given criteria.</returns>
protected ReadOnlyCollection<IWebElement> FindElements(string mechanism, string value)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("using", mechanism);
parameters.Add("value", value);
Response commandResponse = this.Execute(DriverCommand.FindElements, parameters);
return this.GetElementsFromResponse(commandResponse);
}
/// <summary>
/// Executes JavaScript in the context of the currently selected frame or window using a specific command.
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="commandName">The name of the command to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
protected object ExecuteScriptCommand(string script, string commandName, params object[] args)
{
object[] convertedArgs = ConvertArgumentsToJavaScriptObjects(args);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("script", script);
if (convertedArgs != null && convertedArgs.Length > 0)
{
parameters.Add("args", convertedArgs);
}
else
{
parameters.Add("args", new object[] { });
}
Response commandResponse = this.Execute(commandName, parameters);
return this.ParseJavaScriptReturnValue(commandResponse.Value);
}
private static object ConvertObjectToJavaScriptObject(object arg)
{
IWrapsElement argAsWrapsElement = arg as IWrapsElement;
IWebElementReference argAsElementReference = arg as IWebElementReference;
IEnumerable argAsEnumerable = arg as IEnumerable;
IDictionary argAsDictionary = arg as IDictionary;
if (argAsElementReference == null && argAsWrapsElement != null)
{
argAsElementReference = argAsWrapsElement.WrappedElement as IWebElementReference;
}
object converted = null;
if (arg is string || arg is float || arg is double || arg is int || arg is long || arg is bool || arg == null)
{
converted = arg;
}
else if (argAsElementReference != null)
{
// TODO: Remove "ELEMENT" addition when all remote ends are spec-compliant.
Dictionary<string, object> elementDictionary = argAsElementReference.ToDictionary();
elementDictionary.Add(RemoteWebElement.LegacyElementReferencePropertyName, argAsElementReference.ElementReferenceId);
converted = elementDictionary;
}
else if (argAsDictionary != null)
{
// Note that we must check for the argument being a dictionary before
// checking for IEnumerable, since dictionaries also implement IEnumerable.
// Additionally, JavaScript objects have property names as strings, so all
// keys will be converted to strings.
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (var key in argAsDictionary.Keys)
{
dictionary.Add(key.ToString(), ConvertObjectToJavaScriptObject(argAsDictionary[key]));
}
converted = dictionary;
}
else if (argAsEnumerable != null)
{
List<object> objectList = new List<object>();
foreach (object item in argAsEnumerable)
{
objectList.Add(ConvertObjectToJavaScriptObject(item));
}
converted = objectList.ToArray();
}
else
{
throw new ArgumentException("Argument is of an illegal type" + arg.ToString(), "arg");
}
return converted;
}
/// <summary>
/// Converts the arguments to JavaScript objects.
/// </summary>
/// <param name="args">The arguments.</param>
/// <returns>The list of the arguments converted to JavaScript objects.</returns>
private static object[] ConvertArgumentsToJavaScriptObjects(object[] args)
{
if (args == null)
{
return new object[] { null };
}
for (int i = 0; i < args.Length; i++)
{
args[i] = ConvertObjectToJavaScriptObject(args[i]);
}
return args;
}
private static void UnpackAndThrowOnError(Response errorResponse)
{
// Check the status code of the error, and only handle if not success.
if (errorResponse.Status != WebDriverResult.Success)
{
Dictionary<string, object> errorAsDictionary = errorResponse.Value as Dictionary<string, object>;
if (errorAsDictionary != null)
{
ErrorResponse errorResponseObject = new ErrorResponse(errorAsDictionary);
string errorMessage = errorResponseObject.Message;
switch (errorResponse.Status)
{
case WebDriverResult.NoSuchElement:
throw new NoSuchElementException(errorMessage);
case WebDriverResult.NoSuchFrame:
throw new NoSuchFrameException(errorMessage);
case WebDriverResult.UnknownCommand:
throw new NotImplementedException(errorMessage);
case WebDriverResult.ObsoleteElement:
throw new StaleElementReferenceException(errorMessage);
case WebDriverResult.ElementClickIntercepted:
throw new ElementClickInterceptedException(errorMessage);
case WebDriverResult.ElementNotInteractable:
throw new ElementNotInteractableException(errorMessage);
case WebDriverResult.ElementNotDisplayed:
throw new ElementNotVisibleException(errorMessage);
case WebDriverResult.InvalidElementState:
case WebDriverResult.ElementNotSelectable:
throw new InvalidElementStateException(errorMessage);
case WebDriverResult.UnhandledError:
throw new WebDriverException(errorMessage);
case WebDriverResult.NoSuchDocument:
throw new NoSuchElementException(errorMessage);
case WebDriverResult.Timeout:
throw new WebDriverTimeoutException(errorMessage);
case WebDriverResult.NoSuchWindow:
throw new NoSuchWindowException(errorMessage);
case WebDriverResult.InvalidCookieDomain:
throw new InvalidCookieDomainException(errorMessage);
case WebDriverResult.UnableToSetCookie:
throw new UnableToSetCookieException(errorMessage);
case WebDriverResult.AsyncScriptTimeout:
throw new WebDriverTimeoutException(errorMessage);
case WebDriverResult.UnexpectedAlertOpen:
// TODO(JimEvans): Handle the case where the unexpected alert setting
// has been set to "ignore", so there is still a valid alert to be
// handled.
string alertText = string.Empty;
if (errorAsDictionary.ContainsKey("alert"))
{
Dictionary<string, object> alertDescription = errorAsDictionary["alert"] as Dictionary<string, object>;
if (alertDescription != null && alertDescription.ContainsKey("text"))
{
alertText = alertDescription["text"].ToString();
}
}
else if (errorAsDictionary.ContainsKey("data"))
{
Dictionary<string, object> alertData = errorAsDictionary["data"] as Dictionary<string, object>;
if (alertData != null && alertData.ContainsKey("text"))
{
alertText = alertData["text"].ToString();
}
}
throw new UnhandledAlertException(errorMessage, alertText);
case WebDriverResult.NoAlertPresent:
throw new NoAlertPresentException(errorMessage);
case WebDriverResult.InvalidSelector:
throw new InvalidSelectorException(errorMessage);
case WebDriverResult.NoSuchDriver:
throw new WebDriverException(errorMessage);
case WebDriverResult.InvalidArgument:
throw new WebDriverArgumentException(errorMessage);
case WebDriverResult.UnexpectedJavaScriptError:
throw new JavaScriptException(errorMessage);
case WebDriverResult.MoveTargetOutOfBounds:
throw new MoveTargetOutOfBoundsException(errorMessage);
default:
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "{0} ({1})", errorMessage, errorResponse.Status));
}
}
else
{
throw new WebDriverException("Unexpected error. " + errorResponse.Value.ToString());
}
}
}
private static ICapabilities ConvertOptionsToCapabilities(DriverOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options", "Driver options must not be null");
}
return options.ToCapabilities();
}
private object ParseJavaScriptReturnValue(object responseValue)
{
object returnValue = null;
Dictionary<string, object> resultAsDictionary = responseValue as Dictionary<string, object>;
object[] resultAsArray = responseValue as object[];
if (resultAsDictionary != null)
{
if (this.elementFactory.ContainsElementReference(resultAsDictionary))
{
returnValue = this.elementFactory.CreateElement(resultAsDictionary);
}
else
{
// Recurse through the dictionary, re-parsing each value.
string[] keyCopy = new string[resultAsDictionary.Keys.Count];
resultAsDictionary.Keys.CopyTo(keyCopy, 0);
foreach (string key in keyCopy)
{
resultAsDictionary[key] = this.ParseJavaScriptReturnValue(resultAsDictionary[key]);
}
returnValue = resultAsDictionary;
}
}
else if (resultAsArray != null)
{
bool allElementsAreWebElements = true;
List<object> toReturn = new List<object>();
foreach (object item in resultAsArray)
{
object parsedItem = this.ParseJavaScriptReturnValue(item);
IWebElement parsedItemAsElement = parsedItem as IWebElement;
if (parsedItemAsElement == null)
{
allElementsAreWebElements = false;
}
toReturn.Add(parsedItem);
}
if (toReturn.Count > 0 && allElementsAreWebElements)
{
List<IWebElement> elementList = new List<IWebElement>();
foreach (object listItem in toReturn)
{
IWebElement itemAsElement = listItem as IWebElement;
elementList.Add(itemAsElement);
}
returnValue = elementList.AsReadOnly();
}
else
{
returnValue = toReturn.AsReadOnly();
}
}
else
{
returnValue = responseValue;
}
return returnValue;
}
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
namespace ESRI.ArcLogistics.Data
{
/// <summary>
/// Class represents a collection of data objects.
/// </summary>
internal class DataObjectCollection<TDataObject, TEntity> :
IDataObjectCollection<TDataObject>
where TDataObject : DataObject
where TEntity : EntityObject
{
#region constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Creates a new instance of DataObjectCollection class.
/// </summary>
public DataObjectCollection(DataObjectContext context,
string entitySetName, bool isReadOnly)
{
_dataService = new DataService<TDataObject>(context, entitySetName);
_isReadOnly = isReadOnly;
}
/// <summary>
/// Creates a new instance of DataObjectCollection class.
/// </summary>
public DataObjectCollection(DataObjectContext context,
string entitySetName,
SpecFields specFields, bool isReadOnly)
{
_dataService = new DataService<TDataObject>(context, entitySetName,
specFields);
_isReadOnly = isReadOnly;
}
/// <summary>
/// Creates a new instance of DataObjectCollection class.
/// </summary>
public DataObjectCollection(DataService<TDataObject> dataService,
bool isReadOnly)
{
Debug.Assert(dataService != null);
_dataService = dataService;
_isReadOnly = isReadOnly;
}
#endregion constructors
#region INotifyCollectionChanged members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion INotifyCollectionChanged members
#region public methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Second-level initialization.
/// Loads collection data.
/// <param name="skipDeletedObjects">
/// A boolean value indicating whether objects marked as deleted must
/// be skipped when loading data.
/// </param>
/// </summary>
public void Initialize(bool skipDeletedObjects, bool syncWithContext)
{
Debug.Assert(!_isInited); // init once
// load data
IEnumerable<TDataObject> objects = null;
if (skipDeletedObjects)
objects = _dataService.FindNotDeletedObjects<TEntity>();
else
objects = _dataService.FindAllObjects<TEntity>();
_FillCollection(objects);
// observable collection events
_dataObjects.CollectionChanged += new NotifyCollectionChangedEventHandler(
_dataObjects_CollectionChanged);
if (syncWithContext)
{
// context events
_dataService.ContextCollectionChanged += new CollectionChangeEventHandler(
_dataService_ContextCollectionChanged);
}
_isInited = true;
this.OnCollectionInitialized();
}
public void Initialize(string initialQuery,
ObjectParameter[] queryParams,
Expression<Func<TEntity, bool>> filterClause)
{
Debug.Assert(!_isInited); // init once
// load data
var objects = _dataService.FindObjects<TEntity>(initialQuery, queryParams);
this.Initialize(objects, filterClause);
}
public void Initialize(Expression<Func<TEntity, bool>> initialClause,
Expression<Func<TEntity, bool>> filterClause)
{
Debug.Assert(!_isInited); // init once
// load data
var objects = _dataService.FindObjects(initialClause);
this.Initialize(objects, filterClause);
}
// TODO: workaround
public void Initialize(IEnumerable<TDataObject> objects,
Expression<Func<TEntity, bool>> filterClause)
{
Debug.Assert(!_isInited); // init once
// load data
_FillCollection(objects);
// observable collection events
_dataObjects.CollectionChanged += _dataObjects_CollectionChanged;
if (filterClause != null)
{
// context events
_dataService.ContextCollectionChanged += _dataService_ContextCollectionChanged;
_filter = filterClause.Compile();
}
_isInited = true;
this.OnCollectionInitialized();
}
public override string ToString()
{
return CollectionHelper.ToString(this as IList<TDataObject>);
}
#endregion public methods
#region IDisposable interface members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public void Dispose()
{
if (_filter != null && _dataService != null)
{
_dataService.ContextCollectionChanged -= new CollectionChangeEventHandler(
_dataService_ContextCollectionChanged);
}
if (_dataObjects != null)
{
_dataObjects.CollectionChanged -= new NotifyCollectionChangedEventHandler(
_dataObjects_CollectionChanged);
}
}
#endregion IDisposable interface members
#region IList<TDataObject> interface members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Default accessor for the collection.
/// </summary>
public TDataObject this[int index]
{
get
{
return (TDataObject)_dataObjects[index];
}
set
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Number of elements in the collection.
/// </summary>
public int Count
{
get { return _dataObjects.Count; }
}
/// <summary>
/// Adds data object to the collection.
/// </summary>
public virtual void Add(TDataObject dataObject)
{
if (dataObject == null)
throw new ArgumentNullException();
// check if collecton can be modified
_CheckReadOnlyFlag();
// check if object already exists
if (_dataObjects.Contains(dataObject))
throw new DataException(Properties.Messages.Error_DataObjectExistsInCollection);
// check if object is applicable to collection filter
if (_CanAddObject(dataObject))
{
// set CanSave flag
dataObject.CanSave = true;
// add object to database
_dataService.AddObject(dataObject);
}
else
{
// object does not conform to filtration clause
throw new DataException(Properties.Messages.Error_DataObjectRejectedByFilter);
}
}
/// <summary>
/// Removes data object from the collection.
/// </summary>
public virtual bool Remove(TDataObject dataObject)
{
if (dataObject == null)
throw new ArgumentNullException();
// check if collection can be modified
_CheckReadOnlyFlag();
// remove object from database
_dataService.RemoveObject(dataObject);
return true;
}
/// <summary>
/// Clear the collection of all it's elements.
/// </summary>
public void Clear()
{
throw new NotImplementedException();
}
/// <summary>
/// Returns boolean value based on whether or not it finds the
/// requested object in the collection.
/// </summary>
public bool Contains(TDataObject dataObject)
{
if (dataObject == null)
throw new ArgumentNullException();
return _dataObjects.Contains(dataObject);
}
/// <summary>
/// Copies objects from this collection into another array.
/// </summary>
public void CopyTo(TDataObject[] dataObjectArray, int index)
{
_dataObjects.CopyTo(dataObjectArray, index);
}
/// <summary>
/// Returns custom generic enumerator for this collection.
/// </summary>
IEnumerator<TDataObject> IEnumerable<TDataObject>.GetEnumerator()
{
return _dataObjects.GetEnumerator();
}
/// <summary>
/// Explicit non-generic interface implementation for IEnumerable
/// extended and required by ICollection (implemented by ICollection<TDataObject>).
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return _dataObjects.GetEnumerator();
}
/// <summary>
/// Returns a boolean value indicating whether the collection is
/// read-only.
/// </summary>
public bool IsReadOnly
{
get { return _isReadOnly; }
}
public int IndexOf(TDataObject item)
{
return _dataObjects.IndexOf(item);
}
public void Insert(int index, TDataObject item)
{
throw new InvalidOperationException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
#endregion IList interface members
#region protected properties
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
protected ObservableCollection<TDataObject> DataObjects
{
get { return _dataObjects; }
}
protected DataService<TDataObject> DataService
{
get { return _dataService; }
}
#endregion protected properties
#region protected methods
/// <summary>
/// Called when this data object collection becomes initialized.
/// </summary>
protected virtual void OnCollectionInitialized()
{
}
#endregion
#region private methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private void _dataObjects_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
CollectionChanged(this, e);
}
private void _dataService_ContextCollectionChanged(object sender, CollectionChangeEventArgs e)
{
TDataObject obj = e.Element as TDataObject;
if (obj != null)
{
if (e.Action == CollectionChangeAction.Add)
{
if (obj.CanSave &&
!_dataObjects.Contains(obj) &&
_CanAddObject(obj))
{
_AddToInternalCollection(obj);
}
}
else if (e.Action == CollectionChangeAction.Remove)
{
_RemoveFromInternalCollection(obj);
}
}
}
private void _FillCollection(IEnumerable<TDataObject> objects)
{
foreach (TDataObject obj in objects)
_AddToInternalCollection(obj);
}
/// <summary>
/// Add object to _dataObjects.
/// </summary>
/// <param name="obj">Object to add.</param>
protected virtual void _AddToInternalCollection(TDataObject obj)
{
_dataObjects.Add(obj);
}
/// <summary>
/// Remove object from _dataObjects.
/// </summary>
/// <param name="obj">Object to remove.</param>
protected virtual void _RemoveFromInternalCollection(TDataObject obj)
{
_dataObjects.Remove(obj);
}
private bool _CanAddObject(TDataObject dataObject)
{
if (_filter == null)
{
return true;
}
var entity = (TEntity)DataObjectHelper.GetEntityObject(dataObject);
return _filter(entity);
}
private void _CheckReadOnlyFlag()
{
if (_isReadOnly)
{
throw new InvalidOperationException(
Properties.Messages.Error_ReadOnlyCollectionChange);
}
}
#endregion private methods
#region private fields
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private ObservableCollection<TDataObject> _dataObjects = new ObservableCollection<TDataObject>();
private DataService<TDataObject> _dataService;
private bool _isReadOnly = false;
private bool _isInited = false;
/// <summary>
/// Filters entity objects before adding them to the collection.
/// </summary>
private Func<TEntity, bool> _filter;
#endregion private fields
}
}
| |
//
// 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 System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.StorSimple;
using Microsoft.WindowsAzure.Management.StorSimple.Models;
namespace Microsoft.WindowsAzure.Management.StorSimple
{
/// <summary>
/// All Operations related to Crypto keys
/// </summary>
internal partial class ResourceEncryptionKeyOperations : IServiceOperations<StorSimpleManagementClient>, IResourceEncryptionKeyOperations
{
/// <summary>
/// Initializes a new instance of the ResourceEncryptionKeyOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ResourceEncryptionKeyOperations(StorSimpleManagementClient client)
{
this._client = client;
}
private StorSimpleManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.StorSimple.StorSimpleManagementClient.
/// </summary>
public StorSimpleManagementClient Client
{
get { return this._client; }
}
/// <param name='customRequestHeaders'>
/// Required. The Custom Request Headers which client must use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for Resource Encryption Key.
/// </returns>
public async Task<GetResourceEncryptionKeyResponse> GetAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (customRequestHeaders == null)
{
throw new ArgumentNullException("customRequestHeaders");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
url = url + "/resources/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/~/";
url = url + "CisVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/api/secretmanagement/publickey";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-01-01.1.0");
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
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2014-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.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
GetResourceEncryptionKeyResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GetResourceEncryptionKeyResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement resourceEncryptionKeysEncryptedElement = responseDoc.Element(XName.Get("ResourceEncryptionKeysEncrypted", "http://windowscloudbackup.com/CiS/V2013_03"));
if (resourceEncryptionKeysEncryptedElement != null)
{
ResourceEncryptionKeys resourceEncryptionKeysEncryptedInstance = new ResourceEncryptionKeys();
result.ResourceEncryptionKeys = resourceEncryptionKeysEncryptedInstance;
XElement encodedEncryptedPublicKeyElement = resourceEncryptionKeysEncryptedElement.Element(XName.Get("EncodedEncryptedPublicKey", "http://windowscloudbackup.com/CiS/V2013_03"));
if (encodedEncryptedPublicKeyElement != null)
{
string encodedEncryptedPublicKeyInstance = encodedEncryptedPublicKeyElement.Value;
resourceEncryptionKeysEncryptedInstance.EncodedEncryptedPublicKey = encodedEncryptedPublicKeyInstance;
}
XElement resourceNameElement = resourceEncryptionKeysEncryptedElement.Element(XName.Get("ResourceName", "http://windowscloudbackup.com/CiS/V2013_03"));
if (resourceNameElement != null)
{
bool isNil = false;
XAttribute nilAttribute = resourceNameElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute != null)
{
isNil = nilAttribute.Value == "true";
}
if (isNil == false)
{
string resourceNameInstance = resourceNameElement.Value;
resourceEncryptionKeysEncryptedInstance.ResourceName = resourceNameInstance;
}
}
XElement thumbprintElement = resourceEncryptionKeysEncryptedElement.Element(XName.Get("Thumbprint", "http://windowscloudbackup.com/CiS/V2013_03"));
if (thumbprintElement != null)
{
string thumbprintInstance = thumbprintElement.Value;
resourceEncryptionKeysEncryptedInstance.Thumbprint = thumbprintInstance;
}
}
}
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();
}
}
}
}
}
| |
// Crc32.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2006-2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2010-January-16 13:16:27>
//
// ------------------------------------------------------------------
//
// Implements the CRC algorithm, which is used in zip files. The zip format calls for
// the zipfile to contain a CRC for the unencrypted byte stream of each file.
//
// It is based on example source code published at
// http://www.vbaccelerator.com/home/net/code/libraries/CRC32/Crc32_zip_CRC32_CRC32_cs.asp
//
// This implementation adds a tweak of that code for use within zip creation. While
// computing the CRC we also compress the byte stream, in the same read loop. This
// avoids the need to read through the uncompressed stream twice - once to compute CRC
// and another time to compress.
//
// ------------------------------------------------------------------
using System;
using Interop=System.Runtime.InteropServices;
namespace Ionic.Zlib
{
/// <summary>
/// Calculates a 32bit Cyclic Redundancy Checksum (CRC) using the same polynomial
/// used by Zip. This type is used internally by DotNetZip; it is generally not used
/// directly by applications wishing to create, read, or manipulate zip archive
/// files.
/// </summary>
[Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000C")]
[Interop.ComVisible(true)]
#if !NETCF
[Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)]
#endif
internal class CRC32
{
/// <summary>
/// indicates the total number of bytes read on the CRC stream.
/// This is used when writing the ZipDirEntry when compressing files.
/// </summary>
public Int64 TotalBytesRead
{
get
{
return _TotalBytesRead;
}
}
/// <summary>
/// Indicates the current CRC for all blocks slurped in.
/// </summary>
public Int32 Crc32Result
{
get
{
// return one's complement of the running result
return unchecked((Int32)(~_RunningCrc32Result));
}
}
/// <summary>
/// Returns the CRC32 for the specified stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32(System.IO.Stream input)
{
return GetCrc32AndCopy(input, null);
}
/// <summary>
/// Returns the CRC32 for the specified stream, and writes the input into the
/// output stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <param name="output">The stream into which to deflate the input</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output)
{
if (input == null)
throw new ZlibException("The input stream must not be null.");
unchecked
{
//UInt32 crc32Result;
//crc32Result = 0xFFFFFFFF;
byte[] buffer = new byte[BUFFER_SIZE];
int readSize = BUFFER_SIZE;
_TotalBytesRead = 0;
int count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
while (count > 0)
{
SlurpBlock(buffer, 0, count);
count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
}
return (Int32)(~_RunningCrc32Result);
}
}
/// <summary>
/// Get the CRC32 for the given (word,byte) combo. This is a computation
/// defined by PKzip.
/// </summary>
/// <param name="W">The word to start with.</param>
/// <param name="B">The byte to combine it with.</param>
/// <returns>The CRC-ized result.</returns>
public Int32 ComputeCrc32(Int32 W, byte B)
{
return _InternalComputeCrc32((UInt32)W, B);
}
internal Int32 _InternalComputeCrc32(UInt32 W, byte B)
{
return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8));
}
/// <summary>
/// Update the value for the running CRC32 using the given block of bytes.
/// This is useful when using the CRC32() class in a Stream.
/// </summary>
/// <param name="block">block of bytes to slurp</param>
/// <param name="offset">starting point in the block</param>
/// <param name="count">how many bytes within the block to slurp</param>
public void SlurpBlock(byte[] block, int offset, int count)
{
if (block == null)
throw new ZlibException("The data buffer must not be null.");
for (int i = 0; i < count; i++)
{
int x = offset + i;
_RunningCrc32Result = ((_RunningCrc32Result) >> 8) ^ crc32Table[(block[x]) ^ ((_RunningCrc32Result) & 0x000000FF)];
}
_TotalBytesRead += count;
}
// pre-initialize the crc table for speed of lookup.
static CRC32()
{
unchecked
{
// PKZip specifies CRC32 with a polynomial of 0xEDB88320;
// This is also the CRC-32 polynomial used bby Ethernet, FDDI,
// bzip2, gzip, and others.
// Often the polynomial is shown reversed as 0x04C11DB7.
// For more details, see http://en.wikipedia.org/wiki/Cyclic_redundancy_check
UInt32 dwPolynomial = 0xEDB88320;
UInt32 i, j;
crc32Table = new UInt32[256];
UInt32 dwCrc;
for (i = 0; i < 256; i++)
{
dwCrc = i;
for (j = 8; j > 0; j--)
{
if ((dwCrc & 1) == 1)
{
dwCrc = (dwCrc >> 1) ^ dwPolynomial;
}
else
{
dwCrc >>= 1;
}
}
crc32Table[i] = dwCrc;
}
}
}
private uint gf2_matrix_times(uint[] matrix, uint vec)
{
uint sum = 0;
int i=0;
while (vec != 0)
{
if ((vec & 0x01)== 0x01)
sum ^= matrix[i];
vec >>= 1;
i++;
}
return sum;
}
private void gf2_matrix_square(uint[] square, uint[] mat)
{
for (int i = 0; i < 32; i++)
square[i] = gf2_matrix_times(mat, mat[i]);
}
/// <summary>
/// Combines the given CRC32 value with the current running total.
/// </summary>
/// <remarks>
/// This is useful when using a divide-and-conquer approach to calculating a CRC.
/// Multiple threads can each calculate a CRC32 on a segment of the data, and then
/// combine the individual CRC32 values at the end.
/// </remarks>
/// <param name="crc">the crc value to be combined with this one</param>
/// <param name="length">the length of data the CRC value was calculated on</param>
public void Combine(int crc, int length)
{
uint[] even = new uint[32]; // even-power-of-two zeros operator
uint[] odd = new uint[32]; // odd-power-of-two zeros operator
if (length == 0)
return;
uint crc1= ~_RunningCrc32Result;
uint crc2= (uint) crc;
// put operator for one zero bit in odd
odd[0] = 0xEDB88320; // the CRC-32 polynomial
uint row = 1;
for (int i = 1; i < 32; i++)
{
odd[i] = row;
row <<= 1;
}
// put operator for two zero bits in even
gf2_matrix_square(even, odd);
// put operator for four zero bits in odd
gf2_matrix_square(odd, even);
uint len2 = (uint) length;
// apply len2 zeros to crc1 (first square will put the operator for one
// zero byte, eight zero bits, in even)
do {
// apply zeros operator for this bit of len2
gf2_matrix_square(even, odd);
if ((len2 & 1)== 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
if (len2 == 0)
break;
// another iteration of the loop with odd and even swapped
gf2_matrix_square(odd, even);
if ((len2 & 1)==1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
} while (len2 != 0);
crc1 ^= crc2;
_RunningCrc32Result= ~crc1;
//return (int) crc1;
return;
}
// private member vars
private Int64 _TotalBytesRead;
private static readonly UInt32[] crc32Table;
private const int BUFFER_SIZE = 8192;
private UInt32 _RunningCrc32Result = 0xFFFFFFFF;
}
/// <summary>
/// A Stream that calculates a CRC32 (a checksum) on all bytes read,
/// or on all bytes written.
/// </summary>
///
/// <remarks>
/// <para>
/// This class can be used to verify the CRC of a ZipEntry when
/// reading from a stream, or to calculate a CRC when writing to a
/// stream. The stream should be used to either read, or write, but
/// not both. If you intermix reads and writes, the results are not
/// defined.
/// </para>
///
/// <para>
/// This class is intended primarily for use internally by the
/// DotNetZip library.
/// </para>
/// </remarks>
internal class CrcCalculatorStream : System.IO.Stream, System.IDisposable
{
private static readonly Int64 UnsetLengthLimit = -99;
internal System.IO.Stream _innerStream;
private CRC32 _Crc32;
private Int64 _lengthLimit = -99;
private bool _leaveOpen;
/// <summary>
/// Gets the total number of bytes run through the CRC32 calculator.
/// </summary>
///
/// <remarks>
/// This is either the total number of bytes read, or the total number of bytes
/// written, depending on the direction of this stream.
/// </remarks>
public Int64 TotalBytesSlurped
{
get { return _Crc32.TotalBytesRead; }
}
/// <summary>
/// The default constructor.
/// </summary>
/// <remarks>
/// Instances returned from this constructor will leave the underlying stream
/// open upon Close().
/// </remarks>
/// <param name="stream">The underlying stream</param>
public CrcCalculatorStream(System.IO.Stream stream)
: this(true, CrcCalculatorStream.UnsetLengthLimit, stream)
{
}
/// <summary>
/// The constructor allows the caller to specify how to handle the underlying
/// stream at close.
/// </summary>
/// <param name="stream">The underlying stream</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the CrcCalculatorStream.; false otherwise.</param>
public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen)
: this(leaveOpen, CrcCalculatorStream.UnsetLengthLimit, stream)
{
}
/// <summary>
/// A constructor allowing the specification of the length of the stream to read.
/// </summary>
/// <remarks>
/// Instances returned from this constructor will leave the underlying stream open
/// upon Close().
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length)
: this(true, length, stream)
{
if (length < 0)
throw new ArgumentException("length");
}
/// <summary>
/// A constructor allowing the specification of the length of the stream to
/// read, as well as whether to keep the underlying stream open upon Close().
/// </summary>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the CrcCalculatorStream.; false otherwise.</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen)
: this(leaveOpen, length, stream)
{
if (length < 0)
throw new ArgumentException("length");
}
// This ctor is private - no validation is done here. This is to allow the use
// of a (specific) negative value for the _lengthLimit, to indicate that there
// is no length set. So we validate the length limit in those ctors that use an
// explicit param, otherwise we don't validate, because it could be our special
// value.
private CrcCalculatorStream(bool leaveOpen, Int64 length, System.IO.Stream stream)
: base()
{
_innerStream = stream;
_Crc32 = new CRC32();
_lengthLimit = length;
_leaveOpen = leaveOpen;
}
/// <summary>
/// Provides the current CRC for all blocks slurped in.
/// </summary>
public Int32 Crc
{
get { return _Crc32.Crc32Result; }
}
/// <summary>
/// Indicates whether the underlying stream will be left open when the
/// CrcCalculatorStream is Closed.
/// </summary>
public bool LeaveOpen
{
get { return _leaveOpen; }
set { _leaveOpen = value; }
}
/// <summary>
/// Read from the stream
/// </summary>
/// <param name="buffer">the buffer to read</param>
/// <param name="offset">the offset at which to start</param>
/// <param name="count">the number of bytes to read</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
int bytesToRead = count;
// Need to limit the # of bytes returned, if the stream is intended to have
// a definite length. This is especially useful when returning a stream for
// the uncompressed data directly to the application. The app won't
// necessarily read only the UncompressedSize number of bytes. For example
// wrapping the stream returned from OpenReader() into a StreadReader() and
// calling ReadToEnd() on it, We can "over-read" the zip data and get a
// corrupt string. The length limits that, prevents that problem.
if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit)
{
if (_Crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF
Int64 bytesRemaining = _lengthLimit - _Crc32.TotalBytesRead;
if (bytesRemaining < count) bytesToRead = (int)bytesRemaining;
}
int n = _innerStream.Read(buffer, offset, bytesToRead);
if (n > 0) _Crc32.SlurpBlock(buffer, offset, n);
return n;
}
/// <summary>
/// Write to the stream.
/// </summary>
/// <param name="buffer">the buffer from which to write</param>
/// <param name="offset">the offset at which to start writing</param>
/// <param name="count">the number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (count > 0) _Crc32.SlurpBlock(buffer, offset, count);
_innerStream.Write(buffer, offset, count);
}
/// <summary>
/// Indicates whether the stream supports reading.
/// </summary>
public override bool CanRead
{
get { return _innerStream.CanRead; }
}
/// <summary>
/// Indicates whether the stream supports seeking.
/// </summary>
public override bool CanSeek
{
get { return _innerStream.CanSeek; }
}
/// <summary>
/// Indicates whether the stream supports writing.
/// </summary>
public override bool CanWrite
{
get { return _innerStream.CanWrite; }
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
_innerStream.Flush();
}
/// <summary>
/// Not implemented.
/// </summary>
public override long Length
{
get
{
if (_lengthLimit == CrcCalculatorStream.UnsetLengthLimit)
return _innerStream.Length;
else return _lengthLimit;
}
}
/// <summary>
/// Not implemented.
/// </summary>
public override long Position
{
get { return _Crc32.TotalBytesRead; }
set { throw new NotImplementedException(); }
}
/// <summary>
/// Not implemented.
/// </summary>
/// <param name="offset">N/A</param>
/// <param name="origin">N/A</param>
/// <returns>N/A</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Not implemented.
/// </summary>
/// <param name="value">N/A</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
void IDisposable.Dispose()
{
Close();
}
/// <summary>
/// Closes the stream.
/// </summary>
public override void Close()
{
base.Close();
if (!_leaveOpen)
_innerStream.Close();
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Support;
using NUnit.Framework;
using System;
using System.IO;
using System.Text;
namespace Lucene.Net.Store
{
using Attributes;
using BytesRef = Lucene.Net.Util.BytesRef;
using Document = Documents.Document;
using Field = Field;
using IndexInputSlicer = Lucene.Net.Store.Directory.IndexInputSlicer;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using TestUtil = Lucene.Net.Util.TestUtil;
/// <summary>
/// Tests MMapDirectory's MultiMMapIndexInput
/// <p>
/// Because Java's ByteBuffer uses an int to address the
/// values, it's necessary to access a file >
/// Integer.MAX_VALUE in size using multiple byte buffers.
/// </summary>
[TestFixture]
public class TestMultiMMap : LuceneTestCase
{
[SetUp]
public override void SetUp()
{
base.SetUp();
// LUCENENET NOTE:
// Java seems to have issues releasing memory mapped resources when calling close()
// http://stackoverflow.com/a/2973059/181087
// However, according to MSDN, the Dispose() method of the MemoryMappedFile class will "release all resources".
// https://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile(v=vs.110).aspx
// Therefore, I am assuming removing the below line is the correct choice for .NET.
//AssumeTrue("test requires a jre that supports unmapping", MMapDirectory.UNMAP_SUPPORTED);
}
[Test]
public virtual void TestCloneSafety()
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testCloneSafety"));
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random()));
io.WriteVInt32(5);
io.Dispose();
IndexInput one = mmapDir.OpenInput("bytes", IOContext.DEFAULT);
IndexInput two = (IndexInput)one.Clone();
IndexInput three = (IndexInput)two.Clone(); // clone of clone
one.Dispose();
try
{
one.ReadVInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ignore)
#pragma warning restore 168
{
// pass
}
try
{
two.ReadVInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ignore)
#pragma warning restore 168
{
// pass
}
try
{
three.ReadVInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ignore)
#pragma warning restore 168
{
// pass
}
two.Dispose();
three.Dispose();
// test double close of master:
one.Dispose();
mmapDir.Dispose();
}
[Test]
public virtual void TestCloneClose()
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testCloneClose"));
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random()));
io.WriteVInt32(5);
io.Dispose();
IndexInput one = mmapDir.OpenInput("bytes", IOContext.DEFAULT);
IndexInput two = (IndexInput)one.Clone();
IndexInput three = (IndexInput)two.Clone(); // clone of clone
two.Dispose();
Assert.AreEqual(5, one.ReadVInt32());
try
{
two.ReadVInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ignore)
#pragma warning restore 168
{
// pass
}
Assert.AreEqual(5, three.ReadVInt32());
one.Dispose();
three.Dispose();
mmapDir.Dispose();
}
[Test]
public virtual void TestCloneSliceSafety()
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testCloneSliceSafety"));
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random()));
io.WriteInt32(1);
io.WriteInt32(2);
io.Dispose();
IndexInputSlicer slicer = mmapDir.CreateSlicer("bytes", NewIOContext(Random()));
IndexInput one = slicer.OpenSlice("first int", 0, 4);
IndexInput two = slicer.OpenSlice("second int", 4, 4);
IndexInput three = (IndexInput)one.Clone(); // clone of clone
IndexInput four = (IndexInput)two.Clone(); // clone of clone
slicer.Dispose();
try
{
one.ReadInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ignore)
#pragma warning restore 168
{
// pass
}
try
{
two.ReadInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ignore)
#pragma warning restore 168
{
// pass
}
try
{
three.ReadInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ignore)
#pragma warning restore 168
{
// pass
}
try
{
four.ReadInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ignore)
#pragma warning restore 168
{
// pass
}
one.Dispose();
two.Dispose();
three.Dispose();
four.Dispose();
// test double-close of slicer:
slicer.Dispose();
mmapDir.Dispose();
}
[Test]
public virtual void TestCloneSliceClose()
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testCloneSliceClose"));
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random()));
io.WriteInt32(1);
io.WriteInt32(2);
io.Dispose();
IndexInputSlicer slicer = mmapDir.CreateSlicer("bytes", NewIOContext(Random()));
IndexInput one = slicer.OpenSlice("first int", 0, 4);
IndexInput two = slicer.OpenSlice("second int", 4, 4);
one.Dispose();
try
{
one.ReadInt32();
Assert.Fail("Must throw ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ignore)
#pragma warning restore 168
{
// pass
}
Assert.AreEqual(2, two.ReadInt32());
// reopen a new slice "one":
one = slicer.OpenSlice("first int", 0, 4);
Assert.AreEqual(1, one.ReadInt32());
one.Dispose();
two.Dispose();
slicer.Dispose();
mmapDir.Dispose();
}
[Test]
public virtual void TestSeekZero()
{
for (int i = 0; i < 31; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSeekZero"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("zeroBytes", NewIOContext(Random()));
io.Dispose();
IndexInput ii = mmapDir.OpenInput("zeroBytes", NewIOContext(Random()));
ii.Seek(0L);
ii.Dispose();
mmapDir.Dispose();
}
}
[Test]
public virtual void TestSeekSliceZero()
{
for (int i = 0; i < 31; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSeekSliceZero"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("zeroBytes", NewIOContext(Random()));
io.Dispose();
IndexInputSlicer slicer = mmapDir.CreateSlicer("zeroBytes", NewIOContext(Random()));
IndexInput ii = slicer.OpenSlice("zero-length slice", 0, 0);
ii.Seek(0L);
ii.Dispose();
slicer.Dispose();
mmapDir.Dispose();
}
}
[Test]
public virtual void TestSeekEnd()
{
for (int i = 0; i < 17; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSeekEnd"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random()));
var bytes = new byte[1 << i];
Random().NextBytes(bytes);
io.WriteBytes(bytes, bytes.Length);
io.Dispose();
IndexInput ii = mmapDir.OpenInput("bytes", NewIOContext(Random()));
var actual = new byte[1 << i];
ii.ReadBytes(actual, 0, actual.Length);
Assert.AreEqual(new BytesRef(bytes), new BytesRef(actual));
ii.Seek(1 << i);
ii.Dispose();
mmapDir.Dispose();
}
}
[Test]
public virtual void TestSeekSliceEnd()
{
for (int i = 0; i < 17; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSeekSliceEnd"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random()));
var bytes = new byte[1 << i];
Random().NextBytes(bytes);
io.WriteBytes(bytes, bytes.Length);
io.Dispose();
IndexInputSlicer slicer = mmapDir.CreateSlicer("bytes", NewIOContext(Random()));
IndexInput ii = slicer.OpenSlice("full slice", 0, bytes.Length);
var actual = new byte[1 << i];
ii.ReadBytes(actual, 0, actual.Length);
Assert.AreEqual(new BytesRef(bytes), new BytesRef(actual));
ii.Seek(1 << i);
ii.Dispose();
slicer.Dispose();
mmapDir.Dispose();
}
}
[Test, LongRunningTest]
public virtual void TestSeeking()
{
for (int i = 0; i < 10; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSeeking"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random()));
var bytes = new byte[1 << (i + 1)]; // make sure we switch buffers
Random().NextBytes(bytes);
io.WriteBytes(bytes, bytes.Length);
io.Dispose();
IndexInput ii = mmapDir.OpenInput("bytes", NewIOContext(Random()));
var actual = new byte[1 << (i + 1)]; // first read all bytes
ii.ReadBytes(actual, 0, actual.Length);
Assert.AreEqual(new BytesRef(bytes), new BytesRef(actual));
for (int sliceStart = 0; sliceStart < bytes.Length; sliceStart++)
{
for (int sliceLength = 0; sliceLength < bytes.Length - sliceStart; sliceLength++)
{
var slice = new byte[sliceLength];
ii.Seek(sliceStart);
ii.ReadBytes(slice, 0, slice.Length);
Assert.AreEqual(new BytesRef(bytes, sliceStart, sliceLength), new BytesRef(slice));
}
}
ii.Dispose();
mmapDir.Dispose();
}
}
// note instead of seeking to offset and reading length, this opens slices at the
// the various offset+length and just does readBytes.
[Test, LongRunningTest]
public virtual void TestSlicedSeeking()
{
for (int i = 0; i < 10; i++)
{
MMapDirectory mmapDir = new MMapDirectory(CreateTempDir("testSlicedSeeking"), null, 1 << i);
IndexOutput io = mmapDir.CreateOutput("bytes", NewIOContext(Random()));
var bytes = new byte[1 << (i + 1)]; // make sure we switch buffers
Random().NextBytes(bytes);
io.WriteBytes(bytes, bytes.Length);
io.Dispose();
IndexInput ii = mmapDir.OpenInput("bytes", NewIOContext(Random()));
var actual = new byte[1 << (i + 1)]; // first read all bytes
ii.ReadBytes(actual, 0, actual.Length);
ii.Dispose();
Assert.AreEqual(new BytesRef(bytes), new BytesRef(actual));
IndexInputSlicer slicer = mmapDir.CreateSlicer("bytes", NewIOContext(Random()));
for (int sliceStart = 0; sliceStart < bytes.Length; sliceStart++)
{
for (int sliceLength = 0; sliceLength < bytes.Length - sliceStart; sliceLength++)
{
var slice = new byte[sliceLength];
IndexInput input = slicer.OpenSlice("bytesSlice", sliceStart, slice.Length);
input.ReadBytes(slice, 0, slice.Length);
input.Dispose();
Assert.AreEqual(new BytesRef(bytes, sliceStart, sliceLength), new BytesRef(slice));
}
}
slicer.Dispose();
mmapDir.Dispose();
}
}
[Test]
public virtual void TestRandomChunkSizes()
{
int num = AtLeast(10);
for (int i = 0; i < num; i++)
{
AssertChunking(Random(), TestUtil.NextInt(Random(), 20, 100));
}
}
private void AssertChunking(Random random, int chunkSize)
{
DirectoryInfo path = CreateTempDir("mmap" + chunkSize);
MMapDirectory mmapDir = new MMapDirectory(path, null, chunkSize);
// LUCENENET specific - unmap hack not needed
//// we will map a lot, try to turn on the unmap hack
//if (MMapDirectory.UNMAP_SUPPORTED)
//{
// mmapDir.UseUnmap = true;
//}
MockDirectoryWrapper dir = new MockDirectoryWrapper(random, mmapDir);
RandomIndexWriter writer = new RandomIndexWriter(random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMergePolicy(NewLogMergePolicy()));
Document doc = new Document();
Field docid = NewStringField("docid", "0", Field.Store.YES);
Field junk = NewStringField("junk", "", Field.Store.YES);
doc.Add(docid);
doc.Add(junk);
int numDocs = 100;
for (int i = 0; i < numDocs; i++)
{
docid.SetStringValue("" + i);
junk.SetStringValue(TestUtil.RandomUnicodeString(random));
writer.AddDocument(doc);
}
IndexReader reader = writer.Reader;
writer.Dispose();
int numAsserts = AtLeast(100);
for (int i = 0; i < numAsserts; i++)
{
int docID = random.Next(numDocs);
Assert.AreEqual("" + docID, reader.Document(docID).Get("docid"));
}
reader.Dispose();
dir.Dispose();
}
[Test, LuceneNetSpecific]
public void TestDisposeIndexInput()
{
string name = "foobar";
var dir = CreateTempDir("testDisposeIndexInput");
string fileName = Path.Combine(dir.FullName, name);
// Create a zero byte file, and close it immediately
File.WriteAllText(fileName, string.Empty, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false) /* No BOM */);
MMapDirectory mmapDir = new MMapDirectory(dir);
using (var indexInput = mmapDir.OpenInput(name, NewIOContext(Random())))
{
} // Dispose
// Now it should be possible to delete the file. This is the condition we are testing for.
File.Delete(fileName);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Win32 {
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Diagnostics.Tracing;
[System.Security.SecurityCritical] // auto-generated
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeNativeMethods {
[DllImport(Win32Native.KERNEL32, EntryPoint="GetTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
internal static extern int GetTimeZoneInformation(out Win32Native.TimeZoneInformation lpTimeZoneInformation);
[DllImport(Win32Native.KERNEL32, EntryPoint="GetDynamicTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
internal static extern int GetDynamicTimeZoneInformation(out Win32Native.DynamicTimeZoneInformation lpDynamicTimeZoneInformation);
//
// BOOL GetFileMUIPath(
// DWORD dwFlags,
// PCWSTR pcwszFilePath,
// PWSTR pwszLanguage,
// PULONG pcchLanguage,
// PWSTR pwszFileMUIPath,
// PULONG pcchFileMUIPath,
// PULONGLONG pululEnumerator
// );
//
[DllImport(Win32Native.KERNEL32, EntryPoint="GetFileMUIPath", SetLastError = true, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetFileMUIPath(
int flags,
[MarshalAs(UnmanagedType.LPWStr)]
String filePath,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder language,
ref int languageLength,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder fileMuiPath,
ref int fileMuiPathLength,
ref Int64 enumerator);
[DllImport(Win32Native.USER32, EntryPoint="LoadStringW", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
internal static extern int LoadString(SafeLibraryHandle handle, int id, StringBuilder buffer, int bufferLength);
[DllImport(Win32Native.KERNEL32, CharSet=System.Runtime.InteropServices.CharSet.Unicode, SetLastError=true)]
internal static extern SafeLibraryHandle LoadLibraryEx(string libFilename, IntPtr reserved, int flags);
[DllImport(Win32Native.KERNEL32, CharSet=System.Runtime.InteropServices.CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern bool FreeLibrary(IntPtr hModule);
[SecurityCritical]
[SuppressUnmanagedCodeSecurityAttribute()]
internal static unsafe class ManifestEtw
{
//
// Constants error coded returned by ETW APIs
//
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 534;
// Occurs when filled buffers are trying to flush to disk,
// but disk IOs are not happening fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 8;
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NOT_SUPPORTED = 50;
internal const int ERROR_INVALID_PARAMETER = 0x57;
//
// ETW Methods
//
internal const int EVENT_CONTROL_CODE_DISABLE_PROVIDER = 0;
internal const int EVENT_CONTROL_CODE_ENABLE_PROVIDER = 1;
internal const int EVENT_CONTROL_CODE_CAPTURE_STATE = 2;
//
// Callback
//
[SecurityCritical]
internal unsafe delegate void EtwEnableCallback(
[In] ref Guid sourceId,
[In] int isEnabled,
[In] byte level,
[In] long matchAnyKeywords,
[In] long matchAllKeywords,
[In] EVENT_FILTER_DESCRIPTOR* filterData,
[In] void* callbackContext
);
//
// Registration APIs
//
[SecurityCritical]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe uint EventRegister(
[In] ref Guid providerId,
[In]EtwEnableCallback enableCallback,
[In]void* callbackContext,
[In][Out]ref long registrationHandle
);
//
[SecurityCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern uint EventUnregister([In] long registrationHandle);
//
// Writing (Publishing/Logging) APIs
//
//
[SecurityCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe int EventWrite(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] int userDataCount,
[In] EventProvider.EventData* userData
);
[SecurityCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe int EventWriteString(
[In] long registrationHandle,
[In] byte level,
[In] long keyword,
[In] string msg
);
[StructLayout(LayoutKind.Sequential)]
unsafe internal struct EVENT_FILTER_DESCRIPTOR
{
public long Ptr;
public int Size;
public int Type;
};
/// <summary>
/// Call the ETW native API EventWriteTransfer and checks for invalid argument error.
/// The implementation of EventWriteTransfer on some older OSes (Windows 2008) does not accept null relatedActivityId.
/// So, for these cases we will retry the call with an empty Guid.
/// </summary>
internal static int EventWriteTransferWrapper(long registrationHandle,
ref EventDescriptor eventDescriptor,
Guid* activityId,
Guid* relatedActivityId,
int userDataCount,
EventProvider.EventData* userData)
{
int HResult = EventWriteTransfer(registrationHandle, ref eventDescriptor, activityId, relatedActivityId, userDataCount, userData);
if (HResult == ERROR_INVALID_PARAMETER && relatedActivityId == null)
{
Guid emptyGuid = Guid.Empty;
HResult = EventWriteTransfer(registrationHandle, ref eventDescriptor, activityId, &emptyGuid, userDataCount, userData);
}
return HResult;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
private static extern int EventWriteTransfer(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] Guid* activityId,
[In] Guid* relatedActivityId,
[In] int userDataCount,
[In] EventProvider.EventData* userData
);
internal enum ActivityControl : uint
{
EVENT_ACTIVITY_CTRL_GET_ID = 1,
EVENT_ACTIVITY_CTRL_SET_ID = 2,
EVENT_ACTIVITY_CTRL_CREATE_ID = 3,
EVENT_ACTIVITY_CTRL_GET_SET_ID = 4,
EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EventActivityIdControl([In] ActivityControl ControlCode, [In][Out] ref Guid ActivityId);
internal enum EVENT_INFO_CLASS
{
BinaryTrackInfo,
SetEnableAllKeywords,
SetTraits,
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventSetInformation", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EventSetInformation(
[In] long registrationHandle,
[In] EVENT_INFO_CLASS informationClass,
[In] void* eventInformation,
[In] int informationLength);
// Support for EnumerateTraceGuidsEx
internal enum TRACE_QUERY_INFO_CLASS
{
TraceGuidQueryList,
TraceGuidQueryInfo,
TraceGuidQueryProcess,
TraceStackTracingInfo,
MaxTraceSetInfoClass
};
internal struct TRACE_GUID_INFO
{
public int InstanceCount;
public int Reserved;
};
internal struct TRACE_PROVIDER_INSTANCE_INFO
{
public int NextOffset;
public int EnableCount;
public int Pid;
public int Flags;
};
internal struct TRACE_ENABLE_INFO
{
public int IsEnabled;
public byte Level;
public byte Reserved1;
public ushort LoggerId;
public int EnableProperty;
public int Reserved2;
public long MatchAnyKeyword;
public long MatchAllKeyword;
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EnumerateTraceGuidsEx", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EnumerateTraceGuidsEx(
TRACE_QUERY_INFO_CLASS TraceQueryInfoClass,
void* InBuffer,
int InBufferSize,
void* OutBuffer,
int OutBufferSize,
ref int ReturnLength);
}
#if FEATURE_COMINTEROP
[SecurityCritical]
[DllImport("combase.dll", PreserveSig = true)]
internal static extern int RoGetActivationFactory(
[MarshalAs(UnmanagedType.HString)] string activatableClassId,
[In] ref Guid iid,
[Out,MarshalAs(UnmanagedType.IInspectable)] out Object factory);
#endif
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Partitions
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
/// <summary>
/// Represents a BIOS (MBR) Partition Table.
/// </summary>
public sealed class BiosPartitionTable : PartitionTable
{
private Stream _diskData;
private Geometry _diskGeometry;
/// <summary>
/// Initializes a new instance of the BiosPartitionTable class.
/// </summary>
/// <param name="disk">The disk containing the partition table</param>
public BiosPartitionTable(VirtualDisk disk)
{
Init(disk.Content, disk.BiosGeometry);
}
/// <summary>
/// Initializes a new instance of the BiosPartitionTable class.
/// </summary>
/// <param name="disk">The stream containing the disk data</param>
/// <param name="diskGeometry">The geometry of the disk</param>
public BiosPartitionTable(Stream disk, Geometry diskGeometry)
{
Init(disk, diskGeometry);
}
/// <summary>
/// Gets the GUID that uniquely identifies this disk, if supported (else returns <c>null</c>).
/// </summary>
public override Guid DiskGuid
{
get { return Guid.Empty; }
}
/// <summary>
/// Gets a collection of the partitions for storing Operating System file-systems.
/// </summary>
public ReadOnlyCollection<BiosPartitionInfo> BiosUserPartitions
{
get
{
List<BiosPartitionInfo> result = new List<BiosPartitionInfo>();
foreach (BiosPartitionRecord r in GetAllRecords())
{
if (r.IsValid)
{
result.Add(new BiosPartitionInfo(this, r));
}
}
return new ReadOnlyCollection<BiosPartitionInfo>(result);
}
}
/// <summary>
/// Gets a collection of the partitions for storing Operating System file-systems.
/// </summary>
public override ReadOnlyCollection<PartitionInfo> Partitions
{
get
{
List<PartitionInfo> result = new List<PartitionInfo>();
foreach (BiosPartitionRecord r in GetAllRecords())
{
if (r.IsValid)
{
result.Add(new BiosPartitionInfo(this, r));
}
}
return new ReadOnlyCollection<PartitionInfo>(result);
}
}
/// <summary>
/// Makes a best guess at the geometry of a disk.
/// </summary>
/// <param name="disk">String containing the disk image to detect the geometry from</param>
/// <returns>The detected geometry</returns>
public static Geometry DetectGeometry(Stream disk)
{
if (disk.Length >= Utilities.SectorSize)
{
disk.Position = 0;
byte[] bootSector = Utilities.ReadFully(disk, Utilities.SectorSize);
if (bootSector[510] == 0x55 && bootSector[511] == 0xAA)
{
byte maxHead = 0;
byte maxSector = 0;
foreach (var record in ReadPrimaryRecords(bootSector))
{
maxHead = Math.Max(maxHead, record.EndHead);
maxSector = Math.Max(maxSector, record.EndSector);
}
if (maxHead > 0 && maxSector > 0)
{
int cylSize = (maxHead + 1) * maxSector * 512;
return new Geometry((int)Utilities.Ceil(disk.Length, cylSize), maxHead + 1, maxSector);
}
}
}
return Geometry.FromCapacity(disk.Length);
}
/// <summary>
/// Indicates if a stream contains a valid partition table.
/// </summary>
/// <param name="disk">The stream to inspect</param>
/// <returns><c>true</c> if the partition table is valid, else <c>false</c>.</returns>
public static bool IsValid(Stream disk)
{
if (disk.Length < Utilities.SectorSize)
{
return false;
}
disk.Position = 0;
byte[] bootSector = Utilities.ReadFully(disk, Utilities.SectorSize);
// Check for the 'bootable sector' marker
if (bootSector[510] != 0x55 || bootSector[511] != 0xAA)
{
return false;
}
List<StreamExtent> knownPartitions = new List<StreamExtent>();
foreach (var record in ReadPrimaryRecords(bootSector))
{
// If the partition extends beyond the end of the disk, this is probably an invalid partition table
if (record.LBALength != 0xFFFFFFFF && (record.LBAStart + (long)record.LBALength) * Sizes.Sector > disk.Length)
{
return false;
}
if (record.LBALength > 0)
{
StreamExtent[] thisPartitionExtents = new StreamExtent[] { new StreamExtent(record.LBAStart, record.LBALength) };
// If the partition intersects another partition, this is probably an invalid partition table
foreach (var overlap in StreamExtent.Intersect(knownPartitions, thisPartitionExtents))
{
return false;
}
knownPartitions = new List<StreamExtent>(StreamExtent.Union(knownPartitions, thisPartitionExtents));
}
}
return true;
}
/// <summary>
/// Creates a new partition table on a disk.
/// </summary>
/// <param name="disk">The disk to initialize.</param>
/// <returns>An object to access the newly created partition table</returns>
public static BiosPartitionTable Initialize(VirtualDisk disk)
{
return Initialize(disk.Content, disk.BiosGeometry);
}
/// <summary>
/// Creates a new partition table on a disk containing a single partition.
/// </summary>
/// <param name="disk">The disk to initialize.</param>
/// <param name="type">The partition type for the single partition</param>
/// <returns>An object to access the newly created partition table</returns>
public static BiosPartitionTable Initialize(VirtualDisk disk, WellKnownPartitionType type)
{
BiosPartitionTable table = Initialize(disk.Content, disk.BiosGeometry);
table.Create(type, true);
return table;
}
/// <summary>
/// Creates a new partition table on a disk.
/// </summary>
/// <param name="disk">The stream containing the disk data</param>
/// <param name="diskGeometry">The geometry of the disk</param>
/// <returns>An object to access the newly created partition table</returns>
public static BiosPartitionTable Initialize(Stream disk, Geometry diskGeometry)
{
Stream data = disk;
byte[] bootSector;
if (data.Length >= Utilities.SectorSize)
{
data.Position = 0;
bootSector = Utilities.ReadFully(data, Utilities.SectorSize);
}
else
{
bootSector = new byte[Utilities.SectorSize];
}
// Wipe all four 16-byte partition table entries
Array.Clear(bootSector, 0x01BE, 16 * 4);
// Marker bytes
bootSector[510] = 0x55;
bootSector[511] = 0xAA;
data.Position = 0;
data.Write(bootSector, 0, bootSector.Length);
return new BiosPartitionTable(disk, diskGeometry);
}
/// <summary>
/// Creates a new partition that encompasses the entire disk.
/// </summary>
/// <param name="type">The partition type</param>
/// <param name="active">Whether the partition is active (bootable)</param>
/// <returns>The index of the partition</returns>
/// <remarks>The partition table must be empty before this method is called,
/// otherwise IOException is thrown.</remarks>
public override int Create(WellKnownPartitionType type, bool active)
{
Geometry allocationGeometry = new Geometry(_diskData.Length, _diskGeometry.HeadsPerCylinder, _diskGeometry.SectorsPerTrack, _diskGeometry.BytesPerSector);
ChsAddress start = new ChsAddress(0, 1, 1);
ChsAddress last = allocationGeometry.LastSector;
long startLba = allocationGeometry.ToLogicalBlockAddress(start);
long lastLba = allocationGeometry.ToLogicalBlockAddress(last);
return CreatePrimaryByCylinder(0, allocationGeometry.Cylinders - 1, ConvertType(type, (lastLba - startLba) * Utilities.SectorSize), active);
}
/// <summary>
/// Creates a new primary partition with a target size.
/// </summary>
/// <param name="size">The target size (in bytes)</param>
/// <param name="type">The partition type</param>
/// <param name="active">Whether the partition is active (bootable)</param>
/// <returns>The index of the new partition</returns>
public override int Create(long size, WellKnownPartitionType type, bool active)
{
int cylinderCapacity = _diskGeometry.SectorsPerTrack * _diskGeometry.HeadsPerCylinder * _diskGeometry.BytesPerSector;
int numCylinders = (int)(size / cylinderCapacity);
int startCylinder = FindCylinderGap(numCylinders);
return CreatePrimaryByCylinder(startCylinder, startCylinder + numCylinders - 1, ConvertType(type, size), active);
}
/// <summary>
/// Creates a new aligned partition that encompasses the entire disk.
/// </summary>
/// <param name="type">The partition type</param>
/// <param name="active">Whether the partition is active (bootable)</param>
/// <param name="alignment">The alignment (in bytes)</param>
/// <returns>The index of the partition</returns>
/// <remarks>The partition table must be empty before this method is called,
/// otherwise IOException is thrown.</remarks>
/// <remarks>
/// Traditionally partitions were aligned to the physical structure of the underlying disk,
/// however with modern storage greater efficiency is acheived by aligning partitions on
/// large values that are a power of two.
/// </remarks>
public override int CreateAligned(WellKnownPartitionType type, bool active, int alignment)
{
Geometry allocationGeometry = new Geometry(_diskData.Length, _diskGeometry.HeadsPerCylinder, _diskGeometry.SectorsPerTrack, _diskGeometry.BytesPerSector);
ChsAddress start = new ChsAddress(0, 1, 1);
long startLba = Utilities.RoundUp(allocationGeometry.ToLogicalBlockAddress(start), alignment / _diskGeometry.BytesPerSector);
long lastLba = Utilities.RoundDown((_diskData.Length / _diskGeometry.BytesPerSector), alignment / _diskGeometry.BytesPerSector);
return CreatePrimaryBySector(startLba, lastLba - 1, ConvertType(type, (lastLba - startLba) * Utilities.SectorSize), active);
}
/// <summary>
/// Creates a new aligned partition with a target size.
/// </summary>
/// <param name="size">The target size (in bytes)</param>
/// <param name="type">The partition type</param>
/// <param name="active">Whether the partition is active (bootable)</param>
/// <param name="alignment">The alignment (in bytes)</param>
/// <returns>The index of the new partition</returns>
/// <remarks>
/// Traditionally partitions were aligned to the physical structure of the underlying disk,
/// however with modern storage greater efficiency is acheived by aligning partitions on
/// large values that are a power of two.
/// </remarks>
public override int CreateAligned(long size, WellKnownPartitionType type, bool active, int alignment)
{
if (size < _diskGeometry.BytesPerSector)
{
throw new ArgumentOutOfRangeException("size", size, "size must be at least one sector");
}
if (alignment % _diskGeometry.BytesPerSector != 0)
{
throw new ArgumentException("Alignment is not a multiple of the sector size");
}
if (size % alignment != 0)
{
throw new ArgumentException("Size is not a multiple of the alignment");
}
long sectorLength = size / _diskGeometry.BytesPerSector;
long start = FindGap(size / _diskGeometry.BytesPerSector, alignment / _diskGeometry.BytesPerSector);
return CreatePrimaryBySector(start, start + sectorLength - 1, ConvertType(type, sectorLength * Utilities.SectorSize), active);
}
/// <summary>
/// Deletes a partition at a given index.
/// </summary>
/// <param name="index">The index of the partition</param>
public override void Delete(int index)
{
WriteRecord(index, new BiosPartitionRecord());
}
/// <summary>
/// Creates a new Primary Partition that occupies whole cylinders, for best compatibility.
/// </summary>
/// <param name="first">The first cylinder to include in the partition (inclusive)</param>
/// <param name="last">The last cylinder to include in the partition (inclusive)</param>
/// <param name="type">The BIOS (MBR) type of the new partition</param>
/// <param name="markActive">Whether to mark the partition active (bootable)</param>
/// <returns>The index of the new partition</returns>
/// <remarks>If the cylinder 0 is given, the first track will not be used, to reserve space
/// for the meta-data at the start of the disk.</remarks>
public int CreatePrimaryByCylinder(int first, int last, byte type, bool markActive)
{
if (first < 0)
{
throw new ArgumentOutOfRangeException("first", first, "First cylinder must be Zero or greater");
}
if (last <= first)
{
throw new ArgumentException("Last cylinder must be greater than first");
}
long lbaStart = (first == 0) ? _diskGeometry.ToLogicalBlockAddress(0, 1, 1) : _diskGeometry.ToLogicalBlockAddress(first, 0, 1);
long lbaLast = _diskGeometry.ToLogicalBlockAddress(last, _diskGeometry.HeadsPerCylinder - 1, _diskGeometry.SectorsPerTrack);
return CreatePrimaryBySector(lbaStart, lbaLast, type, markActive);
}
/// <summary>
/// Creates a new Primary Partition, specified by Logical Block Addresses.
/// </summary>
/// <param name="first">The LBA address of the first sector (inclusive)</param>
/// <param name="last">The LBA address of the last sector (inclusive)</param>
/// <param name="type">The BIOS (MBR) type of the new partition</param>
/// <param name="markActive">Whether to mark the partition active (bootable)</param>
/// <returns>The index of the new partition</returns>
public int CreatePrimaryBySector(long first, long last, byte type, bool markActive)
{
if (first >= last)
{
throw new ArgumentException("The first sector in a partition must be before the last");
}
if ((last + 1) * _diskGeometry.BytesPerSector > _diskData.Length)
{
throw new ArgumentOutOfRangeException("last", last, "The last sector extends beyond the end of the disk");
}
BiosPartitionRecord[] existing = GetPrimaryRecords();
BiosPartitionRecord newRecord = new BiosPartitionRecord();
ChsAddress startAddr = _diskGeometry.ToChsAddress(first);
ChsAddress endAddr = _diskGeometry.ToChsAddress(last);
// Because C/H/S addresses can max out at lower values than the LBA values,
// the special tuple (1023, 254, 63) is used.
if (startAddr.Cylinder > 1023)
{
startAddr = new ChsAddress(1023, 254, 63);
}
if (endAddr.Cylinder > 1023)
{
endAddr = new ChsAddress(1023, 254, 63);
}
newRecord.StartCylinder = (ushort)startAddr.Cylinder;
newRecord.StartHead = (byte)startAddr.Head;
newRecord.StartSector = (byte)startAddr.Sector;
newRecord.EndCylinder = (ushort)endAddr.Cylinder;
newRecord.EndHead = (byte)endAddr.Head;
newRecord.EndSector = (byte)endAddr.Sector;
newRecord.LBAStart = (uint)first;
newRecord.LBALength = (uint)(last - first + 1);
newRecord.PartitionType = type;
newRecord.Status = (byte)(markActive ? 0x80 : 0x00);
// First check for overlap with existing partition...
foreach (var r in existing)
{
if (Utilities.RangesOverlap((uint)first, (uint)last + 1, r.LBAStartAbsolute, r.LBAStartAbsolute + r.LBALength))
{
throw new IOException("New partition overlaps with existing partition");
}
}
// Now look for empty partition
for (int i = 0; i < 4; ++i)
{
if (!existing[i].IsValid)
{
WriteRecord(i, newRecord);
return i;
}
}
throw new IOException("No primary partition slots available");
}
/// <summary>
/// Sets the active partition.
/// </summary>
/// <param name="index">The index of the primary partition to mark bootable, or <c>-1</c> for none</param>
/// <remarks>The supplied index is the index within the primary partition, see <c>PrimaryIndex</c> on <c>BiosPartitionInfo</c>.</remarks>
public void SetActivePartition(int index)
{
List<BiosPartitionRecord> records = new List<BiosPartitionRecord>(GetPrimaryRecords());
for (int i = 0; i < records.Count; ++i)
{
records[i].Status = (i == index) ? (byte)0x80 : (byte)0x00;
WriteRecord(i, records[i]);
}
}
/// <summary>
/// Gets all of the disk ranges containing partition table metadata.
/// </summary>
/// <returns>Set of stream extents, indicated as byte offset from the start of the disk.</returns>
public IEnumerable<StreamExtent> GetMetadataDiskExtents()
{
List<StreamExtent> extents = new List<StreamExtent>();
extents.Add(new StreamExtent(0, Sizes.Sector));
foreach (BiosPartitionRecord primaryRecord in GetPrimaryRecords())
{
if (primaryRecord.IsValid)
{
if (IsExtendedPartition(primaryRecord))
{
extents.AddRange(new BiosExtendedPartitionTable(_diskData, primaryRecord.LBAStart).GetMetadataDiskExtents());
}
}
}
return extents;
}
/// <summary>
/// Updates the CHS fields in partition records to reflect a new BIOS geometry.
/// </summary>
/// <param name="geometry">The disk's new BIOS geometry</param>
/// <remarks>The partitions are not relocated to a cylinder boundary, just the CHS fields are updated on the
/// assumption the LBA fields are definitive.</remarks>
public void UpdateBiosGeometry(Geometry geometry)
{
_diskData.Position = 0;
byte[] bootSector = Utilities.ReadFully(_diskData, Utilities.SectorSize);
BiosPartitionRecord[] records = ReadPrimaryRecords(bootSector);
for (int i = 0; i < records.Length; ++i)
{
BiosPartitionRecord record = records[i];
if (record.IsValid)
{
ChsAddress newStartAddress = geometry.ToChsAddress(record.LBAStartAbsolute);
if (newStartAddress.Cylinder > 1023)
{
newStartAddress = new ChsAddress(1023, geometry.HeadsPerCylinder - 1, geometry.SectorsPerTrack);
}
ChsAddress newEndAddress = geometry.ToChsAddress(record.LBAStartAbsolute + record.LBALength - 1);
if (newEndAddress.Cylinder > 1023)
{
newEndAddress = new ChsAddress(1023, geometry.HeadsPerCylinder - 1, geometry.SectorsPerTrack);
}
record.StartCylinder = (ushort)newStartAddress.Cylinder;
record.StartHead = (byte)newStartAddress.Head;
record.StartSector = (byte)newStartAddress.Sector;
record.EndCylinder = (ushort)newEndAddress.Cylinder;
record.EndHead = (byte)newEndAddress.Head;
record.EndSector = (byte)newEndAddress.Sector;
WriteRecord(i, record);
}
}
_diskGeometry = geometry;
}
internal SparseStream Open(BiosPartitionRecord record)
{
return new SubStream(_diskData, Ownership.None, ((long)record.LBAStartAbsolute) * Utilities.SectorSize, ((long)record.LBALength) * Utilities.SectorSize);
}
private static BiosPartitionRecord[] ReadPrimaryRecords(byte[] bootSector)
{
BiosPartitionRecord[] records = new BiosPartitionRecord[4];
for (int i = 0; i < 4; ++i)
{
records[i] = new BiosPartitionRecord(bootSector, 0x01BE + (i * 0x10), 0, i);
}
return records;
}
private static bool IsExtendedPartition(BiosPartitionRecord r)
{
return r.PartitionType == BiosPartitionTypes.Extended || r.PartitionType == BiosPartitionTypes.ExtendedLba;
}
private static byte ConvertType(WellKnownPartitionType type, long size)
{
switch (type)
{
case WellKnownPartitionType.WindowsFat:
if (size < 512 * Sizes.OneMiB)
{
return BiosPartitionTypes.Fat16;
}
else if (size < 1023 * (long)254 * 63 * 512)
{
// Max BIOS size
return BiosPartitionTypes.Fat32;
}
else
{
return BiosPartitionTypes.Fat32Lba;
}
case WellKnownPartitionType.WindowsNtfs:
return BiosPartitionTypes.Ntfs;
case WellKnownPartitionType.Linux:
return BiosPartitionTypes.LinuxNative;
case WellKnownPartitionType.LinuxSwap:
return BiosPartitionTypes.LinuxSwap;
case WellKnownPartitionType.LinuxLvm:
return BiosPartitionTypes.LinuxLvm;
default:
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Unrecognized partition type: '{0}'", type), "type");
}
}
private BiosPartitionRecord[] GetAllRecords()
{
List<BiosPartitionRecord> newList = new List<BiosPartitionRecord>();
foreach (BiosPartitionRecord primaryRecord in GetPrimaryRecords())
{
if (primaryRecord.IsValid)
{
if (IsExtendedPartition(primaryRecord))
{
newList.AddRange(GetExtendedRecords(primaryRecord));
}
else
{
newList.Add(primaryRecord);
}
}
}
return newList.ToArray();
}
private BiosPartitionRecord[] GetPrimaryRecords()
{
_diskData.Position = 0;
byte[] bootSector = Utilities.ReadFully(_diskData, Utilities.SectorSize);
return ReadPrimaryRecords(bootSector);
}
private BiosPartitionRecord[] GetExtendedRecords(BiosPartitionRecord r)
{
return new BiosExtendedPartitionTable(_diskData, r.LBAStart).GetPartitions();
}
private void WriteRecord(int i, BiosPartitionRecord newRecord)
{
_diskData.Position = 0;
byte[] bootSector = Utilities.ReadFully(_diskData, Utilities.SectorSize);
newRecord.WriteTo(bootSector, 0x01BE + (i * 16));
_diskData.Position = 0;
_diskData.Write(bootSector, 0, bootSector.Length);
}
private int FindCylinderGap(int numCylinders)
{
var list = Utilities.Filter<List<BiosPartitionRecord>, BiosPartitionRecord>(GetPrimaryRecords(), (r) => r.IsValid);
list.Sort();
int startCylinder = 0;
foreach (var r in list)
{
int existingStart = r.StartCylinder;
int existingEnd = r.EndCylinder;
// LBA can represent bigger disk locations than CHS, so assume the LBA to be definitive in the case where it
// appears the CHS address has been truncated.
if (r.LBAStart > _diskGeometry.ToLogicalBlockAddress(r.StartCylinder, r.StartHead, r.StartSector))
{
existingStart = _diskGeometry.ToChsAddress((int)r.LBAStart).Cylinder;
}
if (r.LBAStart + r.LBALength > _diskGeometry.ToLogicalBlockAddress(r.EndCylinder, r.EndHead, r.EndSector))
{
existingEnd = _diskGeometry.ToChsAddress((int)(r.LBAStart + r.LBALength)).Cylinder;
}
if (!Utilities.RangesOverlap(startCylinder, startCylinder + numCylinders - 1, existingStart, existingEnd))
{
break;
}
else
{
startCylinder = existingEnd + 1;
}
}
return startCylinder;
}
private long FindGap(long numSectors, long alignmentSectors)
{
var list = Utilities.Filter<List<BiosPartitionRecord>, BiosPartitionRecord>(GetPrimaryRecords(), (r) => r.IsValid);
list.Sort();
long startSector = Utilities.RoundUp(_diskGeometry.ToLogicalBlockAddress(0, 1, 1), alignmentSectors);
int idx = 0;
while (idx < list.Count)
{
var entry = list[idx];
while (idx < list.Count && startSector >= entry.LBAStartAbsolute + entry.LBALength)
{
idx++;
entry = list[idx];
}
if (Utilities.RangesOverlap(startSector, startSector + numSectors, entry.LBAStartAbsolute, entry.LBAStartAbsolute + entry.LBALength))
{
startSector = Utilities.RoundUp(entry.LBAStartAbsolute + entry.LBALength, alignmentSectors);
}
idx++;
}
if (_diskGeometry.TotalSectorsLong - startSector < numSectors)
{
throw new IOException(string.Format(CultureInfo.InvariantCulture, "Unable to find free space of {0} sectors", numSectors));
}
return startSector;
}
private void Init(Stream disk, Geometry diskGeometry)
{
_diskData = disk;
_diskGeometry = diskGeometry;
_diskData.Position = 0;
byte[] bootSector = Utilities.ReadFully(_diskData, Utilities.SectorSize);
if (bootSector[510] != 0x55 || bootSector[511] != 0xAA)
{
throw new IOException("Invalid boot sector - no magic number 0xAA55");
}
}
}
}
| |
#region License and Terms
// /***************************************************************************
// Copyright (c) 2015 Conplement AG
//
// 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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace TFSWebService.Website.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator" /> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage" /> or
/// <see cref="HttpResponseMessage" />.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null" /> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)" /> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription" />.
/// </summary>
/// <param name="api">The <see cref="ApiDescription" />.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription" />.
/// </summary>
/// <param name="api">The <see cref="ApiDescription" />.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription" />.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api,
SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof (HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter,
mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples" />.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName,
IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType,
SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (
ActionSamples.TryGetValue(
new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames),
out sample) ||
ActionSamples.TryGetValue(
new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] {"*"}),
out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects" />. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory" /> (which wraps an <see cref="ObjectGenerator" />) and other
/// factories in <see cref="SampleObjectFactories" />.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification =
"Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}" /> passed to the
/// <see cref="System.Net.Http.HttpRequestMessage" /> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription" />.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage" /> or
/// <see cref="HttpResponseMessage" /> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription" />.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters",
Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName,
IEnumerable<string> parameterNames, SampleDirection sampleDirection,
out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof (SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int) sampleDirection,
typeof (SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (
ActualHttpMessageTypes.TryGetValue(
new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(
new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] {"*"}), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter =
api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null
? null
: requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type,
MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName,
string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] {"*"}) ||
parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils
{
using System;
using System.Collections.Generic;
/// <summary>
/// Represents a range of bytes in a stream.
/// </summary>
/// <remarks>This is normally used to represent regions of a SparseStream that
/// are actually stored in the underlying storage medium (rather than implied
/// zero bytes). Extents are stored as a zero-based byte offset (from the
/// beginning of the stream), and a byte length.</remarks>
public sealed class StreamExtent : IEquatable<StreamExtent>, IComparable<StreamExtent>
{
private long _start;
private long _length;
/// <summary>
/// Initializes a new instance of the StreamExtent class.
/// </summary>
/// <param name="start">The start of the extent.</param>
/// <param name="length">The length of the extent.</param>
public StreamExtent(long start, long length)
{
_start = start;
_length = length;
}
/// <summary>
/// Gets the start of the extent (in bytes).
/// </summary>
public long Start
{
get { return _start; }
}
/// <summary>
/// Gets the start of the extent (in bytes).
/// </summary>
public long Length
{
get { return _length; }
}
/// <summary>
/// Calculates the union of a list of extents with another extent.
/// </summary>
/// <param name="extents">The list of extents.</param>
/// <param name="other">The other extent.</param>
/// <returns>The union of the extents.</returns>
public static IEnumerable<StreamExtent> Union(IEnumerable<StreamExtent> extents, StreamExtent other)
{
List<StreamExtent> otherList = new List<StreamExtent>();
otherList.Add(other);
return Union(extents, otherList);
}
/// <summary>
/// Calculates the union of the extents of multiple streams.
/// </summary>
/// <param name="streams">The stream extents.</param>
/// <returns>The union of the extents from multiple streams.</returns>
/// <remarks>A typical use of this method is to calculate the combined set of
/// stored extents from a number of overlayed sparse streams.</remarks>
public static IEnumerable<StreamExtent> Union(params IEnumerable<StreamExtent>[] streams)
{
long extentStart = long.MaxValue;
long extentEnd = 0;
// Initialize enumerations and find first stored byte position
IEnumerator<StreamExtent>[] enums = new IEnumerator<StreamExtent>[streams.Length];
bool[] streamsValid = new bool[streams.Length];
int validStreamsRemaining = 0;
for (int i = 0; i < streams.Length; ++i)
{
enums[i] = streams[i].GetEnumerator();
streamsValid[i] = enums[i].MoveNext();
if (streamsValid[i])
{
++validStreamsRemaining;
if (enums[i].Current.Start < extentStart)
{
extentStart = enums[i].Current.Start;
extentEnd = enums[i].Current.Start + enums[i].Current.Length;
}
}
}
while (validStreamsRemaining > 0)
{
// Find the end of this extent
bool foundIntersection;
do
{
foundIntersection = false;
validStreamsRemaining = 0;
for (int i = 0; i < streams.Length; ++i)
{
while (streamsValid[i] && enums[i].Current.Start + enums[i].Current.Length <= extentEnd)
{
streamsValid[i] = enums[i].MoveNext();
}
if (streamsValid[i])
{
++validStreamsRemaining;
}
if (streamsValid[i] && enums[i].Current.Start <= extentEnd)
{
extentEnd = enums[i].Current.Start + enums[i].Current.Length;
foundIntersection = true;
streamsValid[i] = enums[i].MoveNext();
}
}
}
while (foundIntersection && validStreamsRemaining > 0);
// Return the discovered extent
yield return new StreamExtent(extentStart, extentEnd - extentStart);
// Find the next extent start point
extentStart = long.MaxValue;
validStreamsRemaining = 0;
for (int i = 0; i < streams.Length; ++i)
{
if (streamsValid[i])
{
++validStreamsRemaining;
if (enums[i].Current.Start < extentStart)
{
extentStart = enums[i].Current.Start;
extentEnd = enums[i].Current.Start + enums[i].Current.Length;
}
}
}
}
}
/// <summary>
/// Calculates the intersection of the extents of a stream with another extent.
/// </summary>
/// <param name="extents">The stream extents.</param>
/// <param name="other">The extent to intersect.</param>
/// <returns>The intersection of the extents.</returns>
public static IEnumerable<StreamExtent> Intersect(IEnumerable<StreamExtent> extents, StreamExtent other)
{
List<StreamExtent> otherList = new List<StreamExtent>(1);
otherList.Add(other);
return Intersect(extents, otherList);
}
/// <summary>
/// Calculates the intersection of the extents of multiple streams.
/// </summary>
/// <param name="streams">The stream extents.</param>
/// <returns>The intersection of the extents from multiple streams.</returns>
/// <remarks>A typical use of this method is to calculate the extents in a
/// region of a stream..</remarks>
public static IEnumerable<StreamExtent> Intersect(params IEnumerable<StreamExtent>[] streams)
{
long extentStart = long.MinValue;
long extentEnd = long.MaxValue;
IEnumerator<StreamExtent>[] enums = new IEnumerator<StreamExtent>[streams.Length];
for (int i = 0; i < streams.Length; ++i)
{
enums[i] = streams[i].GetEnumerator();
if (!enums[i].MoveNext())
{
// Gone past end of one stream (in practice was empty), so no intersections
yield break;
}
}
int overlapsFound = 0;
while (true)
{
// We keep cycling round the streams, until we get streams.Length continuous overlaps
for (int i = 0; i < streams.Length; ++i)
{
// Move stream on past all extents that are earlier than our candidate start point
while (enums[i].Current.Length == 0
|| enums[i].Current.Start + enums[i].Current.Length <= extentStart)
{
if (!enums[i].MoveNext())
{
// Gone past end of this stream, no more intersections possible
yield break;
}
}
// If this stream has an extent that spans over the candidate start point
if (enums[i].Current.Start <= extentStart)
{
extentEnd = Math.Min(extentEnd, enums[i].Current.Start + enums[i].Current.Length);
overlapsFound++;
}
else
{
extentStart = enums[i].Current.Start;
extentEnd = extentStart + enums[i].Current.Length;
overlapsFound = 1;
}
// We've just done a complete loop of all streams, they overlapped this start position
// and we've cut the extent's end down to the shortest run.
if (overlapsFound == streams.Length)
{
yield return new StreamExtent(extentStart, extentEnd - extentStart);
extentStart = extentEnd;
extentEnd = long.MaxValue;
overlapsFound = 0;
}
}
}
}
/// <summary>
/// Calculates the subtraction of the extents of a stream by another extent.
/// </summary>
/// <param name="extents">The stream extents.</param>
/// <param name="other">The extent to subtract.</param>
/// <returns>The subtraction of <c>other</c> from <c>extents</c>.</returns>
public static IEnumerable<StreamExtent> Subtract(IEnumerable<StreamExtent> extents, StreamExtent other)
{
return Subtract(extents, new StreamExtent[] { other });
}
/// <summary>
/// Calculates the subtraction of the extents of a stream by another stream.
/// </summary>
/// <param name="a">The stream extents to subtract from.</param>
/// <param name="b">The stream extents to subtract.</param>
/// <returns>The subtraction of the extents of b from a.</returns>
public static IEnumerable<StreamExtent> Subtract(IEnumerable<StreamExtent> a, IEnumerable<StreamExtent> b)
{
return Intersect(a, Invert(b));
}
/// <summary>
/// Calculates the inverse of the extents of a stream.
/// </summary>
/// <param name="extents">The stream extents to inverse.</param>
/// <returns>The inverted extents.</returns>
/// <remarks>
/// This method assumes a logical stream addressable from <c>0</c> to <c>long.MaxValue</c>, and is undefined
/// should any stream extent start at less than 0. To constrain the extents to a specific range, use the
/// <c>Intersect</c> method.
/// </remarks>
public static IEnumerable<StreamExtent> Invert(IEnumerable<StreamExtent> extents)
{
StreamExtent last = new StreamExtent(0, 0);
foreach (StreamExtent extent in extents)
{
// Skip over any 'noise'
if (extent.Length == 0)
{
continue;
}
long lastEnd = last.Start + last.Length;
if (lastEnd < extent.Start)
{
yield return new StreamExtent(lastEnd, extent.Start - lastEnd);
}
last = extent;
}
long finalEnd = last.Start + last.Length;
if (finalEnd < long.MaxValue)
{
yield return new StreamExtent(finalEnd, long.MaxValue - finalEnd);
}
}
/// <summary>
/// Offsets the extents of a stream.
/// </summary>
/// <param name="stream">The stream extents.</param>
/// <param name="delta">The amount to offset the extents by.</param>
/// <returns>The stream extents, offset by delta.</returns>
public static IEnumerable<StreamExtent> Offset(IEnumerable<StreamExtent> stream, long delta)
{
foreach (StreamExtent extent in stream)
{
yield return new StreamExtent(extent.Start + delta, extent.Length);
}
}
/// <summary>
/// Returns the number of blocks containing stream data.
/// </summary>
/// <param name="stream">The stream extents.</param>
/// <param name="blockSize">The size of each block.</param>
/// <returns>The number of blocks containing stream data.</returns>
/// <remarks>This method logically divides the stream into blocks of a specified
/// size, then indicates how many of those blocks contain actual stream data.</remarks>
public static long BlockCount(IEnumerable<StreamExtent> stream, long blockSize)
{
long totalBlocks = 0;
long lastBlock = -1;
foreach (var extent in stream)
{
if (extent.Length > 0)
{
long extentStartBlock = extent.Start / blockSize;
long extentNextBlock = Utilities.Ceil(extent.Start + extent.Length, blockSize);
long extentNumBlocks = extentNextBlock - extentStartBlock;
if (extentStartBlock == lastBlock)
{
extentNumBlocks--;
}
lastBlock = extentNextBlock - 1;
totalBlocks += extentNumBlocks;
}
}
return totalBlocks;
}
/// <summary>
/// Returns all of the blocks containing stream data.
/// </summary>
/// <param name="stream">The stream extents.</param>
/// <param name="blockSize">The size of each block.</param>
/// <returns>Ranges of blocks, as block indexes.</returns>
/// <remarks>This method logically divides the stream into blocks of a specified
/// size, then indicates ranges of blocks that contain stream data.</remarks>
public static IEnumerable<Range<long, long>> Blocks(IEnumerable<StreamExtent> stream, long blockSize)
{
long? rangeStart = null;
long rangeLength = 0;
foreach (var extent in stream)
{
if (extent.Length > 0)
{
long extentStartBlock = extent.Start / blockSize;
long extentNextBlock = Utilities.Ceil(extent.Start + extent.Length, blockSize);
if (rangeStart != null && extentStartBlock > rangeStart + rangeLength)
{
// This extent is non-contiguous (in terms of blocks), so write out the last range and start new
yield return new Range<long, long>((long)rangeStart, rangeLength);
rangeStart = extentStartBlock;
}
else if (rangeStart == null)
{
// First extent, so start first range
rangeStart = extentStartBlock;
}
// Set the length of the current range, based on the end of this extent
rangeLength = extentNextBlock - (long)rangeStart;
}
}
// Final range (if any ranges at all) hasn't been returned yet, so do that now
if (rangeStart != null)
{
yield return new Range<long, long>((long)rangeStart, rangeLength);
}
}
/// <summary>
/// The equality operator.
/// </summary>
/// <param name="a">The first extent to compare.</param>
/// <param name="b">The second extent to compare.</param>
/// <returns>Whether the two extents are equal.</returns>
public static bool operator ==(StreamExtent a, StreamExtent b)
{
if (Object.ReferenceEquals(a, null))
{
return Object.ReferenceEquals(b, null);
}
else
{
return a.Equals(b);
}
}
/// <summary>
/// The inequality operator.
/// </summary>
/// <param name="a">The first extent to compare.</param>
/// <param name="b">The second extent to compare.</param>
/// <returns>Whether the two extents are different.</returns>
public static bool operator !=(StreamExtent a, StreamExtent b)
{
return !(a == b);
}
/// <summary>
/// The less-than operator.
/// </summary>
/// <param name="a">The first extent to compare.</param>
/// <param name="b">The second extent to compare.</param>
/// <returns>Whether a is less than b.</returns>
public static bool operator <(StreamExtent a, StreamExtent b)
{
return a.CompareTo(b) < 0;
}
/// <summary>
/// The greater-than operator.
/// </summary>
/// <param name="a">The first extent to compare.</param>
/// <param name="b">The second extent to compare.</param>
/// <returns>Whether a is greater than b.</returns>
public static bool operator >(StreamExtent a, StreamExtent b)
{
return a.CompareTo(b) > 0;
}
/// <summary>
/// Indicates if this StreamExtent is equal to another.
/// </summary>
/// <param name="other">The extent to compare.</param>
/// <returns><c>true</c> if the extents are equal, else <c>false</c>.</returns>
public bool Equals(StreamExtent other)
{
if (other == null)
{
return false;
}
else
{
return _start == other._start && _length == other._length;
}
}
/// <summary>
/// Returns a string representation of the extent as [start:+length].
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
return "[" + _start + ":+" + _length + "]";
}
/// <summary>
/// Indicates if this stream extent is equal to another object.
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if <c>obj</c> is equivalent, else <c>false</c>.</returns>
public override bool Equals(object obj)
{
return Equals(obj as StreamExtent);
}
/// <summary>
/// Gets a hash code for this extent.
/// </summary>
/// <returns>The extent's hash code.</returns>
public override int GetHashCode()
{
return _start.GetHashCode() ^ _length.GetHashCode();
}
/// <summary>
/// Compares this stream extent to another.
/// </summary>
/// <param name="other">The extent to compare.</param>
/// <returns>Value greater than zero if this extent starts after
/// <c>other</c>, zero if they start at the same position, else
/// a value less than zero.</returns>
public int CompareTo(StreamExtent other)
{
if (_start > other._start)
{
return 1;
}
else if (_start == other._start)
{
return 0;
}
else
{
return -1;
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CoreGraphicsRenderContext.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Implements a <see cref="IRenderContext"/> for CoreGraphics.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.Xamarin.Mac
{
using System;
using System.Collections.Generic;
using System.Linq;
using AppKit;
using CoreGraphics;
using CoreText;
using Foundation;
/// <summary>
/// Implements a <see cref="IRenderContext"/> for CoreGraphics.
/// </summary>
public class CoreGraphicsRenderContext : RenderContextBase, IDisposable
{
/// <summary>
/// The images in use.
/// </summary>
private readonly HashSet<OxyImage> imagesInUse = new HashSet<OxyImage> ();
/// <summary>
/// The fonts cache.
/// </summary>
private readonly Dictionary<string, CTFont> fonts = new Dictionary<string, CTFont> ();
/// <summary>
/// The image cache.
/// </summary>
private readonly Dictionary<OxyImage, NSImage> imageCache = new Dictionary<OxyImage, NSImage> ();
/// <summary>
/// The graphics context.
/// </summary>
private readonly CGContext gctx;
/// <summary>
/// Initializes a new instance of the <see cref="CoreGraphicsRenderContext"/> class.
/// </summary>
/// <param name="context">The context.</param>
public CoreGraphicsRenderContext (CGContext context)
{
this.gctx = context;
// Set rendering quality
this.gctx.SetAllowsFontSmoothing (true);
this.gctx.SetAllowsFontSubpixelQuantization (true);
this.gctx.SetAllowsAntialiasing (true);
this.gctx.SetShouldSmoothFonts (true);
this.gctx.SetShouldAntialias (true);
this.gctx.InterpolationQuality = CGInterpolationQuality.High;
this.gctx.SetTextDrawingMode (CGTextDrawingMode.Fill);
this.gctx.TextMatrix = CGAffineTransform.MakeScale (1, 1);
}
/// <summary>
/// Draws an ellipse.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The thickness.</param>
public override void DrawEllipse (OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
this.SetAlias (false);
var convertedRectangle = rect.Convert ();
if (fill.IsVisible ()) {
this.SetFill (fill);
using (var path = new CGPath ()) {
path.AddEllipseInRect (convertedRectangle);
this.gctx.AddPath (path);
}
this.gctx.DrawPath (CGPathDrawingMode.Fill);
}
if (stroke.IsVisible () && thickness > 0) {
this.SetStroke (stroke, thickness);
using (var path = new CGPath ()) {
path.AddEllipseInRect (convertedRectangle);
this.gctx.AddPath (path);
}
this.gctx.DrawPath (CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws the specified portion of the specified <see cref="OxyImage" /> at the specified location and with the specified size.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="srcX">The x-coordinate of the upper-left corner of the portion of the source image to draw.</param>
/// <param name="srcY">The y-coordinate of the upper-left corner of the portion of the source image to draw.</param>
/// <param name="srcWidth">Width of the portion of the source image to draw.</param>
/// <param name="srcHeight">Height of the portion of the source image to draw.</param>
/// <param name="destX">The x-coordinate of the upper-left corner of drawn image.</param>
/// <param name="destY">The y-coordinate of the upper-left corner of drawn image.</param>
/// <param name="destWidth">The width of the drawn image.</param>
/// <param name="destHeight">The height of the drawn image.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolate">Interpolate if set to <c>true</c>.</param>
public override void DrawImage (OxyImage source, double srcX, double srcY, double srcWidth, double srcHeight, double destX, double destY, double destWidth, double destHeight, double opacity, bool interpolate)
{
var image = this.GetImage (source);
if (image == null) {
return;
}
this.gctx.SaveState ();
double x = destX - (srcX / srcWidth * destWidth);
double y = destY - (srcY / srcHeight * destHeight);
this.gctx.ScaleCTM (1, -1);
this.gctx.TranslateCTM ((float)x, -(float)(y + destHeight));
this.gctx.SetAlpha ((float)opacity);
this.gctx.InterpolationQuality = interpolate ? CGInterpolationQuality.High : CGInterpolationQuality.None;
var destRect = new CGRect (0f, 0f, (float)destWidth, (float)destHeight);
this.gctx.DrawImage (destRect, image.CGImage);
this.gctx.RestoreState ();
}
/// <summary>
/// Cleans up resources not in use.
/// </summary>
/// <remarks>This method is called at the end of each rendering.</remarks>
public override void CleanUp ()
{
var imagesToRelease = this.imageCache.Keys.Where (i => !this.imagesInUse.Contains (i)).ToList ();
foreach (var i in imagesToRelease) {
var image = this.GetImage (i);
image.Dispose ();
this.imageCache.Remove (i);
}
this.imagesInUse.Clear ();
}
/// <summary>
/// Sets the clip rectangle.
/// </summary>
/// <param name="rect">The clip rectangle.</param>
/// <returns>True if the clip rectangle was set.</returns>
public override bool SetClip (OxyRect rect)
{
this.gctx.SaveState ();
this.gctx.ClipToRect (rect.Convert ());
return true;
}
/// <summary>
/// Resets the clip rectangle.
/// </summary>
public override void ResetClip ()
{
this.gctx.RestoreState ();
}
/// <summary>
/// Draws a polyline.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param>
public override void DrawLine (IList<ScreenPoint> points, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased)
{
if (stroke.IsVisible () && thickness > 0) {
this.SetAlias (aliased);
this.SetStroke (stroke, thickness, dashArray, lineJoin);
using (var path = new CGPath ()) {
var convertedPoints = (aliased ? points.Select (p => p.ConvertAliased ()) : points.Select (p => p.Convert ())).ToArray ();
path.AddLines (convertedPoints);
this.gctx.AddPath (path);
}
this.gctx.DrawPath (CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws a polygon. The polygon can have stroke and/or fill.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">If set to <c>true</c> the shape will be aliased.</param>
public override void DrawPolygon (IList<ScreenPoint> points, OxyColor fill, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased)
{
this.SetAlias (aliased);
var convertedPoints = (aliased ? points.Select (p => p.ConvertAliased ()) : points.Select (p => p.Convert ())).ToArray ();
if (fill.IsVisible ()) {
this.SetFill (fill);
using (var path = new CGPath ()) {
path.AddLines (convertedPoints);
path.CloseSubpath ();
this.gctx.AddPath (path);
}
this.gctx.DrawPath (CGPathDrawingMode.Fill);
}
if (stroke.IsVisible () && thickness > 0) {
this.SetStroke (stroke, thickness, dashArray, lineJoin);
using (var path = new CGPath ()) {
path.AddLines (convertedPoints);
path.CloseSubpath ();
this.gctx.AddPath (path);
}
this.gctx.DrawPath (CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws a rectangle.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
public override void DrawRectangle (OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
this.SetAlias (true);
var convertedRect = rect.ConvertAliased ();
if (fill.IsVisible ()) {
this.SetFill (fill);
using (var path = new CGPath ()) {
path.AddRect (convertedRect);
this.gctx.AddPath (path);
}
this.gctx.DrawPath (CGPathDrawingMode.Fill);
}
if (stroke.IsVisible () && thickness > 0) {
this.SetStroke (stroke, thickness);
using (var path = new CGPath ()) {
path.AddRect (convertedRect);
this.gctx.AddPath (path);
}
this.gctx.DrawPath (CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws the text.
/// </summary>
/// <param name="p">The position of the text.</param>
/// <param name="text">The text.</param>
/// <param name="fill">The fill color.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="fontWeight">The font weight.</param>
/// <param name="rotate">The rotation angle.</param>
/// <param name="halign">The horizontal alignment.</param>
/// <param name="valign">The vertical alignment.</param>
/// <param name="maxSize">The maximum size of the text.</param>
public override void DrawText (ScreenPoint p, string text, OxyColor fill, string fontFamily, double fontSize, double fontWeight, double rotate, HorizontalAlignment halign, VerticalAlignment valign, OxySize? maxSize)
{
if (string.IsNullOrEmpty (text)) {
return;
}
var fontName = GetActualFontName (fontFamily, fontWeight);
var font = this.GetCachedFont (fontName, fontSize);
using (var attributedString = new NSAttributedString (text, new CTStringAttributes {
ForegroundColorFromContext = true,
Font = font
})) {
using (var textLine = new CTLine (attributedString)) {
nfloat width;
nfloat height;
this.gctx.TextPosition = new CGPoint (0, 0);
this.GetFontMetrics(font, out nfloat lineHeight, out nfloat delta);
var bounds = textLine.GetImageBounds (this.gctx);
var x0 = 0;
var y0 = delta;
if (maxSize.HasValue || halign != HorizontalAlignment.Left || valign != VerticalAlignment.Bottom) {
width = bounds.Left + bounds.Width;
height = lineHeight;
} else {
width = height = 0f;
}
if (maxSize.HasValue) {
if (width > maxSize.Value.Width) {
width = (float)maxSize.Value.Width;
}
if (height > maxSize.Value.Height) {
height = (float)maxSize.Value.Height;
}
}
var dx = halign == HorizontalAlignment.Left ? 0d : (halign == HorizontalAlignment.Center ? -width * 0.5 : -width);
var dy = valign == VerticalAlignment.Bottom ? 0d : (valign == VerticalAlignment.Middle ? height * 0.5 : height);
this.SetFill (fill);
this.SetAlias (false);
this.gctx.SaveState ();
this.gctx.TranslateCTM ((float)p.X, (float)p.Y);
if (!rotate.Equals (0)) {
this.gctx.RotateCTM ((float)(rotate / 180 * Math.PI));
}
this.gctx.TranslateCTM ((float)dx + x0, (float)dy + y0);
this.gctx.ScaleCTM (1f, -1f);
if (maxSize.HasValue) {
var clipRect = new CGRect (-x0, y0, (float)Math.Ceiling (width), (float)Math.Ceiling (height));
this.gctx.ClipToRect (clipRect);
}
textLine.Draw (this.gctx);
this.gctx.RestoreState ();
}
}
}
/// <summary>
/// Measures the text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>
/// The size of the text.
/// </returns>
public override OxySize MeasureText (string text, string fontFamily, double fontSize, double fontWeight)
{
if (string.IsNullOrEmpty (text) || fontFamily == null) {
return OxySize.Empty;
}
var fontName = GetActualFontName (fontFamily, fontWeight);
var font = this.GetCachedFont (fontName, (float)fontSize);
using (var attributedString = new NSAttributedString (text, new CTStringAttributes {
ForegroundColorFromContext = true,
Font = font
})) {
using (var textLine = new CTLine (attributedString)) {
this.GetFontMetrics(font, out nfloat lineHeight, out nfloat delta);
// the text position must be set to get the correct bounds
this.gctx.TextPosition = new CGPoint (0, 0);
var bounds = textLine.GetImageBounds (this.gctx);
var width = bounds.Left + bounds.Width;
return new OxySize (width, lineHeight);
}
}
}
/// <summary>
/// Releases all resource used by the <see cref="OxyPlot.Xamarin.Mac.CoreGraphicsRenderContext"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the
/// <see cref="OxyPlot.Xamarin.Mac.CoreGraphicsRenderContext"/>. The <see cref="Dispose"/> method leaves the
/// <see cref="OxyPlot.Xamarin.Mac.CoreGraphicsRenderContext"/> in an unusable state. After calling
/// <see cref="Dispose"/>, you must release all references to the
/// <see cref="OxyPlot.Xamarin.Mac.CoreGraphicsRenderContext"/> so the garbage collector can reclaim the memory that
/// the <see cref="OxyPlot.Xamarin.Mac.CoreGraphicsRenderContext"/> was occupying.</remarks>
public void Dispose ()
{
foreach (var image in this.imageCache.Values) {
image.Dispose ();
}
foreach (var font in this.fonts.Values) {
font.Dispose ();
}
}
/// <summary>
/// Gets the actual font for iOS.
/// </summary>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>The actual font name.</returns>
private static string GetActualFontName (string fontFamily, double fontWeight)
{
string fontName;
switch (fontFamily) {
case null:
case "Segoe UI":
fontName = "HelveticaNeue";
break;
case "Arial":
fontName = "ArialMT";
break;
case "Times":
case "Times New Roman":
fontName = "TimesNewRomanPSMT";
break;
case "Courier New":
fontName = "CourierNewPSMT";
break;
default:
fontName = fontFamily;
break;
}
if (fontWeight >= 700) {
fontName += "-Bold";
}
return fontName;
}
/// <summary>
/// Gets font metrics for the specified font.
/// </summary>
/// <param name="font">The font.</param>
/// <param name="defaultLineHeight">Default line height.</param>
/// <param name="delta">The vertical delta.</param>
private void GetFontMetrics (CTFont font, out nfloat defaultLineHeight, out nfloat delta)
{
var ascent = font.AscentMetric;
var descent = font.DescentMetric;
var leading = font.LeadingMetric;
//// http://stackoverflow.com/questions/5511830/how-does-line-spacing-work-in-core-text-and-why-is-it-different-from-nslayoutm
leading = leading < 0 ? 0 : (float)Math.Floor (leading + 0.5f);
var lineHeight = (nfloat)Math.Floor (ascent + 0.5f) + (nfloat)Math.Floor (descent + 0.5) + leading;
var ascenderDelta = leading >= 0 ? 0 : (nfloat)Math.Floor ((0.2 * lineHeight) + 0.5);
defaultLineHeight = lineHeight + ascenderDelta;
delta = ascenderDelta - descent;
}
/// <summary>
/// Gets the specified from cache.
/// </summary>
/// <returns>The font.</returns>
/// <param name="fontName">Font name.</param>
/// <param name="fontSize">Font size.</param>
private CTFont GetCachedFont (string fontName, double fontSize)
{
var key = fontName + fontSize.ToString ("0.###");
if (this.fonts.TryGetValue(key, out CTFont font))
{
return font;
}
return this.fonts [key] = new CTFont (fontName, (nfloat)fontSize);
}
/// <summary>
/// Sets the alias state.
/// </summary>
/// <param name="alias">alias if set to <c>true</c>.</param>
private void SetAlias (bool alias)
{
this.gctx.SetShouldAntialias (!alias);
}
/// <summary>
/// Sets the fill color.
/// </summary>
/// <param name="c">The color.</param>
private void SetFill (OxyColor c)
{
this.gctx.SetFillColor (c.ToCGColor ());
}
/// <summary>
/// Sets the stroke style.
/// </summary>
/// <param name="c">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join.</param>
private void SetStroke (OxyColor c, double thickness, double[] dashArray = null, LineJoin lineJoin = LineJoin.Miter)
{
this.gctx.SetStrokeColor (c.ToCGColor ());
this.gctx.SetLineWidth ((float)thickness);
this.gctx.SetLineJoin (lineJoin.Convert ());
if (dashArray != null) {
var lengths = dashArray.Select (d => (nfloat)d).ToArray ();
this.gctx.SetLineDash (0f, lengths);
} else {
this.gctx.SetLineDash (0, null);
}
}
/// <summary>
/// Gets the image from cache or converts the specified <paramref name="source"/> <see cref="OxyImage"/>.
/// </summary>
/// <param name="source">The source.</param>
/// <returns>The image.</returns>
private NSImage GetImage (OxyImage source)
{
if (source == null) {
return null;
}
if (!this.imagesInUse.Contains (source)) {
this.imagesInUse.Add (source);
}
if (!this.imageCache.TryGetValue(source, out NSImage src))
{
using (var ms = new System.IO.MemoryStream(source.GetData()))
{
src = NSImage.FromStream(ms);
}
if (src != null)
{
this.imageCache.Add(source, src);
}
}
return src;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
public struct SendReply
{
public bool Success;
public string Message;
public int Disposition;
}
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "OfflineMessageModule")]
public class OfflineMessageModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool enabled = true;
private List<Scene> m_SceneList = new List<Scene>();
private string m_RestURL = String.Empty;
IMessageTransferModule m_TransferModule = null;
private bool m_ForwardOfflineGroupMessages = true;
private Dictionary<IClientAPI, List<UUID>> m_repliesSent= new Dictionary<IClientAPI, List<UUID>>();
public void Initialise(IConfigSource config)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf == null)
{
enabled = false;
return;
}
if (cnf != null && cnf.GetString("OfflineMessageModule", "None") !=
"OfflineMessageModule")
{
enabled = false;
return;
}
m_RestURL = cnf.GetString("OfflineMessageURL", "");
if (m_RestURL == "")
{
m_log.Error("[OFFLINE MESSAGING] Module was enabled, but no URL is given, disabling");
enabled = false;
return;
}
m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", m_ForwardOfflineGroupMessages);
}
public void AddRegion(Scene scene)
{
if (!enabled)
return;
lock (m_SceneList)
{
m_SceneList.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
}
}
public void RegionLoaded(Scene scene)
{
if (!enabled)
return;
if (m_TransferModule == null)
{
m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
{
scene.EventManager.OnNewClient -= OnNewClient;
enabled = false;
m_SceneList.Clear();
m_log.Error("[OFFLINE MESSAGING] No message transfer module is enabled. Diabling offline messages");
}
m_TransferModule.OnUndeliveredMessage += UndeliveredMessage;
}
}
public void RemoveRegion(Scene scene)
{
if (!enabled)
return;
lock (m_SceneList)
{
m_SceneList.Remove(scene);
}
}
public void PostInitialise()
{
if (!enabled)
return;
m_log.Debug("[OFFLINE MESSAGING] Offline messages enabled");
}
public string Name
{
get { return "OfflineMessageModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Close()
{
}
private Scene FindScene(UUID agentID)
{
foreach (Scene s in m_SceneList)
{
ScenePresence presence = s.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return s;
}
return null;
}
private IClientAPI FindClient(UUID agentID)
{
foreach (Scene s in m_SceneList)
{
ScenePresence presence = s.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return presence.ControllingClient;
}
return null;
}
private void OnNewClient(IClientAPI client)
{
client.OnRetrieveInstantMessages += RetrieveInstantMessages;
client.OnLogout += OnClientLoggedOut;
}
public void OnClientLoggedOut(IClientAPI client)
{
m_repliesSent.Remove(client);
}
private void RetrieveInstantMessages(IClientAPI client)
{
if (m_RestURL == String.Empty)
{
return;
}
else
{
m_log.DebugFormat("[OFFLINE MESSAGING]: Retrieving stored messages for {0}", client.AgentId);
List<GridInstantMessage> msglist
= SynchronousRestObjectRequester.MakeRequest<UUID, List<GridInstantMessage>>(
"POST", m_RestURL + "/RetrieveMessages/", client.AgentId);
if (msglist != null)
{
foreach (GridInstantMessage im in msglist)
{
if (im.dialog == (byte)InstantMessageDialog.InventoryOffered)
// send it directly or else the item will be given twice
client.SendInstantMessage(im);
else
{
// Send through scene event manager so all modules get a chance
// to look at this message before it gets delivered.
//
// Needed for proper state management for stored group
// invitations
//
im.offline = 1;
Scene s = FindScene(client.AgentId);
if (s != null)
s.EventManager.TriggerIncomingInstantMessage(im);
}
}
}
}
}
private void UndeliveredMessage(GridInstantMessage im)
{
if (im.dialog != (byte)InstantMessageDialog.MessageFromObject &&
im.dialog != (byte)InstantMessageDialog.MessageFromAgent &&
im.dialog != (byte)InstantMessageDialog.GroupNotice &&
im.dialog != (byte)InstantMessageDialog.GroupInvitation &&
im.dialog != (byte)InstantMessageDialog.InventoryOffered &&
im.dialog != (byte)InstantMessageDialog.TaskInventoryOffered)
{
return;
}
if (!m_ForwardOfflineGroupMessages)
{
if (im.dialog == (byte)InstantMessageDialog.GroupNotice ||
im.dialog == (byte)InstantMessageDialog.GroupInvitation)
return;
}
Scene scene = FindScene(new UUID(im.fromAgentID));
if (scene == null)
scene = m_SceneList[0];
// Avination new code
// SendReply reply = SynchronousRestObjectRequester.MakeRequest<GridInstantMessage, SendReply>(
// "POST", m_RestURL+"/SaveMessage/?scope=" +
// scene.RegionInfo.ScopeID.ToString(), im);
// current opensim and osgrid compatible
bool success = SynchronousRestObjectRequester.MakeRequest<GridInstantMessage, bool>(
"POST", m_RestURL+"/SaveMessage/", im, 10000);
// current opensim and osgrid compatible end
if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
{
IClientAPI client = FindClient(new UUID(im.fromAgentID));
if (client == null)
return;
/* Avination new code
if (reply.Message == String.Empty)
reply.Message = "User is not logged in. " + (reply.Success ? "Message saved." : "Message not saved");
bool sendReply = true;
switch (reply.Disposition)
{
case 0: // Normal
break;
case 1: // Only once per user
if (m_repliesSent.ContainsKey(client) && m_repliesSent[client].Contains(new UUID(im.toAgentID)))
{
sendReply = false;
}
else
{
if (!m_repliesSent.ContainsKey(client))
m_repliesSent[client] = new List<UUID>();
m_repliesSent[client].Add(new UUID(im.toAgentID));
}
break;
}
if (sendReply)
{
client.SendInstantMessage(new GridInstantMessage(
null, new UUID(im.toAgentID),
"System", new UUID(im.fromAgentID),
(byte)InstantMessageDialog.MessageFromAgent,
reply.Message,
false, new Vector3()));
}
*/
// current opensim and osgrid compatible
client.SendInstantMessage(new GridInstantMessage(
null, new UUID(im.toAgentID),
"System", new UUID(im.fromAgentID),
(byte)InstantMessageDialog.MessageFromAgent,
"User is not logged in. "+
(success ? "Message saved." : "Message not saved"),
false, new Vector3()));
// current opensim and osgrid compatible end
}
}
}
}
| |
/*
* 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 log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Server.Base;
using OpenSim.Framework.Servers.HttpServer;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.Avatar.Friends
{
public class FriendsModule : ISharedRegionModule, IFriendsModule
{
protected class UserFriendData
{
public UUID PrincipalID;
public FriendInfo[] Friends;
public int Refcount;
public UUID RegionID;
public bool IsFriend(string friend)
{
foreach (FriendInfo fi in Friends)
{
if (fi.Friend == friend)
return true;
}
return false;
}
}
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected List<Scene> m_Scenes = new List<Scene>();
protected IPresenceService m_PresenceService = null;
protected IFriendsService m_FriendsService = null;
protected FriendsSimConnector m_FriendsSimConnector;
protected Dictionary<UUID, UserFriendData> m_Friends =
new Dictionary<UUID, UserFriendData>();
protected List<UUID> m_NeedsListOfFriends = new List<UUID>();
protected IPresenceService PresenceService
{
get
{
if (m_PresenceService == null)
{
if (m_Scenes.Count > 0)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
}
return m_PresenceService;
}
}
protected IFriendsService FriendsService
{
get
{
if (m_FriendsService == null)
{
if (m_Scenes.Count > 0)
m_FriendsService = m_Scenes[0].RequestModuleInterface<IFriendsService>();
}
return m_FriendsService;
}
}
protected IGridService GridService
{
get { return m_Scenes[0].GridService; }
}
public IUserAccountService UserAccountService
{
get { return m_Scenes[0].UserAccountService; }
}
public IScene Scene
{
get
{
if (m_Scenes.Count > 0)
return m_Scenes[0];
else
return null;
}
}
public void Initialise(IConfigSource config)
{
IConfig friendsConfig = config.Configs["Friends"];
if (friendsConfig != null)
{
int mPort = friendsConfig.GetInt("Port", 0);
string connector = friendsConfig.GetString("Connector", String.Empty);
Object[] args = new Object[] { config };
m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(connector, args);
m_FriendsSimConnector = new FriendsSimConnector();
// Instantiate the request handler
IHttpServer server = MainServer.GetHttpServer((uint)mPort);
server.AddStreamHandler(new FriendsRequestHandler(this));
}
if (m_FriendsService == null)
{
m_log.Error("[FRIENDS]: No Connector defined in section Friends, or failed to load, cannot continue");
throw new Exception("Connector load error");
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IFriendsModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClientClosed += OnClientClosed;
scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
scene.EventManager.OnClientLogin += OnClientLogin;
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
m_Scenes.Remove(scene);
}
public string Name
{
get { return "FriendsModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public uint GetFriendPerms(UUID principalID, UUID friendID)
{
if (!m_Friends.ContainsKey(principalID))
return 0;
UserFriendData data = m_Friends[principalID];
foreach (FriendInfo fi in data.Friends)
{
if (fi.Friend == friendID.ToString())
return (uint)fi.TheirFlags;
}
return 0;
}
private void OnNewClient(IClientAPI client)
{
client.OnInstantMessage += OnInstantMessage;
client.OnApproveFriendRequest += OnApproveFriendRequest;
client.OnDenyFriendRequest += OnDenyFriendRequest;
client.OnTerminateFriendship += OnTerminateFriendship;
client.OnGrantUserRights += OnGrantUserRights;
lock (m_Friends)
{
if (m_Friends.ContainsKey(client.AgentId))
{
m_Friends[client.AgentId].Refcount++;
return;
}
UserFriendData newFriends = new UserFriendData();
newFriends.PrincipalID = client.AgentId;
newFriends.Friends = m_FriendsService.GetFriends(client.AgentId);
newFriends.Refcount = 1;
newFriends.RegionID = UUID.Zero;
m_Friends.Add(client.AgentId, newFriends);
}
}
private void OnClientClosed(UUID agentID, Scene scene)
{
ScenePresence sp = scene.GetScenePresence(agentID);
if (sp != null && !sp.IsChildAgent)
// do this for root agents closing out
StatusChange(agentID, false);
lock (m_Friends)
if (m_Friends.ContainsKey(agentID))
{
if (m_Friends[agentID].Refcount == 1)
m_Friends.Remove(agentID);
else
m_Friends[agentID].Refcount--;
}
}
private void OnMakeRootAgent(ScenePresence sp)
{
UUID agentID = sp.ControllingClient.AgentId;
if (m_Friends.ContainsKey(agentID))
{
// This is probably an overkill, but just
// to make sure we have the latest and greatest
// friends list -- always pull OnMakeRoot
m_Friends[agentID].Friends =
m_FriendsService.GetFriends(agentID);
m_Friends[agentID].RegionID =
sp.ControllingClient.Scene.RegionInfo.RegionID;
}
}
private void OnMakeChildAgent(ScenePresence sp)
{
UUID agentID = sp.ControllingClient.AgentId;
if (m_Friends.ContainsKey(agentID))
{
if (m_Friends[agentID].RegionID == sp.ControllingClient.Scene.RegionInfo.RegionID)
m_Friends[agentID].RegionID = UUID.Zero;
}
}
private void OnClientLogin(IClientAPI client)
{
UUID agentID = client.AgentId;
// Inform the friends that this user is online
StatusChange(agentID, true);
// Register that we need to send the list of online friends to this user
lock (m_NeedsListOfFriends)
if (!m_NeedsListOfFriends.Contains(agentID))
{
m_NeedsListOfFriends.Add(agentID);
}
}
public void SendFriendsOnlineIfNeeded(IClientAPI client)
{
UUID agentID = client.AgentId;
if (m_NeedsListOfFriends.Contains(agentID))
{
if (!m_Friends.ContainsKey(agentID))
{
m_log.DebugFormat("[FRIENDS MODULE]: agent {0} not found in local cache", agentID);
return;
}
//
// Send the friends online
//
List<UUID> online = GetOnlineFriends(agentID);
if (online.Count > 0)
{
m_log.DebugFormat("[FRIENDS MODULE]: User {0} in region {1} has {2} friends online", client.AgentId, client.Scene.RegionInfo.RegionName, online.Count);
client.SendAgentOnline(online.ToArray());
}
//
// Send outstanding friendship offers
//
if (m_Friends.ContainsKey(agentID))
{
List<string> outstanding = new List<string>();
foreach (FriendInfo fi in m_Friends[agentID].Friends)
if (fi.TheirFlags == -1)
outstanding.Add(fi.Friend);
GridInstantMessage im = new GridInstantMessage(client.Scene, UUID.Zero, "", agentID, (byte)InstantMessageDialog.FriendshipOffered, "Will you be my friend?", true, Vector3.Zero);
foreach (string fid in outstanding)
{
try
{
im.fromAgentID = new Guid(fid);
}
catch
{
continue;
}
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(client.Scene.RegionInfo.ScopeID, new UUID(im.fromAgentID));
im.fromAgentName = account.FirstName + " " + account.LastName;
PresenceInfo presence = null;
PresenceInfo[] presences = PresenceService.GetAgents(new string[] { fid });
if (presences != null && presences.Length > 0)
presence = presences[0];
if (presence != null)
im.offline = 0;
im.imSessionID = im.fromAgentID;
// Finally
LocalFriendshipOffered(agentID, im);
}
}
lock (m_NeedsListOfFriends)
m_NeedsListOfFriends.Remove(agentID);
}
}
List<UUID> GetOnlineFriends(UUID userID)
{
List<string> friendList = new List<string>();
List<UUID> online = new List<UUID>();
foreach (FriendInfo fi in m_Friends[userID].Friends)
{
if (((fi.TheirFlags & 1) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi.Friend);
}
if (friendList.Count == 0)
// no friends whatsoever
return online;
PresenceInfo[] presence = PresenceService.GetAgents(friendList.ToArray());
foreach (PresenceInfo pi in presence)
online.Add(new UUID(pi.UserID));
//m_log.DebugFormat("[XXX] {0} friend online {1}", userID, pi.UserID);
return online;
}
//
// Find the client for a ID
//
public IClientAPI LocateClientObject(UUID agentID)
{
Scene scene = GetClientScene(agentID);
if (scene == null)
return null;
ScenePresence presence = scene.GetScenePresence(agentID);
if (presence == null)
return null;
return presence.ControllingClient;
}
//
// Find the scene for an agent
//
private Scene GetClientScene(UUID agentId)
{
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
{
ScenePresence presence = scene.GetScenePresence(agentId);
if (presence != null)
{
if (!presence.IsChildAgent)
return scene;
}
}
}
return null;
}
/// <summary>
/// Caller beware! Call this only for root agents.
/// </summary>
/// <param name="agentID"></param>
/// <param name="online"></param>
private void StatusChange(UUID agentID, bool online)
{
//m_log.DebugFormat("[FRIENDS]: StatusChange {0}", online);
if (m_Friends.ContainsKey(agentID))
{
//m_log.DebugFormat("[FRIENDS]: # of friends: {0}", m_Friends[agentID].Friends.Length);
List<FriendInfo> friendList = new List<FriendInfo>();
foreach (FriendInfo fi in m_Friends[agentID].Friends)
{
if (((fi.MyFlags & 1) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi);
}
Util.FireAndForget(delegate
{
foreach (FriendInfo fi in friendList)
{
//m_log.DebugFormat("[FRIENDS]: Notifying {0}", fi.PrincipalID);
// Notify about this user status
StatusNotify(fi, agentID, online);
}
});
}
else
m_log.WarnFormat("[FRIENDS]: {0} not found in cache", agentID);
}
private void StatusNotify(FriendInfo friend, UUID userID, bool online)
{
UUID friendID = UUID.Zero;
if (UUID.TryParse(friend.Friend, out friendID))
{
// Try local
if (LocalStatusNotification(userID, friendID, online))
return;
// The friend is not here [as root]. Let's forward.
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = null;
foreach (PresenceInfo pinfo in friendSessions)
if (pinfo.RegionID != UUID.Zero) // let's guard against sessions-gone-bad
{
friendSession = pinfo;
break;
}
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
//m_log.DebugFormat("[FRIENDS]: Remote Notify to region {0}", region.RegionName);
m_FriendsSimConnector.StatusNotify(region, userID, friendID, online);
}
}
// Friend is not online. Ignore.
}
else
m_log.WarnFormat("[FRIENDS]: Error parsing friend ID {0}", friend.Friend);
}
private void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
if (im.dialog == (byte)OpenMetaverse.InstantMessageDialog.FriendshipOffered)
{
// we got a friendship offer
UUID principalID = new UUID(im.fromAgentID);
UUID friendID = new UUID(im.toAgentID);
m_log.DebugFormat("[FRIENDS]: {0} ({1}) offered friendship to {2}", principalID, im.fromAgentName, friendID);
// This user wants to be friends with the other user.
// Let's add the relation backwards, in case the other is not online
FriendsService.StoreFriend(friendID, principalID.ToString(), 0);
// Now let's ask the other user to be friends with this user
ForwardFriendshipOffer(principalID, friendID, im);
}
}
private void ForwardFriendshipOffer(UUID agentID, UUID friendID, GridInstantMessage im)
{
// !!!!!!!! This is a hack so that we don't have to keep state (transactionID/imSessionID)
// We stick this agent's ID as imSession, so that it's directly available on the receiving end
im.imSessionID = im.fromAgentID;
// Try the local sim
UserAccount account = UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, agentID);
im.fromAgentName = (account == null) ? "Unknown" : account.FirstName + " " + account.LastName;
if (LocalFriendshipOffered(friendID, im))
return;
// The prospective friend is not here [as root]. Let's forward.
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipOffered(region, agentID, friendID, im.message);
}
}
// If the prospective friend is not online, he'll get the message upon login.
}
private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIENDS]: {0} accepted friendship from {1}", agentID, friendID);
FriendsService.StoreFriend(agentID, friendID.ToString(), 1);
FriendsService.StoreFriend(friendID, agentID.ToString(), 1);
// update the local cache
m_Friends[agentID].Friends = FriendsService.GetFriends(agentID);
//
// Notify the friend
//
// Try Local
if (LocalFriendshipApproved(agentID, client.Name, friendID))
{
client.SendAgentOnline(new UUID[] { friendID });
return;
}
// The friend is not here
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipApproved(region, agentID, client.Name, friendID);
client.SendAgentOnline(new UUID[] { friendID });
}
}
}
private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders)
{
m_log.DebugFormat("[FRIENDS]: {0} denied friendship to {1}", agentID, friendID);
FriendsService.Delete(agentID, friendID.ToString());
FriendsService.Delete(friendID, agentID.ToString());
//
// Notify the friend
//
// Try local
if (LocalFriendshipDenied(agentID, client.Name, friendID))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
if (region != null)
m_FriendsSimConnector.FriendshipDenied(region, agentID, client.Name, friendID);
else
m_log.WarnFormat("[FRIENDS]: Could not find region {0} in locating {1}", friendSession.RegionID, friendID);
}
}
}
private void OnTerminateFriendship(IClientAPI client, UUID agentID, UUID exfriendID)
{
FriendsService.Delete(agentID, exfriendID.ToString());
FriendsService.Delete(exfriendID, agentID.ToString());
// Update local cache
m_Friends[agentID].Friends = FriendsService.GetFriends(agentID);
client.SendTerminateFriend(exfriendID);
//
// Notify the friend
//
// Try local
if (LocalFriendshipTerminated(exfriendID))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { exfriendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
m_FriendsSimConnector.FriendshipTerminated(region, agentID, exfriendID);
}
}
}
private void OnGrantUserRights(IClientAPI remoteClient, UUID requester, UUID target, int rights)
{
if (!m_Friends.ContainsKey(remoteClient.AgentId))
return;
m_log.DebugFormat("[FRIENDS MODULE]: User {0} changing rights to {1} for friend {2}", requester, rights, target);
// Let's find the friend in this user's friend list
UserFriendData fd = m_Friends[remoteClient.AgentId];
FriendInfo friend = null;
foreach (FriendInfo fi in fd.Friends)
if (fi.Friend == target.ToString())
friend = fi;
if (friend != null) // Found it
{
// Store it on the DB
FriendsService.StoreFriend(requester, target.ToString(), rights);
// Store it in the local cache
int myFlags = friend.MyFlags;
friend.MyFlags = rights;
// Always send this back to the original client
remoteClient.SendChangeUserRights(requester, target, rights);
//
// Notify the friend
//
// Try local
if (LocalGrantRights(requester, target, myFlags, rights))
return;
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { target.ToString() });
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = friendSessions[0];
if (friendSession != null)
{
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
// TODO: You might want to send the delta to save the lookup
// on the other end!!
m_FriendsSimConnector.GrantRights(region, requester, target, myFlags, rights);
}
}
}
}
#region Local
public bool LocalFriendshipOffered(UUID toID, GridInstantMessage im)
{
IClientAPI friendClient = LocateClientObject(toID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipApproved(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
(byte)OpenMetaverse.InstantMessageDialog.FriendshipAccepted, userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
// update the local cache
m_Friends[friendID].Friends = FriendsService.GetFriends(friendID);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipDenied(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(Scene, userID, userName, friendID,
(byte)OpenMetaverse.InstantMessageDialog.FriendshipDeclined, userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipTerminated(UUID exfriendID)
{
IClientAPI friendClient = LocateClientObject(exfriendID);
if (friendClient != null)
{
// the friend in this sim as root agent
friendClient.SendTerminateFriend(exfriendID);
// update local cache
m_Friends[exfriendID].Friends = FriendsService.GetFriends(exfriendID);
// we're done
return true;
}
return false;
}
public bool LocalGrantRights(UUID userID, UUID friendID, int userFlags, int rights)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
bool onlineBitChanged = ((rights ^ userFlags) & (int)FriendRights.CanSeeOnline) != 0;
if (onlineBitChanged)
{
if ((rights & (int)FriendRights.CanSeeOnline) == 1)
friendClient.SendAgentOnline(new UUID[] { new UUID(userID) });
else
friendClient.SendAgentOffline(new UUID[] { new UUID(userID) });
}
else
{
bool canEditObjectsChanged = ((rights ^ userFlags) & (int)FriendRights.CanModifyObjects) != 0;
if (canEditObjectsChanged)
friendClient.SendChangeUserRights(userID, friendID, rights);
}
// update local cache
//m_Friends[friendID].Friends = m_FriendsService.GetFriends(friendID);
foreach (FriendInfo finfo in m_Friends[friendID].Friends)
if (finfo.Friend == userID.ToString())
finfo.TheirFlags = rights;
return true;
}
return false;
}
public bool LocalStatusNotification(UUID userID, UUID friendID, bool online)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
//m_log.DebugFormat("[FRIENDS]: Local Status Notify {0} that user {1} is {2}", friendID, userID, online);
// the friend in this sim as root agent
if (online)
friendClient.SendAgentOnline(new UUID[] { userID });
else
friendClient.SendAgentOffline(new UUID[] { userID });
// we're done
return true;
}
return false;
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Globalization;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Textures;
using osu.Game.Audio;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSkinnableDrawable : OsuTestScene
{
[Test]
public void TestConfineScaleDown()
{
FillFlowContainer<ExposedSkinnableDrawable> fill = null;
AddStep("setup layout larger source", () =>
{
Child = new SkinProvidingContainer(new SizedSource(50))
{
RelativeSizeAxes = Axes.Both,
Child = fill = new FillFlowContainer<ExposedSkinnableDrawable>
{
Size = new Vector2(30),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Spacing = new Vector2(10),
Children = new[]
{
new ExposedSkinnableDrawable("default", _ => new DefaultBox(), _ => true),
new ExposedSkinnableDrawable("available", _ => new DefaultBox(), _ => true),
new ExposedSkinnableDrawable("available", _ => new DefaultBox(), _ => true, ConfineMode.ScaleToFit),
new ExposedSkinnableDrawable("available", _ => new DefaultBox(), _ => true, ConfineMode.NoScaling)
}
},
};
});
AddAssert("check sizes", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 30, 30, 30, 50 }));
AddStep("adjust scale", () => fill.Scale = new Vector2(2));
AddAssert("check sizes unchanged by scale", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 30, 30, 30, 50 }));
}
[Test]
public void TestConfineScaleUp()
{
FillFlowContainer<ExposedSkinnableDrawable> fill = null;
AddStep("setup layout larger source", () =>
{
Child = new SkinProvidingContainer(new SizedSource(30))
{
RelativeSizeAxes = Axes.Both,
Child = fill = new FillFlowContainer<ExposedSkinnableDrawable>
{
Size = new Vector2(50),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Spacing = new Vector2(10),
Children = new[]
{
new ExposedSkinnableDrawable("default", _ => new DefaultBox(), _ => true),
new ExposedSkinnableDrawable("available", _ => new DefaultBox(), _ => true),
new ExposedSkinnableDrawable("available", _ => new DefaultBox(), _ => true, ConfineMode.ScaleToFit),
new ExposedSkinnableDrawable("available", _ => new DefaultBox(), _ => true, ConfineMode.NoScaling)
}
},
};
});
AddAssert("check sizes", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 50, 30, 50, 30 }));
AddStep("adjust scale", () => fill.Scale = new Vector2(2));
AddAssert("check sizes unchanged by scale", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 50, 30, 50, 30 }));
}
[Test]
public void TestInitialLoad()
{
var secondarySource = new SecondarySource();
SkinConsumer consumer = null;
AddStep("setup layout", () =>
{
Child = new SkinSourceContainer
{
RelativeSizeAxes = Axes.Both,
Child = new SkinProvidingContainer(secondarySource)
{
RelativeSizeAxes = Axes.Both,
Child = consumer = new SkinConsumer("test", name => new NamedBox("Default Implementation"), source => true)
}
};
});
AddAssert("consumer using override source", () => consumer.Drawable is SecondarySourceBox);
AddAssert("skinchanged only called once", () => consumer.SkinChangedCount == 1);
}
[Test]
public void TestOverride()
{
var secondarySource = new SecondarySource();
SkinConsumer consumer = null;
Container target = null;
AddStep("setup layout", () =>
{
Child = new SkinSourceContainer
{
RelativeSizeAxes = Axes.Both,
Child = target = new SkinProvidingContainer(secondarySource)
{
RelativeSizeAxes = Axes.Both,
}
};
});
AddStep("add permissive", () => target.Add(consumer = new SkinConsumer("test", name => new NamedBox("Default Implementation"), source => true)));
AddAssert("consumer using override source", () => consumer.Drawable is SecondarySourceBox);
AddAssert("skinchanged only called once", () => consumer.SkinChangedCount == 1);
}
[Test]
public void TestSwitchOff()
{
SkinConsumer consumer = null;
SwitchableSkinProvidingContainer target = null;
AddStep("setup layout", () =>
{
Child = new SkinSourceContainer
{
RelativeSizeAxes = Axes.Both,
Child = target = new SwitchableSkinProvidingContainer(new SecondarySource())
{
RelativeSizeAxes = Axes.Both,
}
};
});
AddStep("add permissive", () => target.Add(consumer = new SkinConsumer("test", name => new NamedBox("Default Implementation"), source => true)));
AddAssert("consumer using override source", () => consumer.Drawable is SecondarySourceBox);
AddStep("disable", () => target.Disable());
AddAssert("consumer using base source", () => consumer.Drawable is BaseSourceBox);
}
private class SwitchableSkinProvidingContainer : SkinProvidingContainer
{
private bool allow = true;
protected override bool AllowDrawableLookup(ISkinComponent component) => allow;
public void Disable()
{
allow = false;
TriggerSourceChanged();
}
public SwitchableSkinProvidingContainer(ISkin skin)
: base(skin)
{
}
}
private class ExposedSkinnableDrawable : SkinnableDrawable
{
public new Drawable Drawable => base.Drawable;
public ExposedSkinnableDrawable(string name, Func<ISkinComponent, Drawable> defaultImplementation, Func<ISkinSource, bool> allowFallback = null,
ConfineMode confineMode = ConfineMode.ScaleDownToFit)
: base(new TestSkinComponent(name), defaultImplementation, allowFallback, confineMode)
{
}
}
private class DefaultBox : DrawWidthBox
{
public DefaultBox()
{
RelativeSizeAxes = Axes.Both;
}
}
private class DrawWidthBox : Container
{
private readonly OsuSpriteText text;
public DrawWidthBox()
{
Children = new Drawable[]
{
new Box
{
Colour = Color4.Gray,
RelativeSizeAxes = Axes.Both,
},
text = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
};
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
text.Text = DrawWidth.ToString(CultureInfo.InvariantCulture);
}
}
private class NamedBox : Container
{
public NamedBox(string name)
{
Children = new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Font = OsuFont.Default.With(size: 40),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Text = name
}
};
}
}
private class SkinConsumer : SkinnableDrawable
{
public new Drawable Drawable => base.Drawable;
public int SkinChangedCount { get; private set; }
public SkinConsumer(string name, Func<ISkinComponent, Drawable> defaultImplementation, Func<ISkinSource, bool> allowFallback = null)
: base(new TestSkinComponent(name), defaultImplementation, allowFallback)
{
}
protected override void SkinChanged(ISkinSource skin, bool allowFallback)
{
base.SkinChanged(skin, allowFallback);
SkinChangedCount++;
}
}
private class BaseSourceBox : NamedBox
{
public BaseSourceBox()
: base("Base Source")
{
}
}
private class SecondarySourceBox : NamedBox
{
public SecondarySourceBox()
: base("Secondary Source")
{
}
}
private class SizedSource : ISkin
{
private readonly float size;
public SizedSource(float size)
{
this.size = size;
}
public Drawable GetDrawableComponent(ISkinComponent componentName) =>
componentName.LookupName == "available"
? new DrawWidthBox
{
Colour = Color4.Yellow,
Size = new Vector2(size)
}
: null;
public Texture GetTexture(string componentName) => throw new NotImplementedException();
public SampleChannel GetSample(ISampleInfo sampleInfo) => throw new NotImplementedException();
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotImplementedException();
}
private class SecondarySource : ISkin
{
public Drawable GetDrawableComponent(ISkinComponent componentName) => new SecondarySourceBox();
public Texture GetTexture(string componentName) => throw new NotImplementedException();
public SampleChannel GetSample(ISampleInfo sampleInfo) => throw new NotImplementedException();
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotImplementedException();
}
[Cached(typeof(ISkinSource))]
private class SkinSourceContainer : Container, ISkinSource
{
public Drawable GetDrawableComponent(ISkinComponent componentName) => new BaseSourceBox();
public Texture GetTexture(string componentName) => throw new NotImplementedException();
public SampleChannel GetSample(ISampleInfo sampleInfo) => throw new NotImplementedException();
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotImplementedException();
public event Action SourceChanged
{
add { }
remove { }
}
}
private class TestSkinComponent : ISkinComponent
{
public TestSkinComponent(string name)
{
LookupName = name;
}
public string ComponentGroup => string.Empty;
public string LookupName { get; }
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace UMAAssetBundleManager
{
/// <summary>
/// An AssetBunldeIndex containing a list of assetbundles each with a list of assets inside that asset bundle. The user can customize the fields of data that are stored for each asset.
/// The entire class is marked as partial so that extra methods for searching the index can be added as necessary.
/// </summary>
public partial class AssetBundleIndex : ScriptableObject
{
/// <summary>
/// The actual data that gets added to the index for any given asset. Made partial so the user can add extra fields to this as required;
/// </summary>
[System.Serializable]
public partial class AssetBundleIndexItem
{
public string filename;
public string assetName;
public int assetHash;
public string assetType;
public AssetBundleIndexItem()
{
}
/// <summary>
/// Adds data about the given asset object to this given index item.
/// Calls AddDataPreProcess before assigning any data and AddDataPostProcess afterwards, both of which are partial classes the user can use if necessary.
/// </summary>
/// <param name="_filename"></param>
/// <param name="obj"></param>
public virtual void AddData(string _filename, UnityEngine.Object obj)
{
AddDataPreProcess(_filename, obj);
assetType = obj.GetType().ToString();
filename = _filename;
if (assetType == "UMA.OverlayDataAsset" || assetType == "UMA.SlotDataAsset" || assetType == "UMA.RaceData" || assetType == "UMATextRecipe")
{
if (assetType == "UMA.RaceData")
{
assetName = (obj as UMA.RaceData).raceName;
assetHash = UMA.UMAUtils.StringToHash((obj as UMA.RaceData).raceName);
}
else if (assetType == "UMA.OverlayDataAsset")
{
assetName = (obj as UMA.OverlayDataAsset).overlayName;
assetHash = UMA.UMAUtils.StringToHash((obj as UMA.OverlayDataAsset).overlayName);
}
else if (assetType == "UMA.SlotDataAsset")
{
assetName = (obj as UMA.SlotDataAsset).slotName;
assetHash = (obj as UMA.SlotDataAsset).nameHash;
}
else if (assetType == "UMATextRecipe")
{
assetName = _filename;
assetHash = UMA.UMAUtils.StringToHash(filename);
}
}
else
{
assetName = _filename;
assetHash = UMA.UMAUtils.StringToHash(filename);
}
AddDataPostProcess(_filename, obj);
}
/// <summary>
/// Impliment this method to run any extra code before data gets added to the index item in AddData
/// </summary>
/// <param name="filename"></param>
/// <param name="obj"></param>
partial void AddDataPreProcess(string filename, UnityEngine.Object obj);
/// <summary>
/// Impliment this method to run any extra code after data has been added to the index item in AddData
/// </summary>
/// <param name="filename"></param>
/// <param name="obj"></param>
partial void AddDataPostProcess(string filename, UnityEngine.Object obj);
}
/// <summary>
/// A list of the available assetbundles each conatining a list of all the assets in that bundle. Marked as partial so this can be extended if necessary.
/// </summary>
[System.Serializable]
public partial class AssetBundleIndexList
{
public string assetBundleName;
public List<AssetBundleIndexItem> assetBundleAssets = new List<AssetBundleIndexItem>();
public string[] allDependencies;
public string[] directDependencies;
public string assetBundleHash;
public AssetBundleIndexList(string _assetBundleName)
{
assetBundleName = _assetBundleName;
}
/// <summary>
/// Adds an AssetBundleIndexItem to the list of assetBundleAssets with the given filename.
/// </summary>
/// <param name="filename"></param>
/// <param name="obj"></param>
public void AddItem(string filename, UnityEngine.Object obj)
{
AssetBundleIndexItem thisItem = new AssetBundleIndexItem();
thisItem.AddData(filename, obj);
assetBundleAssets.Add(thisItem);
}
}
[SerializeField]
public string ownBundleHash;
[SerializeField]
public List<AssetBundleIndexList> bundlesIndex = new List<AssetBundleIndexList>();
[SerializeField]
public string[] bundlesWithVariant;
public AssetBundleIndex()
{
}
#region AssetBundleManifest clone methods
//These methods are replicas of the AssetBundleManifest methods so that we can just use this Index in place of the manifest
public string[] GetAllAssetBundles()
{
return GetAllAssetBundleNames();
}
public Hash128 GetAssetBundleHash(string assetBundleName)
{
Hash128 hash = new Hash128();
for (int i = 0; i < bundlesIndex.Count; i++)
{
if (bundlesIndex[i].assetBundleName == assetBundleName)
{
hash = Hash128.Parse(bundlesIndex[i].assetBundleHash);
}
}
return hash;
}
//TODO work out what this actually is and how its made so we can recreate it server side
public string[] GetAllAssetBundlesWithVariant()
{
return bundlesWithVariant;
}
public string[] GetAllDependencies(string assetBundleName)
{
string[] deps = new string[0];
for (int i = 0; i < bundlesIndex.Count; i++)
{
if (bundlesIndex[i].assetBundleName == assetBundleName)
{
deps = bundlesIndex[i].allDependencies;
}
}
return deps;
}
public string[] GetDirectDependencies(string assetBundleName)
{
string[] deps = new string[0];
for (int i = 0; i < bundlesIndex.Count; i++)
{
if (bundlesIndex[i].assetBundleName == assetBundleName)
{
deps = bundlesIndex[i].directDependencies;
}
}
return deps;
}
#endregion
/// <summary>
/// Replicates AssetDatabase.GetAllAssetBundleNames() method. Gets the names of all available asset bundles.
/// </summary>
/// <returns>String array of all available bundles.</returns>
public string[] GetAllAssetBundleNames()
{
List<string> assetBundleNames = new List<string>();
foreach (AssetBundleIndexList iAssetList in bundlesIndex)
{
assetBundleNames.Add(iAssetList.assetBundleName);
}
return assetBundleNames.ToArray();
}
/// <summary>
/// Replicates AssetBundle.Contains but adds an optional type filter
/// </summary>
/// <param name="assetBundleName"></param>
/// <param name="assetName"></param>
/// <param name="type"></param>
/// <returns></returns>
public bool AssetBundleContains(string assetBundleName, string assetName, string type = "")
{
bool assetFound = false;
if (GetAssetBundleIndexItem(assetBundleName, assetName, type) != null)
{
assetFound = true;
}
return assetFound;
}
/// <summary>
/// Replicates AssetBundle.Contains but uses assetNameHash and adds an optional type filter
/// </summary>
/// <param name="assetBundleName"></param>
/// <param name="assetName"></param>
/// <param name="type"></param>
/// <returns></returns>
public bool AssetBundleContains(string assetBundleName, int? assetHash, string type = "")
{
bool assetFound = false;
if (GetAssetBundleIndexItem(assetBundleName, assetHash, type) != null)
{
assetFound = true;
}
return assetFound;
}
/// <summary>
/// Searches the available AssetBundles for the given assetName optionally filtered by type
/// </summary>
/// <param name="assetName"></param>
/// <param name="type"></param>
/// <returns></returns>
public string[] FindContainingAssetBundle(string assetNameOrFilename, string type = "")
{
List<string> assetFoundIn = new List<string>();
for (int i = 0; i < bundlesIndex.Count; i++)
{
for (int ii = 0; ii < bundlesIndex[i].assetBundleAssets.Count; ii++)
{
if (assetNameOrFilename == bundlesIndex[i].assetBundleAssets[ii].assetName)
{
if (type == "" || (type != "" && (type == bundlesIndex[i].assetBundleAssets[ii].assetType || type == GetTypeWithoutAssembly(bundlesIndex[i].assetBundleAssets[ii].assetType))))
{
assetFoundIn.Add(bundlesIndex[i].assetBundleName);
}
}
}
}
//if we didn't find it check the filename?
if (assetFoundIn.Count == 0)
{
for (int i = 0; i < bundlesIndex.Count; i++)
{
for (int ii = 0; ii < bundlesIndex[i].assetBundleAssets.Count; ii++)
{
if (assetNameOrFilename == bundlesIndex[i].assetBundleAssets[ii].filename)
{
if (type == "" || (type != "" && (type == bundlesIndex[i].assetBundleAssets[ii].assetType || type == GetTypeWithoutAssembly(bundlesIndex[i].assetBundleAssets[ii].assetType))))
{
assetFoundIn.Add(bundlesIndex[i].assetBundleName);
}
}
}
}
}
return assetFoundIn.ToArray();
}
/// <summary>
/// Searches the available AssetBundles for the given assetNameHash optionally filtered by type (type may be un-necessary it depends how unique the hashes are)
/// </summary>
/// <param name="assetNameHash"></param>
/// <param name="type"></param>
/// <returns></returns>
public string[] FindContainingAssetBundle(int? assetNameHash, string type = "")
{
List<string> assetFoundIn = new List<string>();
for (int i = 0; i < bundlesIndex.Count; i++)
{
for (int ii = 0; ii < bundlesIndex[i].assetBundleAssets.Count; ii++)
{
if (assetNameHash == bundlesIndex[i].assetBundleAssets[ii].assetHash)
{
if (type == "" || (type != "" && (type == bundlesIndex[i].assetBundleAssets[ii].assetType || type == GetTypeWithoutAssembly(bundlesIndex[i].assetBundleAssets[ii].assetType))))
{
assetFoundIn.Add(bundlesIndex[i].assetBundleName);
}
}
}
}
return assetFoundIn.ToArray();
}
/// <summary>
/// Gets all the assets of a particular type that are contained in the given asset bundle
/// </summary>
/// <param name="assetBundleName"></param>
/// <param name="type"></param>
/// <returns></returns>
public string[] GetAllAssetsOfTypeInBundle(string assetBundleName, string type)
{
List<string> foundAssets = new List<string>();
foreach (AssetBundleIndexList iAssetList in bundlesIndex)
{
if (iAssetList.assetBundleName == assetBundleName)
{
foreach (AssetBundleIndexItem iAsset in iAssetList.assetBundleAssets)
{
if (type == "" || (type != "" && (type == iAsset.assetType || type == GetTypeWithoutAssembly(iAsset.assetType))))
{
foundAssets.Add(iAsset.assetName);
}
}
}
}
return foundAssets.ToArray();
}
public AssetBundleIndexItem GetAssetBundleIndexItem(string assetBundleName, string assetNameOrFilename, string type = "")
{
AssetBundleIndexItem indexAsset = null;
foreach (AssetBundleIndexList iAssetList in bundlesIndex)
{
if (indexAsset != null)
break;
if (iAssetList.assetBundleName == assetBundleName)
{
foreach (AssetBundleIndexItem iAsset in iAssetList.assetBundleAssets)
{
if (assetNameOrFilename == iAsset.assetName)
{
if (type == "" || (type != "" && (type == iAsset.assetType || type == GetTypeWithoutAssembly(iAsset.assetType))))
{
indexAsset = iAsset;
}
}
else if (assetNameOrFilename == iAsset.filename)
{
if (type == "" || (type != "" && (type == iAsset.assetType || type == GetTypeWithoutAssembly(iAsset.assetType))))
{
indexAsset = iAsset;
}
}
if (indexAsset != null)
break;
}
}
}
return indexAsset;
}
public AssetBundleIndexItem GetAssetBundleIndexItem(string assetBundleName, int? assetNameHash, string type = "")
{
AssetBundleIndexItem indexAsset = null;
foreach (AssetBundleIndexList iAssetList in bundlesIndex)
{
if (indexAsset != null)
break;
if (iAssetList.assetBundleName == assetBundleName)
{
foreach (AssetBundleIndexItem iAsset in iAssetList.assetBundleAssets)
{
if (assetNameHash == iAsset.assetHash)
{
if (type == "" || (type != "" && (type == iAsset.assetType || type == GetTypeWithoutAssembly(iAsset.assetType))))
{
indexAsset = iAsset;
}
}
if (indexAsset != null)
break;
}
}
}
return indexAsset;
}
public string GetAssetNameFromFilename(string filename, string type = "")
{
string assetName = "";
string[] foundInBundles = FindContainingAssetBundle(filename, type);
if (foundInBundles.Length > 0)
{
assetName = GetAssetBundleIndexItem(foundInBundles[0], filename, type).assetName;
}
return assetName;
}
public string GetAssetNameFromFilename(string assetBundleName, string filename, string type = "")
{
string assetName = "";
assetName = GetAssetBundleIndexItem(assetBundleName, filename, type).assetName;
return assetName;
}
public string GetAssetNameFromHash(int? assetNameHash, string type = "")
{
string assetName = "";
string[] foundInBundles = FindContainingAssetBundle(assetNameHash, type);
if (foundInBundles.Length > 0)
{
assetName = GetAssetBundleIndexItem(foundInBundles[0], assetNameHash, type).assetName;
}
return assetName;
}
public string GetAssetNameFromHash(string assetBundleName, int? assetNameHash, string type = "")
{
string assetName = "";
assetName = GetAssetBundleIndexItem(assetBundleName, assetNameHash, type).assetName;
return assetName;
}
public int? GetAssetHashFromName(string assetBundleName, string assetName, string type = "")
{
int? assetNameHash = null;
assetNameHash = (int?)GetAssetBundleIndexItem(assetBundleName, assetName, type).assetHash;
return assetNameHash;
}
string GetTypeWithoutAssembly(string fullType)
{
//we could do with also checking anything after the last '.' since I am not sure if GetType always includes the assembly
//i.e. I am not sure if will always return 'UMA.OverlayDataAsset', of if its called in a UMA namespaced script it just returns 'OverlayDataAsset'
string typeWithoutAssembly = fullType;
if (fullType.IndexOf(".") > -1)
{
//will need to do regex on this and get the last match...
typeWithoutAssembly = Regex.Match(fullType, "[^.]+$").Value;
}
return typeWithoutAssembly;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Benchmarks
{
using System;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Apache.Ignite.Benchmarks.Model;
/// <summary>
/// Utility methods for benchmarks.
/// </summary>
internal static class BenchmarkUtils
{
/** Property binding flags. */
private static readonly BindingFlags PropFlags = BindingFlags.Instance | BindingFlags.Public;
/** Thread-local random. */
private static readonly ThreadLocal<Random> Rand;
/** Cached ANSI chcracters. */
private static readonly char[] Chars;
/** Seed to randoms. */
private static int _seedCtr;
/// <summary>
/// Static initializer.
/// </summary>
static BenchmarkUtils()
{
Rand = new ThreadLocal<Random>(() =>
{
var seed = Interlocked.Add(ref _seedCtr, 100);
return new Random(seed);
});
Chars = new char[10 + 26 + 26];
var pos = 0;
for (var i = '0'; i < '0' + 10; i++)
Chars[pos++] = i;
for (var i = 'A'; i < 'A' + 26; i++)
Chars[pos++] = i;
for (var i = 'a'; i < 'a' + 26; i++)
Chars[pos++] = i;
}
/// <summary>
/// Generate random integer.
/// </summary>
/// <param name="max">Maximum value (exclusive).</param>
/// <returns></returns>
public static int GetRandomInt(int max)
{
return GetRandomInt(0, max);
}
/// <summary>
/// Generate random integer.
/// </summary>
/// <param name="min">Minimum value (inclusive).</param>
/// <param name="max">Maximum value (exclusive).</param>
/// <returns></returns>
public static int GetRandomInt(int min, int max)
{
return Rand.Value.Next(min, max);
}
/// <summary>
/// Generate random string.
/// </summary>
/// <param name="len">Length.</param>
/// <returns>String.</returns>
public static string GetRandomString(int len)
{
var rand = Rand.Value;
var sb = new StringBuilder();
for (var i = 0; i < len; i++)
sb.Append(Chars[rand.Next(Chars.Length)]);
return sb.ToString();
}
/// <summary>
/// Generate random address.
/// </summary>
/// <returns>Address.</returns>
public static Address GetRandomAddress()
{
return new Address(
GetRandomString(15),
GetRandomString(20),
GetRandomInt(1, 500),
GetRandomInt(1, 35)
);
}
/// <summary>
/// Generate random company.
/// </summary>
/// <returns>Company.</returns>
public static Company GetRandomCompany()
{
return new Company(
GetRandomInt(0, 100),
GetRandomString(20),
GetRandomInt(100, 3000),
GetRandomAddress(),
GetRandomString(20)
);
}
/// <summary>
/// Generate random employee.
/// </summary>
/// <param name="payload">Payload size.</param>
/// <returns>Employee.</returns>
public static Employee GetRandomEmployee(int payload)
{
return new Employee(
GetRandomInt(0, 1000),
GetRandomString(15),
GetRandomInt(0, 1000),
GetRandomInt(18, 60),
(Sex)GetRandomInt(0, 1),
GetRandomInt(10000, 30000),
GetRandomAddress(),
(Department)GetRandomInt(0, 5),
payload
);
}
/// <summary>
/// List all properties present in the given object.
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>Properties.</returns>
public static PropertyInfo[] GetProperties(object obj)
{
return obj.GetType().GetProperties(PropFlags);
}
/// <summary>
/// Find property with the given name in the object.
/// </summary>
/// <param name="obj">Object.</param>
/// <param name="name">Name.</param>
/// <returns>Property.</returns>
public static PropertyInfo GetProperty(object obj, string name)
{
return GetProperties(obj)
.FirstOrDefault(prop => prop.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Set property on the given object.
/// </summary>
/// <param name="obj">Object.</param>
/// <param name="prop">Property.</param>
/// <param name="val">Value.</param>
public static void SetProperty(object obj, PropertyInfo prop, string val)
{
object val0;
var propType = prop.PropertyType;
if (propType == typeof(int))
{
try
{
val0 = int.Parse(val);
}
catch (Exception e)
{
throw new Exception("Failed to parse property value [property=" + prop.Name +
", value=" + val + ']', e);
}
}
else if (propType == typeof(long))
{
try
{
val0 = long.Parse(val);
}
catch (Exception e)
{
throw new Exception("Failed to parse property value [property=" + prop.Name +
", value=" + val + ']', e);
}
}
else if (propType == typeof(bool))
{
try
{
val0 = bool.Parse(val);
}
catch (Exception e)
{
throw new Exception("Failed to parse property value [property=" + prop.Name +
", value=" + val + ']', e);
}
}
else if (propType == typeof(string))
val0 = val;
else
throw new Exception("Unsupported property type [property=" + prop.Name +
", type=" + propType.Name + ']');
prop.SetValue(obj, val0, null);
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
// initializeCore
// Initializes core game functionality.
//---------------------------------------------------------------------------------------------
function initializeCore()
{
// Not Reentrant
if( $coreInitialized == true )
return;
// Core keybindings.
GlobalActionMap.bind(keyboard, tilde, toggleConsole);
GlobalActionMap.bind(keyboard, "ctrl p", doScreenShot);
GlobalActionMap.bindcmd(keyboard, "alt enter", "Canvas.attemptFullscreenToggle();","");
GlobalActionMap.bindcmd(keyboard, "alt k", "cls();", "");
// GlobalActionMap.bindCmd(keyboard, "escape", "", "handleEscape();");
// Very basic functions used by everyone.
exec("./audio.cs");
exec("./canvas.cs");
exec("./cursor.cs");
exec("./persistenceManagerTest.cs");
// Content.
exec("~/art/gui/profiles.cs");
exec("~/scripts/gui/cursors.cs");
exec( "./audioEnvironments.cs" );
exec( "./audioDescriptions.cs" );
exec( "./audioStates.cs" );
exec( "./audioAmbiences.cs" );
// Seed the random number generator.
setRandomSeed();
// Set up networking.
setNetPort(0);
// Initialize the canvas.
initializeCanvas();
// Start processing file change events.
startFileChangeNotifications();
// Core Guis.
exec("~/art/gui/remapDlg.gui");
exec("~/art/gui/console.gui");
exec("~/art/gui/consoleVarDlg.gui");
exec("~/art/gui/netGraphGui.gui");
// Gui Helper Scripts.
exec("~/scripts/gui/help.cs");
// Random Scripts.
exec("~/scripts/client/screenshot.cs");
exec("~/scripts/client/scriptDoc.cs");
//exec("~/scripts/client/keybindings.cs");
exec("~/scripts/client/helperfuncs.cs");
exec("~/scripts/client/commands.cs");
// Client scripts
exec("~/scripts/client/devHelpers.cs");
exec("~/scripts/client/metrics.cs");
exec("~/scripts/client/recordings.cs");
exec("~/scripts/client/centerPrint.cs");
// Materials and Shaders for rendering various object types
loadCoreMaterials();
exec("~/scripts/client/commonMaterialData.cs");
exec("~/scripts/client/shaders.cs");
exec("~/scripts/client/materials.cs");
exec("~/scripts/client/terrainBlock.cs");
exec("~/scripts/client/water.cs");
exec("~/scripts/client/imposter.cs");
exec("~/scripts/client/scatterSky.cs");
exec("~/scripts/client/clouds.cs");
// Initialize all core post effects.
exec("~/scripts/client/postFx.cs");
initPostEffects();
// Initialize the post effect manager.
exec("~/scripts/client/postFx/postFXManager.gui");
exec("~/scripts/client/postFx/postFXManager.gui.cs");
exec("~/scripts/client/postFx/postFXManager.gui.settings.cs");
exec("~/scripts/client/postFx/postFXManager.persistance.cs");
PostFXManager.settingsApplyDefaultPreset(); // Get the default preset settings
// Set a default cursor.
Canvas.setCursor(DefaultCursor);
loadKeybindings();
$coreInitialized = true;
}
//---------------------------------------------------------------------------------------------
// shutdownCore
// Shuts down core game functionality.
//---------------------------------------------------------------------------------------------
function shutdownCore()
{
// Stop file change events.
stopFileChangeNotifications();
sfxShutdown();
}
//---------------------------------------------------------------------------------------------
// dumpKeybindings
// Saves of all keybindings.
//---------------------------------------------------------------------------------------------
function dumpKeybindings()
{
// Loop through all the binds.
for (%i = 0; %i < $keybindCount; %i++)
{
// If we haven't dealt with this map yet...
if (isObject($keybindMap[%i]))
{
// Save and delete.
$keybindMap[%i].save(getPrefsPath("bind.cs"), %i == 0 ? false : true);
$keybindMap[%i].delete();
}
}
}
function handleEscape()
{
if (isObject(EditorGui))
{
if (Canvas.getContent() == EditorGui.getId())
{
EditorGui.handleEscape();
return;
}
else if ( EditorIsDirty() )
{
MessageBoxYesNoCancel( "Level Modified", "Level has been modified in the Editor. Save?",
"EditorDoExitMission(1);",
"EditorDoExitMission();",
"");
return;
}
}
if (isObject(GuiEditor))
{
if (GuiEditor.isAwake())
{
GuiEditCanvas.quit();
return;
}
}
if (PlayGui.isAwake())
escapeFromGame();
}
//-----------------------------------------------------------------------------
// loadMaterials - load all materials.cs files
//-----------------------------------------------------------------------------
function loadCoreMaterials()
{
// Load any materials files for which we only have DSOs.
for( %file = findFirstFile( "core/materials.cs.dso" );
%file !$= "";
%file = findNextFile( "core/materials.cs.dso" ))
{
// Only execute, if we don't have the source file.
%csFileName = getSubStr( %file, 0, strlen( %file ) - 4 );
if( !isFile( %csFileName ) )
exec( %csFileName );
}
// Load all source material files.
for( %file = findFirstFile( "core/materials.cs" );
%file !$= "";
%file = findNextFile( "core/materials.cs" ))
{
exec( %file );
}
}
function reloadCoreMaterials()
{
reloadTextures();
loadCoreMaterials();
reInitMaterials();
}
//-----------------------------------------------------------------------------
// loadMaterials - load all materials.cs files
//-----------------------------------------------------------------------------
function loadMaterials()
{
// Load any materials files for which we only have DSOs.
for( %file = findFirstFile( "*/materials.cs.dso" );
%file !$= "";
%file = findNextFile( "*/materials.cs.dso" ))
{
// Only execute, if we don't have the source file.
%csFileName = getSubStr( %file, 0, strlen( %file ) - 4 );
if( !isFile( %csFileName ) )
exec( %csFileName );
}
// Load all source material files.
for( %file = findFirstFile( "*/materials.cs" );
%file !$= "";
%file = findNextFile( "*/materials.cs" ))
{
exec( %file );
}
// Load all materials created by the material editor if
// the folder exists
if( IsDirectory( "materialEditor" ) )
{
for( %file = findFirstFile( "materialEditor/*.cs.dso" );
%file !$= "";
%file = findNextFile( "materialEditor/*.cs.dso" ))
{
// Only execute, if we don't have the source file.
%csFileName = getSubStr( %file, 0, strlen( %file ) - 4 );
if( !isFile( %csFileName ) )
exec( %csFileName );
}
for( %file = findFirstFile( "materialEditor/*.cs" );
%file !$= "";
%file = findNextFile( "materialEditor/*.cs" ))
{
exec( %file );
}
}
}
function reloadMaterials()
{
reloadTextures();
loadMaterials();
reInitMaterials();
}
| |
//------------------------------------------------------------------------------
// <copyright file="Focus.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Xsl.XPath;
using System.Xml.Xsl.Qil;
namespace System.Xml.Xsl.Xslt {
using T = XmlQueryTypeFactory;
// <spec>http://www.w3.org/TR/xslt20/#dt-singleton-focus</spec>
internal enum SingletonFocusType {
// No context set
// Used to prevent bugs
None,
// Document node of the document containing the initial context node
// Used while compiling global variables and params
InitialDocumentNode,
// Initial context node for the transformation
// Used while compiling initial apply-templates
InitialContextNode,
// Context node is specified by iterator
// Used while compiling keys
Iterator,
}
internal struct SingletonFocus : IFocus {
private XPathQilFactory f;
private SingletonFocusType focusType;
private QilIterator current;
public SingletonFocus(XPathQilFactory f) {
this.f = f;
focusType = SingletonFocusType.None;
current = null;
}
public void SetFocus(SingletonFocusType focusType) {
Debug.Assert(focusType != SingletonFocusType.Iterator);
this.focusType = focusType;
}
public void SetFocus(QilIterator current) {
if (current != null) {
this.focusType = SingletonFocusType.Iterator;
this.current = current;
} else {
this.focusType = SingletonFocusType.None;
this.current = null;
}
}
[Conditional("DEBUG")]
private void CheckFocus() {
Debug.Assert(focusType != SingletonFocusType.None, "Focus is not set, call SetFocus first");
}
public QilNode GetCurrent() {
CheckFocus();
switch (focusType) {
case SingletonFocusType.InitialDocumentNode: return f.Root(f.XmlContext());
case SingletonFocusType.InitialContextNode : return f.XmlContext();
default:
Debug.Assert(focusType == SingletonFocusType.Iterator && current != null, "Unexpected singleton focus type");
return current;
}
}
public QilNode GetPosition() {
CheckFocus();
return f.Double(1);
}
public QilNode GetLast() {
CheckFocus();
return f.Double(1);
}
}
internal struct FunctionFocus : IFocus {
private bool isSet;
private QilParameter current, position, last;
public void StartFocus(IList<QilNode> args, XslFlags flags) {
Debug.Assert(! IsFocusSet, "Focus was already set");
int argNum = 0;
if ((flags & XslFlags.Current) != 0) {
this.current = (QilParameter)args[argNum ++];
Debug.Assert(this.current.Name.NamespaceUri == XmlReservedNs.NsXslDebug && this.current.Name.LocalName == "current");
}
if ((flags & XslFlags.Position) != 0) {
this.position = (QilParameter)args[argNum ++];
Debug.Assert(this.position.Name.NamespaceUri == XmlReservedNs.NsXslDebug && this.position.Name.LocalName == "position");
}
if ((flags & XslFlags.Last) != 0) {
this.last = (QilParameter)args[argNum ++];
Debug.Assert(this.last.Name.NamespaceUri == XmlReservedNs.NsXslDebug && this.last.Name.LocalName == "last");
}
this.isSet = true;
}
public void StopFocus() {
Debug.Assert(IsFocusSet, "Focus was not set");
isSet = false;
this.current = this.position = this.last = null;
}
public bool IsFocusSet {
get { return this.isSet; }
}
public QilNode GetCurrent() {
Debug.Assert(this.current != null, "---- current() is not expected in this function");
return this.current;
}
public QilNode GetPosition() {
Debug.Assert(this.position != null, "---- position() is not expected in this function");
return this.position;
}
public QilNode GetLast() {
Debug.Assert(this.last != null, "---- last() is not expected in this function");
return this.last;
}
}
internal struct LoopFocus : IFocus {
private XPathQilFactory f;
private QilIterator current, cached, last;
public LoopFocus(XPathQilFactory f) {
this.f = f;
current = cached = last = null;
}
public void SetFocus(QilIterator current) {
this.current = current;
cached = last = null;
}
public bool IsFocusSet {
get { return current != null; }
}
public QilNode GetCurrent() {
return current;
}
public QilNode GetPosition() {
return f.XsltConvert(f.PositionOf(current), T.DoubleX);
}
public QilNode GetLast() {
if (last == null) {
// Create a let that will be fixed up later in ConstructLoop or by LastFixupVisitor
last = f.Let(f.Double(0));
}
return last;
}
public void EnsureCache() {
if (cached == null) {
cached = f.Let(current.Binding);
current.Binding = cached;
}
}
public void Sort(QilNode sortKeys) {
if (sortKeys != null) {
// If sorting is required, cache the input node-set to support last() within sort key expressions
EnsureCache();
// The rest of the loop content must be compiled in the context of already sorted node-set
current = f.For(f.Sort(current, sortKeys));
}
}
public QilLoop ConstructLoop(QilNode body) {
QilLoop result;
if (last != null) {
// last() encountered either in the sort keys or in the body of the current loop
EnsureCache();
last.Binding = f.XsltConvert(f.Length(cached), T.DoubleX);
}
result = f.BaseFactory.Loop(current, body);
if (last != null) {
result = f.BaseFactory.Loop(last, result);
}
if (cached != null) {
result = f.BaseFactory.Loop(cached, result);
}
return result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Numerics.Tests
{
public class powTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunPowPositive()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Pow Method - 0^(1)
VerifyPowString(BigInteger.One.ToString() + " " + BigInteger.Zero.ToString() + " bPow");
// Pow Method - 0^(0)
VerifyPowString(BigInteger.Zero.ToString() + " " + BigInteger.Zero.ToString() + " bPow");
// Pow Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 1);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
}
// Pow Method - One large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 1);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
}
// Pow Method - One large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { 0 };
VerifyPowString(Print(tempByteArray2) + Print(tempByteArray1) + "bPow");
}
// Pow Method - One small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 2);
tempByteArray2 = new byte[] { 0 };
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
VerifyPowString(Print(tempByteArray2) + Print(tempByteArray1) + "bPow");
}
}
[Fact]
public static void RunPowAxiomXPow1()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X^1 = X
VerifyIdentityString(BigInteger.One + " " + Int32.MaxValue + " bPow", Int32.MaxValue.ToString());
VerifyIdentityString(BigInteger.One + " " + Int64.MaxValue + " bPow", Int64.MaxValue.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(BigInteger.One + " " + randBigInt + "bPow", randBigInt.Substring(0, randBigInt.Length - 1));
}
}
[Fact]
public static void RunPowAxiomXPow0()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X^0 = 1
VerifyIdentityString(BigInteger.Zero + " " + Int32.MaxValue + " bPow", BigInteger.One.ToString());
VerifyIdentityString(BigInteger.Zero + " " + Int64.MaxValue + " bPow", BigInteger.One.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(BigInteger.Zero + " " + randBigInt + "bPow", BigInteger.One.ToString());
}
}
[Fact]
public static void RunPowAxiom0PowX()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: 0^X = 0
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " bPow", BigInteger.Zero.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomPosByteArray(s_random, 4));
VerifyIdentityString(randBigInt + BigInteger.Zero + " bPow", BigInteger.Zero.ToString());
}
}
[Fact]
public static void RunPowAxiom1PowX()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: 1^X = 1
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " bPow", BigInteger.One.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomPosByteArray(s_random, 4));
VerifyIdentityString(randBigInt + BigInteger.One + " bPow", BigInteger.One.ToString());
}
}
[Fact]
public static void RunPowBoundary()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyPowString("2 " + Math.Pow(2, 32) + " bPow");
// 32 bit boundary n1=0 n2=1
VerifyPowString("2 " + Math.Pow(2, 33) + " bPow");
}
[Fact]
public static void RunPowNegative()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Pow Method - 1^(-1)
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyPowString(BigInteger.MinusOne.ToString() + " " + BigInteger.One.ToString() + " bPow");
});
// Pow Method - 0^(-1)
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyPowString(BigInteger.MinusOne.ToString() + " " + BigInteger.Zero.ToString() + " bPow");
});
// Pow Method - Negative Exponent
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomNegByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
});
}
}
private static void VerifyPowString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static void VerifyIdentityString(string opstring1, string opstring2)
{
StackCalc sc1 = new StackCalc(opstring1);
while (sc1.DoNextOperation())
{
//Run the full calculation
sc1.DoNextOperation();
}
StackCalc sc2 = new StackCalc(opstring2);
while (sc2.DoNextOperation())
{
//Run the full calculation
sc2.DoNextOperation();
}
Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString());
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 10));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
private static Byte[] GetRandomPosByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] &= 0x7F;
return value;
}
private static Byte[] GetRandomNegByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] |= 0x80;
return value;
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace LibGit2Sharp.Core
{
internal class HistoryRewriter
{
private readonly IRepository repo;
private readonly HashSet<Commit> targetedCommits;
private readonly Dictionary<GitObject, GitObject> objectMap = new Dictionary<GitObject, GitObject>();
private readonly Dictionary<Reference, Reference> refMap = new Dictionary<Reference, Reference>();
private readonly Queue<Action> rollbackActions = new Queue<Action>();
private readonly string backupRefsNamespace;
private readonly RewriteHistoryOptions options;
public HistoryRewriter(
IRepository repo,
IEnumerable<Commit> commitsToRewrite,
RewriteHistoryOptions options)
{
this.repo = repo;
this.options = options;
targetedCommits = new HashSet<Commit>(commitsToRewrite);
backupRefsNamespace = this.options.BackupRefsNamespace;
if (!backupRefsNamespace.EndsWith("/", StringComparison.Ordinal))
{
backupRefsNamespace += "/";
}
}
public void Execute()
{
var success = false;
try
{
// Find out which refs lead to at least one the commits
var refsToRewrite = repo.Refs.ReachableFrom(targetedCommits).ToList();
var filter = new CommitFilter
{
Since = refsToRewrite,
SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Topological
};
var commits = repo.Commits.QueryBy(filter);
foreach (var commit in commits)
{
RewriteCommit(commit);
}
// Ordering matters. In the case of `A -> B -> commit`, we need to make sure B is rewritten
// before A.
foreach (var reference in refsToRewrite.OrderBy(ReferenceDepth))
{
// TODO: Check how rewriting of notes actually behaves
RewriteReference(reference);
}
success = true;
if (options.OnSucceeding != null)
{
options.OnSucceeding();
}
}
catch (Exception ex)
{
try
{
if (!success && options.OnError != null)
{
options.OnError(ex);
}
}
finally
{
foreach (var action in rollbackActions)
{
action();
}
}
throw;
}
finally
{
rollbackActions.Clear();
}
}
private Reference RewriteReference(Reference reference)
{
// Has this target already been rewritten?
if (refMap.ContainsKey(reference))
{
return refMap[reference];
}
var sref = reference as SymbolicReference;
if (sref != null)
{
return RewriteReference(
sref, old => old.Target, RewriteReference,
(refs, old, target, sig, logMessage) => refs.UpdateTarget(old, target, sig, logMessage));
}
var dref = reference as DirectReference;
if (dref != null)
{
return RewriteReference(
dref, old => old.Target, RewriteTarget,
(refs, old, target, sig, logMessage) => refs.UpdateTarget(old, target.Id, sig, logMessage));
}
return reference;
}
private delegate Reference ReferenceUpdater<in TRef, in TTarget>(
ReferenceCollection refs, TRef origRef, TTarget origTarget, Signature signature, string logMessage)
where TRef : Reference
where TTarget : class;
private Reference RewriteReference<TRef, TTarget>(
TRef oldRef, Func<TRef, TTarget> selectTarget,
Func<TTarget, TTarget> rewriteTarget,
ReferenceUpdater<TRef, TTarget> updateTarget)
where TRef : Reference
where TTarget : class
{
var oldRefTarget = selectTarget(oldRef);
var signature = repo.Config.BuildSignature(DateTimeOffset.Now);
string newRefName = oldRef.CanonicalName;
if (oldRef.IsTag() && options.TagNameRewriter != null)
{
newRefName = Reference.TagPrefix +
options.TagNameRewriter(oldRef.CanonicalName.Substring(Reference.TagPrefix.Length),
false, oldRef.TargetIdentifier);
}
var newTarget = rewriteTarget(oldRefTarget);
if (oldRefTarget.Equals(newTarget) && oldRef.CanonicalName == newRefName)
{
// The reference isn't rewritten
return oldRef;
}
string backupName = backupRefsNamespace + oldRef.CanonicalName.Substring("refs/".Length);
if (repo.Refs.Resolve<Reference>(backupName) != null)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.InvariantCulture, "Can't back up reference '{0}' - '{1}' already exists",
oldRef.CanonicalName, backupName));
}
repo.Refs.Add(backupName, oldRef.TargetIdentifier, signature, "filter-branch: backup");
rollbackActions.Enqueue(() => repo.Refs.Remove(backupName));
if (newTarget == null)
{
repo.Refs.Remove(oldRef);
rollbackActions.Enqueue(() => repo.Refs.Add(oldRef.CanonicalName, oldRef, signature, "filter-branch: abort", true));
return refMap[oldRef] = null;
}
Reference newRef = updateTarget(repo.Refs, oldRef, newTarget, signature, "filter-branch: rewrite");
rollbackActions.Enqueue(() => updateTarget(repo.Refs, oldRef, oldRefTarget, signature, "filter-branch: abort"));
if (newRef.CanonicalName == newRefName)
{
return refMap[oldRef] = newRef;
}
var movedRef = repo.Refs.Rename(newRef, newRefName);
rollbackActions.Enqueue(() => repo.Refs.Rename(newRef, oldRef.CanonicalName));
return refMap[oldRef] = movedRef;
}
private void RewriteCommit(Commit commit)
{
var newHeader = CommitRewriteInfo.From(commit);
var newTree = commit.Tree;
// Find the new parents
var newParents = commit.Parents;
if (targetedCommits.Contains(commit))
{
// Get the new commit header
if (options.CommitHeaderRewriter != null)
{
newHeader = options.CommitHeaderRewriter(commit) ?? newHeader;
}
if (options.CommitTreeRewriter != null)
{
// Get the new commit tree
var newTreeDefinition = options.CommitTreeRewriter(commit);
newTree = repo.ObjectDatabase.CreateTree(newTreeDefinition);
}
// Retrieve new parents
if (options.CommitParentsRewriter != null)
{
newParents = options.CommitParentsRewriter(commit);
}
}
// Create the new commit
var mappedNewParents = newParents
.Select(oldParent =>
objectMap.ContainsKey(oldParent)
? objectMap[oldParent] as Commit
: oldParent)
.Where(newParent => newParent != null)
.ToList();
if (options.PruneEmptyCommits &&
TryPruneEmptyCommit(commit, mappedNewParents, newTree))
{
return;
}
var newCommit = repo.ObjectDatabase.CreateCommit(newHeader.Author,
newHeader.Committer,
newHeader.Message,
newTree,
mappedNewParents,
true);
// Record the rewrite
objectMap[commit] = newCommit;
}
private bool TryPruneEmptyCommit(Commit commit, IList<Commit> mappedNewParents, Tree newTree)
{
var parent = mappedNewParents.Count > 0 ? mappedNewParents[0] : null;
if (parent == null)
{
if (newTree.Count == 0)
{
objectMap[commit] = null;
return true;
}
}
else if (parent.Tree == newTree)
{
objectMap[commit] = parent;
return true;
}
return false;
}
private GitObject RewriteTarget(GitObject oldTarget)
{
// Has this target already been rewritten?
if (objectMap.ContainsKey(oldTarget))
{
return objectMap[oldTarget];
}
Debug.Assert((oldTarget as Commit) == null);
var annotation = oldTarget as TagAnnotation;
if (annotation == null)
{
//TODO: Probably a Tree or a Blob. This is not covered by any test
return oldTarget;
}
// Recursively rewrite annotations if necessary
var newTarget = RewriteTarget(annotation.Target);
string newName = annotation.Name;
if (options.TagNameRewriter != null)
{
newName = options.TagNameRewriter(annotation.Name, true, annotation.Target.Sha);
}
var newAnnotation = repo.ObjectDatabase.CreateTagAnnotation(newName, newTarget, annotation.Tagger,
annotation.Message);
objectMap[annotation] = newAnnotation;
return newAnnotation;
}
private int ReferenceDepth(Reference reference)
{
var dref = reference as DirectReference;
return dref == null
? 1 + ReferenceDepth(((SymbolicReference)reference).Target)
: 1;
}
}
}
/* This is extra221 */
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using Gallio.Common.Collections;
using Gallio.Model.Schema;
using Gallio.Runner.Extensions;
using Gallio.Runner.Projects;
using Gallio.Runner.Reports.Schema;
using Gallio.Runtime.Logging;
using Gallio.Runtime.ProgressMonitoring;
using Gallio.Runtime;
using Gallio.Model;
using Gallio.Runner.Reports;
using System.Threading;
namespace Gallio.Runner
{
/// <summary>
/// The test launcher encapsulated the entire test execution lifecycle from
/// start to finish and provides a simplified pattern for running tests.
/// </summary>
/// <remarks>
/// <para>
/// The basic usage pattern is as follows:
/// <list type="numbered">
/// <item>Create the launcher.</item>
/// <item>Set properties to specify the inputs and outputs of the test run.</item>
/// <item>Run the tests all in one go.</item>
/// <item>Optionally do something with the contents of the final report.</item>
/// </list>
/// </para>
/// <para>
/// By default, the launcher assumes that a runtime environment has already been
/// established and is accessible via the <see cref="RuntimeAccessor" />. If there
/// is no runtime yet, then you can cause one to be configured automatically for the
/// duration of the test run by setting the <see cref="RuntimeSetup"/> property accordingly.
/// </para>
/// </remarks>
public class TestLauncher
{
private readonly List<string> filePatterns;
private TestProject testProject;
private TestRunnerOptions testRunnerOptions;
private TestExplorationOptions testExplorationOptions;
private TestExecutionOptions testExecutionOptions;
private readonly List<string> reportFormats;
private ReportFormatterOptions reportFormatterOptions;
private IProgressMonitorProvider progressMonitorProvider;
private ILogger logger;
private readonly object cancelationSyncRoot = new object();
private bool isCanceled;
private IProgressMonitor cancelableProgressMonitor;
/// <summary>
/// Creates a launcher with default options and no test assemblies specified.
/// </summary>
public TestLauncher()
{
filePatterns = new List<string>();
testProject = new TestProject();
testRunnerOptions = new TestRunnerOptions();
testExplorationOptions = new TestExplorationOptions();
testExecutionOptions = new TestExecutionOptions();
reportFormats = new List<string>();
reportFormatterOptions = new ReportFormatterOptions();
progressMonitorProvider = NullProgressMonitorProvider.Instance;
logger = NullLogger.Instance;
}
/// <summary>
/// Gets or sets the progress monitor provider to use.
/// </summary>
/// <remarks>
/// <para>
/// The default provider is <see cref="NullProgressMonitorProvider.Instance" />.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public IProgressMonitorProvider ProgressMonitorProvider
{
get
{
return progressMonitorProvider;
}
set
{
if (value == null)
throw new ArgumentNullException(@"value");
progressMonitorProvider = value;
}
}
/// <summary>
/// Gets or sets the logger to use.
/// </summary>
/// <remarks>
/// <para>
/// The default logger is <see cref="NullLogger.Instance" />.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public ILogger Logger
{
get
{
return logger;
}
set
{
if (value == null)
throw new ArgumentNullException(@"value");
logger = value;
}
}
/// <summary>
/// Gets or sets the <see cref="RuntimeSetup" /> to use for automatically initializing
/// the runtime during test execution or <c>null</c> if the runtime is already initialized.
/// </summary>
/// <remarks>
/// <para>
/// If this value if not <c>null</c> then the launcher will initialize the runtime
/// using this <see cref="RuntimeSetup" /> (unless already initialized) just prior to
/// test execution and will automatically shut down the runtime just afterwards.
/// </para>
/// <para>
/// The default value is <c>null</c> which assumes that the runtime is already initialized.
/// </para>
/// </remarks>
public RuntimeSetup RuntimeSetup
{
get;
set;
}
/// <summary>
/// Gets or sets the test runner options.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public TestRunnerOptions TestRunnerOptions
{
get
{
return testRunnerOptions;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
testRunnerOptions = value;
}
}
/// <summary>
/// Gets a read-only list of test file patterns (with wildcards) or test project files
/// that are to be resolved and included in the test package prior to execution.
/// </summary>
public IList<string> FilePatterns
{
get
{
return new ReadOnlyCollection<string>(filePatterns);
}
}
/// <summary>
/// Gets or sets the test project.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public TestProject TestProject
{
get
{
return testProject;
}
set
{
if (value == null)
throw new ArgumentNullException(@"value");
testProject = value;
}
}
/// <summary>
/// Gets or sets the test exploration options.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public TestExplorationOptions TestExplorationOptions
{
get
{
return testExplorationOptions;
}
set
{
if (value == null)
throw new ArgumentNullException(@"value");
testExplorationOptions = value;
}
}
/// <summary>
/// Gets or sets the test execution options.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public TestExecutionOptions TestExecutionOptions
{
get
{
return testExecutionOptions;
}
set
{
if (value == null)
throw new ArgumentNullException(@"value");
testExecutionOptions = value;
}
}
/// <summary>
/// Controls whether the test runner will echo result to the <see cref="Logger" />
/// as each test finishes.
/// </summary>
/// <remarks>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </remarks>
public bool EchoResults
{
get;
set;
}
/// <summary>
/// Gets or sets whether to skip test execution.
/// </summary>
/// <remarks>
/// <para>
/// This option may be used to produce a report that contains test
/// metadata for consumption by other tools.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </remarks>
public bool DoNotRun
{
get;
set;
}
/// <summary>
/// Gets a read-only list of report formats to generate.
/// </summary>
public IList<string> ReportFormats
{
get
{
return new ReadOnlyCollection<string>(reportFormats);
}
}
/// <summary>
/// Gets or sets the report formatter options.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public ReportFormatterOptions ReportFormatterOptions
{
get
{
return reportFormatterOptions;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
reportFormatterOptions = value;
}
}
/// <summary>
/// Gets or sets whether to show the reports after the test run finishes.
/// </summary>
/// <remarks>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </remarks>
public bool ShowReports
{
get;
set;
}
/// <summary>
/// Gets or sets whether to ignore annotations when determining the result code.
/// </summary>
/// <remarks>
/// <para>
/// If false, then error annotations, usually indicative of broken tests, will cause
/// a failure result to be generated.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </remarks>
public bool IgnoreAnnotations
{
get;
set;
}
/// <summary>
/// Gets or sets the maximum amount of time the tests can run before they are canceled.
/// </summary>
/// <remarks>
/// <para>
/// The default value is <c>null</c>, meaning an infinite time.
/// </para>
/// </remarks>
public TimeSpan? RunTimeLimit
{
get;
set;
}
/// <summary>
/// Clears the list of file patterns.
/// </summary>
public void ClearFilePatterns()
{
filePatterns.Clear();
}
/// <summary>
/// Adds a file pattern if not already added to the launcher.
/// </summary>
/// <param name="filePattern">The file path or a wildcard pattern to add.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="filePattern"/> is null.</exception>
public void AddFilePattern(string filePattern)
{
if (filePattern == null)
throw new ArgumentNullException("filePattern");
if (!filePatterns.Contains(filePattern))
filePatterns.Add(filePattern);
}
/// <summary>
/// Removes a file pattern.
/// </summary>
/// <param name="filePattern">The file pattern to remove.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="filePattern"/> is null.</exception>
public void RemoveFilePattern(string filePattern)
{
if (filePattern == null)
throw new ArgumentNullException("filePattern");
filePatterns.Remove(filePattern);
}
/// <summary>
/// Clears the list of report formats.
/// </summary>
public void ClearReportFormats()
{
reportFormats.Clear();
}
/// <summary>
/// Adds a report format if not already added to the launcher.
/// </summary>
/// <param name="reportFormat">The report format to add.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="reportFormat"/> is null.</exception>
public void AddReportFormat(string reportFormat)
{
if (reportFormat == null)
throw new ArgumentNullException("reportFormat");
if (!reportFormats.Contains(reportFormat))
reportFormats.Add(reportFormat);
}
/// <summary>
/// Removes a report format.
/// </summary>
/// <param name="reportFormat">The report format to remove.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="reportFormat"/> is null.</exception>
public void RemoveReportFormat(string reportFormat)
{
if (reportFormat == null)
throw new ArgumentNullException("reportFormat");
reportFormats.Remove(reportFormat);
}
/// <summary>
/// Cancels the test run and prevents a new one from starting.
/// </summary>
public void Cancel()
{
lock (cancelationSyncRoot)
{
isCanceled = true;
if (cancelableProgressMonitor != null)
cancelableProgressMonitor.Cancel();
}
}
/// <summary>
/// Runs the test package as configured.
/// </summary>
/// <remarks>
/// <para>
/// If <see cref="RuntimeSetup" /> is non-<c>null</c>,
/// initializes the runtime for the duration of this method then shuts it down automatically
/// before returning. Otherwise assumes the runtime has already been initialized and
/// accesses it using <see cref="RuntimeAccessor" />.
/// </para>
/// <para>
/// Runtimes cannot be nested. So if the launcher is asked to initialize the runtime and
/// it has already been initialized, then it will not be initialized again.
/// </para>
/// </remarks>
/// <returns>A result object.</returns>
public TestLauncherResult Run()
{
Canonicalize(null);
DisplayConfiguration();
Timer runTimeTimer = null;
if (RunTimeLimit != null)
{
runTimeTimer = new Timer(delegate
{
Cancel();
logger.Log(LogSeverity.Warning, "Run time limit reached! Canceled test run.");
}, null, (int)RunTimeLimit.Value.TotalMilliseconds, Timeout.Infinite);
}
Stopwatch stopWatch = Stopwatch.StartNew();
logger.Log(LogSeverity.Important, String.Format("Start time: {0}", DateTime.Now.ToShortTimeString()));
bool wasCanceled = false;
try
{
using (InitializeRuntimeIfNeeded(ref wasCanceled))
{
if (wasCanceled)
return CreateResult(ResultCode.Canceled, testProject);
return RunWithRuntime();
}
}
finally
{
logger.Log(LogSeverity.Important,
String.Format("Stop time: {0} (Total execution time: {1:#0.000} seconds)",
DateTime.Now.ToShortTimeString(),
stopWatch.Elapsed.TotalSeconds));
if (runTimeTimer != null)
runTimeTimer.Dispose();
}
}
private IDisposable InitializeRuntimeIfNeeded(ref bool canceled)
{
IDisposable result = null;
if (RuntimeSetup != null && !RuntimeAccessor.IsInitialized)
{
RunWithProgress(progressMonitor =>
{
progressMonitor.BeginTask("Initializing the runtime and loading plugins.", 1);
result = RuntimeBootstrap.Initialize(RuntimeSetup, logger);
}, ref canceled);
}
return result;
}
private TestLauncherResult RunWithRuntime()
{
bool wasCanceled = false;
ITestProjectManager testProjectManager = RuntimeAccessor.ServiceLocator.Resolve<ITestProjectManager>();
TestProject consolidatedTestProject = ConsolidateTestProject(testProjectManager, ref wasCanceled);
if (wasCanceled)
return CreateResult(ResultCode.Canceled, testProject);
if (consolidatedTestProject == null)
return CreateResult(ResultCode.InvalidArguments, testProject);
if (consolidatedTestProject.TestPackage.Files.Count == 0)
{
logger.Log(LogSeverity.Warning, "No test files to execute!");
return CreateResult(ResultCode.NoTests, consolidatedTestProject);
}
IReportManager reportManager = RuntimeAccessor.ServiceLocator.Resolve<IReportManager>();
if (!ValidateReportFormats(reportManager, consolidatedTestProject))
return CreateResult(ResultCode.InvalidArguments, consolidatedTestProject);
ITestRunnerManager testRunnerManager = RuntimeAccessor.ServiceLocator.Resolve<ITestRunnerManager>();
ITestRunnerFactory testRunnerFactory = testRunnerManager.GetFactory(consolidatedTestProject.TestRunnerFactoryName);
if (testRunnerFactory == null)
{
logger.Log(LogSeverity.Error, String.Format("Unrecognized test runner factory name: '{0}'.", consolidatedTestProject.TestRunnerFactoryName));
return CreateResult(ResultCode.InvalidArguments, consolidatedTestProject);
}
ITestRunner runner = testRunnerFactory.CreateTestRunner();
var result = new TestLauncherResult(new Report { TestPackage = new TestPackageData(TestProject.TestPackage) });
try
{
DoRegisterExtensions(runner, consolidatedTestProject);
DoInitialize(runner, ref wasCanceled);
if (!wasCanceled)
{
result = RunWithInitializedRunner(runner, consolidatedTestProject, reportManager);
}
}
finally
{
DoDispose(runner, ref wasCanceled);
}
if (wasCanceled)
result.SetResultCode(ResultCode.Canceled);
return result;
}
private TestLauncherResult RunWithInitializedRunner(ITestRunner runner, TestProject consolidatedTestProject, IReportManager reportManager)
{
bool wasCanceled = false;
// Explore or Run tests.
Report report = DoExploreOrRun(runner, consolidatedTestProject.TestPackage, ref wasCanceled);
if (report == null)
report = new Report();
var result = new TestLauncherResult(report);
// Generate reports even if the test run is canceled, unless this step
// also gets canceled.
if (result.Report.TestPackageRun != null || DoNotRun)
GenerateReports(result, reportManager, consolidatedTestProject, ref wasCanceled);
// Done.
if (ShowReports)
ShowReportDocuments(result);
// Produce the final result code.
if (wasCanceled)
{
result.SetResultCode(ResultCode.Canceled);
}
else
{
if (! IgnoreAnnotations
&& result.Report.TestModel != null
&& result.Report.TestModel.GetErrorAnnotationCount() != 0)
result.SetResultCode(ResultCode.Failure);
else if (result.Report.TestPackageRun != null
&& result.Statistics.FailedCount > 0)
result.SetResultCode(ResultCode.Failure);
else if (result.Report.TestPackageRun != null
&& result.Statistics.TestCount == 0)
result.SetResultCode(ResultCode.NoTests);
}
return result;
}
private void GenerateReports(TestLauncherResult result, IReportManager reportManager,
TestProject consolidatedTestProject, ref bool canceled)
{
if (reportFormats.Count == 0)
return;
RunWithProgress(progressMonitor => result.GenerateReports(consolidatedTestProject.ReportDirectory,
result.Report.FormatReportName(consolidatedTestProject.ReportNameFormat), consolidatedTestProject.ReportArchive,
reportFormats, reportFormatterOptions, reportManager, progressMonitor), ref canceled);
}
private void ShowReportDocuments(TestLauncherResult result)
{
if (result.ReportDocumentPaths.Count == 0)
return;
logger.Log(LogSeverity.Important, "Displaying reports.");
if (!result.ShowReportDocuments())
logger.Log(LogSeverity.Important, "There was an error opening the report documents.");
}
private bool ValidateReportFormats(IReportManager reportManager, TestProject consolidatedTestProject)
{
foreach (string reportFormat in reportFormats)
{
IReportFormatter formatter = reportManager.GetReportFormatter(reportFormat);
if (formatter != null)
continue;
logger.Log(LogSeverity.Error, String.Format("Unrecognized report format: '{0}'.", reportFormat));
return false;
}
if (consolidatedTestProject.ReportNameFormat.Length == 0)
{
logger.Log(LogSeverity.Error, "Report name format must not be empty.");
return false;
}
return true;
}
private void DoRegisterExtensions(ITestRunner runner, TestProject consolidatedTestProject)
{
if (EchoResults)
runner.RegisterExtension(new LogExtension());
foreach (ITestRunnerExtension extension in consolidatedTestProject.TestRunnerExtensions)
runner.RegisterExtension(extension);
// de-dupe extension specs
List<string> uniqueExtensionSpecifications = new List<string>();
GenericCollectionUtils.AddAllIfNotAlreadyPresent(consolidatedTestProject.TestRunnerExtensionSpecifications,
uniqueExtensionSpecifications);
foreach (string extensionSpecification in uniqueExtensionSpecifications)
{
var testRunnerExtension =
TestRunnerExtensionUtils.CreateExtensionFromSpecification(extensionSpecification);
runner.RegisterExtension(testRunnerExtension);
}
}
private void DisplayConfiguration()
{
DisplayPaths(testProject.TestPackage.Files, "Test Files:");
DisplayPaths(testProject.TestPackage.HintDirectories, "Hint Directories:");
if (RuntimeSetup != null)
DisplayPaths(RuntimeSetup.PluginDirectories, "Plugin Directories:");
}
private void DisplayPaths<T>(ICollection<T> paths, string name)
where T : FileSystemInfo
{
DisplayPaths(GenericCollectionUtils.ConvertAllToArray(paths, path => path.ToString()), name);
}
private void DisplayPaths(ICollection<string> paths, string name)
{
if (paths == null || paths.Count <= 0)
return;
var message = new StringBuilder();
message.Append(name);
foreach (string path in paths)
message.Append("\n\t").Append(path);
message.AppendLine();
logger.Log(LogSeverity.Info, message.ToString());
}
private void Canonicalize(string baseDirectory)
{
if (RuntimeSetup != null)
RuntimeSetup.Canonicalize(baseDirectory);
}
/// <summary>
/// Processes test file patterns and generates a consolidated test project.
/// </summary>
private TestProject ConsolidateTestProject(ITestProjectManager testProjectManager, ref bool canceled)
{
TestProject consolidatedTestProject = null;
RunWithProgress(delegate(IProgressMonitor progressMonitor)
{
List<string> allFilePatterns = new List<string>(filePatterns);
GenericCollectionUtils.ConvertAndAddAll(testProject.TestPackage.Files, allFilePatterns, x => x.ToString());
TestProject overlayTestProject = testProject.Copy();
overlayTestProject.TestPackage.ClearFiles();
TestProject baseTestProject = null;
bool haveProject = false;
using (progressMonitor.BeginTask("Verifying test files.", Math.Max(allFilePatterns.Count, 1)))
{
foreach (string filePattern in allFilePatterns)
{
IList<FileInfo> files = ExpandFilePattern(filePattern);
if (files == null)
return;
foreach (FileInfo file in files)
{
bool isProject = file.Extension == TestProject.Extension;
if (isProject && overlayTestProject.TestPackage.Files.Count != 0 || haveProject)
{
logger.Log(LogSeverity.Error, "At most one test project can be specified at a time and it cannot be combined with other test files.");
return;
}
if (isProject)
{
haveProject = true;
try
{
baseTestProject = testProjectManager.LoadProject(file);
}
catch (Exception ex)
{
logger.Log(LogSeverity.Error, string.Format("Could not load test project '{0}'.", file.FullName), ex);
}
}
else
{
overlayTestProject.TestPackage.AddFile(file);
}
}
progressMonitor.Worked(1);
}
if (baseTestProject != null)
{
baseTestProject.ApplyOverlay(overlayTestProject);
consolidatedTestProject = baseTestProject;
}
else
{
consolidatedTestProject = overlayTestProject;
}
}
}, ref canceled);
return consolidatedTestProject;
}
private IList<FileInfo> ExpandFilePattern(string filePattern)
{
if (filePattern.Contains("?") || filePattern.Contains("*"))
{
string directory = Path.GetDirectoryName(filePattern);
if (string.IsNullOrEmpty(directory))
directory = Environment.CurrentDirectory;
else
directory = Path.GetFullPath(directory);
if (! Directory.Exists(directory))
{
logger.Log(LogSeverity.Error,
String.Format("Cannot find directory containing file pattern '{0}'.", filePattern));
return null;
}
var files = new List<FileInfo>();
string searchPattern = Path.GetFileName(filePattern);
foreach (string file in Directory.GetFiles(directory, searchPattern))
files.Add(new FileInfo(Path.Combine(directory, file)));
return files;
}
if (! File.Exists(filePattern))
{
logger.Log(LogSeverity.Error, String.Format("Cannot find file '{0}'.", filePattern));
return null;
}
return new[] { new FileInfo(Path.GetFullPath(filePattern)) };
}
private void DoInitialize(ITestRunner runner, ref bool canceled)
{
RunWithProgress(progressMonitor => runner.Initialize(testRunnerOptions,
logger, progressMonitor), ref canceled);
}
private Report DoExploreOrRun(ITestRunner runner, TestPackage testPackage, ref bool canceled)
{
Report report = null;
RunWithProgress(delegate(IProgressMonitor progressMonitor)
{
report = DoNotRun ? runner.Explore(testPackage, testExplorationOptions, progressMonitor) :
runner.Run(testPackage, testExplorationOptions, testExecutionOptions, progressMonitor);
}, ref canceled);
return report;
}
private void DoDispose(ITestRunner runner, ref bool canceled)
{
RunWithProgress(runner.Dispose, ref canceled);
}
private TestLauncherResult CreateResult(int resultCode, TestProject consolidatedTestProject)
{
Report report = new Report();
report.TestPackage = new TestPackageData(consolidatedTestProject.TestPackage);
var result = new TestLauncherResult(report);
result.SetResultCode(resultCode);
return result;
}
private void RunWithProgress(TaskWithProgress task, ref bool canceled)
{
try
{
progressMonitorProvider.Run(progressMonitor =>
{
try
{
bool wasCanceled;
lock (cancelationSyncRoot)
{
wasCanceled = isCanceled;
cancelableProgressMonitor = progressMonitor;
}
if (wasCanceled)
{
progressMonitor.Cancel();
}
else
{
task(progressMonitor);
}
}
finally
{
lock (cancelationSyncRoot)
cancelableProgressMonitor = null;
}
});
}
catch (OperationCanceledException)
{
canceled = true;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
internal static class IOInputs
{
// see: http://msdn.microsoft.com/en-us/library/aa365247.aspx
private static readonly char[] s_invalidFileNameChars = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
new char[] { '\"', '<', '>', '|', '\0', (Char)1, (Char)2, (Char)3, (Char)4, (Char)5, (Char)6, (Char)7, (Char)8, (Char)9, (Char)10, (Char)11, (Char)12, (Char)13, (Char)14, (Char)15, (Char)16, (Char)17, (Char)18, (Char)19, (Char)20, (Char)21, (Char)22, (Char)23, (Char)24, (Char)25, (Char)26, (Char)27, (Char)28, (Char)29, (Char)30, (Char)31, '*', '?' } :
new char[] { '\0' };
public static bool SupportsSettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } }
public static bool SupportsGettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } }
// Max path length (minus trailing \0). Unix values vary system to system; just using really long values here likely to be more than on the average system.
public static readonly int MaxPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 259 : 10000;
// Same as MaxPath on Unix
public static readonly int MaxLongPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MaxExtendedPath : MaxPath;
// Windows specific, this is the maximum length that can be passed to APIs taking directory names, such as Directory.CreateDirectory & Directory.Move.
// Does not include the trailing \0.
// We now do the appropriate wrapping to allow creating longer directories. Like MaxPath, this is a legacy restriction.
public static readonly int MaxDirectory = 247;
// Windows specific, this is the maximum length that can be passed using extended syntax. Does not include the trailing \0.
public static readonly int MaxExtendedPath = short.MaxValue - 1;
public const int MaxComponent = 255;
public const string ExtendedPrefix = @"\\?\";
public const string ExtendedUncPrefix = @"\\?\UNC\";
public static IEnumerable<string> GetValidPathComponentNames()
{
yield return Path.GetRandomFileName();
yield return "!@#$%^&";
yield return "\x65e5\x672c\x8a9e";
yield return "A";
yield return " A";
yield return " A";
yield return "FileName";
yield return "FileName.txt";
yield return " FileName";
yield return " FileName.txt";
yield return " FileName";
yield return " FileName.txt";
yield return "This is a valid component name";
yield return "This is a valid component name.txt";
yield return "V1.0.0.0000";
}
public static IEnumerable<string> GetControlWhiteSpace()
{
yield return "\t";
yield return "\t\t";
yield return "\t\t\t";
yield return "\n";
yield return "\n\n";
yield return "\n\n\n";
yield return "\t\n";
yield return "\t\n\t\n";
yield return "\n\t\n";
yield return "\n\t\n\t";
}
public static IEnumerable<string> GetSimpleWhiteSpace()
{
yield return " ";
yield return " ";
yield return " ";
yield return " ";
yield return " ";
}
public static IEnumerable<string> GetWhiteSpace()
{
return GetControlWhiteSpace().Concat(GetSimpleWhiteSpace());
}
public static IEnumerable<string> GetUncPathsWithoutShareName()
{
foreach (char slash in new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar })
{
string slashes = new string(slash, 2);
yield return slashes;
yield return slashes + " ";
yield return slashes + new string(slash, 5);
yield return slashes + "S";
yield return slashes + "S ";
yield return slashes + "LOCALHOST";
yield return slashes + "LOCALHOST " + slash;
yield return slashes + "LOCALHOST " + new string(slash, 2);
yield return slashes + "LOCALHOST" + slash + " ";
yield return slashes + "LOCALHOST" + slash + slash + " ";
}
}
public static IEnumerable<string> GetPathsWithReservedDeviceNames()
{
string root = Path.GetPathRoot(Directory.GetCurrentDirectory());
foreach (string deviceName in GetReservedDeviceNames())
{
yield return deviceName;
yield return Path.Combine(root, deviceName);
yield return Path.Combine(root, "Directory", deviceName);
yield return Path.Combine(new string(Path.DirectorySeparatorChar, 2), "LOCALHOST", deviceName);
}
}
public static IEnumerable<string> GetPathsWithAlternativeDataStreams()
{
yield return @"AA:";
yield return @"AAA:";
yield return @"AA:A";
yield return @"AAA:A";
yield return @"AA:AA";
yield return @"AAA:AA";
yield return @"AA:AAA";
yield return @"AAA:AAA";
yield return @"AA:FileName";
yield return @"AAA:FileName";
yield return @"AA:FileName.txt";
yield return @"AAA:FileName.txt";
yield return @"A:FileName.txt:";
yield return @"AA:FileName.txt:AA";
yield return @"AAA:FileName.txt:AAA";
yield return @"C:\:";
yield return @"C:\:FileName";
yield return @"C:\:FileName.txt";
yield return @"C:\fileName:";
yield return @"C:\fileName:FileName.txt";
yield return @"C:\fileName:FileName.txt:";
yield return @"C:\fileName:FileName.txt:AA";
yield return @"C:\fileName:FileName.txt:AAA";
yield return @"ftp://fileName:FileName.txt:AAA";
}
public static IEnumerable<string> GetPathsWithInvalidColons()
{
// Windows specific. We document that these return NotSupportedException.
yield return @":";
yield return @" :";
yield return @" :";
yield return @"C::";
yield return @"C::FileName";
yield return @"C::FileName.txt";
yield return @"C::FileName.txt:";
yield return @"C::FileName.txt::";
yield return @":f";
yield return @":filename";
yield return @"file:";
yield return @"file:file";
yield return @"http:";
yield return @"http:/";
yield return @"http://";
yield return @"http://www";
yield return @"http://www.microsoft.com";
yield return @"http://www.microsoft.com/index.html";
yield return @"http://server";
yield return @"http://server/";
yield return @"http://server/home";
yield return @"file://";
yield return @"file:///C|/My Documents/ALetter.html";
}
public static IEnumerable<string> GetPathsWithInvalidCharacters()
{
// NOTE: That I/O treats "file"/http" specially and throws ArgumentException.
// Otherwise, it treats all other urls as alternative data streams
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // alternate data streams, drive labels, etc.
{
yield return "\0";
yield return "middle\0path";
yield return "trailing\0";
// TODO: #6931 Add these back in some fashion
//yield return @"\\?\";
//yield return @"\\?\UNC\";
//yield return @"\\?\UNC\LOCALHOST";
}
else
{
yield return "\0";
yield return "middle\0path";
yield return "trailing\0";
}
foreach (char c in s_invalidFileNameChars)
{
yield return c.ToString();
}
}
public static IEnumerable<string> GetPathsWithComponentLongerThanMaxComponent()
{
// While paths themselves can be up to and including 32,000 characters, most volumes
// limit each component of the path to a total of 255 characters.
string component = new string('s', MaxComponent + 1);
yield return String.Format(@"C:\{0}", component);
yield return String.Format(@"C:\{0}\Filename.txt", component);
yield return String.Format(@"C:\{0}\Filename.txt\", component);
yield return String.Format(@"\\{0}\Share", component);
yield return String.Format(@"\\LOCALHOST\{0}", component);
yield return String.Format(@"\\LOCALHOST\{0}\FileName.txt", component);
yield return String.Format(@"\\LOCALHOST\Share\{0}", component);
}
public static IEnumerable<string> GetPathsLongerThanMaxDirectory(string rootPath)
{
yield return GetLongPath(rootPath, MaxDirectory + 1);
yield return GetLongPath(rootPath, MaxDirectory + 2);
yield return GetLongPath(rootPath, MaxDirectory + 3);
}
public static IEnumerable<string> GetPathsLongerThanMaxPath(string rootPath, bool useExtendedSyntax = false)
{
yield return GetLongPath(rootPath, MaxPath + 1, useExtendedSyntax);
yield return GetLongPath(rootPath, MaxPath + 2, useExtendedSyntax);
yield return GetLongPath(rootPath, MaxPath + 3, useExtendedSyntax);
}
public static IEnumerable<string> GetPathsLongerThanMaxLongPath(string rootPath, bool useExtendedSyntax = false)
{
yield return GetLongPath(rootPath, MaxExtendedPath + 1 - (useExtendedSyntax ? 0 : ExtendedPrefix.Length), useExtendedSyntax);
yield return GetLongPath(rootPath, MaxExtendedPath + 2 - (useExtendedSyntax ? 0 : ExtendedPrefix.Length), useExtendedSyntax);
}
private static string GetLongPath(string rootPath, int characterCount, bool extended = false)
{
return IOServices.GetPath(rootPath, characterCount, extended).FullPath;
}
public static IEnumerable<string> GetReservedDeviceNames()
{ // See: http://msdn.microsoft.com/en-us/library/aa365247.aspx
yield return "CON";
yield return "AUX";
yield return "NUL";
yield return "PRN";
yield return "COM1";
yield return "COM2";
yield return "COM3";
yield return "COM4";
yield return "COM5";
yield return "COM6";
yield return "COM7";
yield return "COM8";
yield return "COM9";
yield return "LPT1";
yield return "LPT2";
yield return "LPT3";
yield return "LPT4";
yield return "LPT5";
yield return "LPT6";
yield return "LPT7";
yield return "LPT8";
yield return "LPT9";
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Glass.Mapper.Configuration;
using Glass.Mapper.Configuration.Attributes;
using NSubstitute;
using NUnit.Framework;
namespace Glass.Mapper.Tests.Configuration.Attributes
{
[TestFixture]
public class AttributeConfigurationLoaderFixture
{
private StubAttributeConfigurationLoader _loader;
[SetUp]
public void Setup()
{
_loader = new StubAttributeConfigurationLoader();
}
#region Method - Create
[Test]
public void Load_LoadsTypesUsingAssemblyNameWithDllAtEnd_TypeReturnedWithTwoProperties()
{
//Assign
string assemblyName = "Glass.Mapper.Tests.dll";
_loader = new StubAttributeConfigurationLoader(assemblyName);
//Act
var results = _loader.Load();
//Assert
Assert.IsTrue(results.Any());
Assert.AreEqual(1, results.Count(x => x.Type == typeof(StubClassWithTypeAttributeAndProperties)));
var config = results.First(x => x.Type == typeof(StubClassWithTypeAttributeAndProperties));
Assert.AreEqual(2, config.Properties.Count());
}
[Test]
public void Load_LoadsTypesUsingAssemblyNameWithoutDllAtEnd_TypeReturnedWithTwoProperties()
{
//Assign
string assemblyName = "Glass.Mapper.Tests";
_loader = new StubAttributeConfigurationLoader(assemblyName);
//Act
var results = _loader.Load();
//Assert
Assert.IsTrue(results.Any());
Assert.AreEqual(1, results.Count(x => x.Type == typeof(StubClassWithTypeAttributeAndProperties)));
var config = results.First(x => x.Type == typeof(StubClassWithTypeAttributeAndProperties));
Assert.AreEqual(2, config.Properties.Count());
}
[Test]
public void Load_AssemblyDoesntExist_ThrowsException()
{
//Assign
string assemblyName = "DoesNotExist";
_loader = new StubAttributeConfigurationLoader(assemblyName);
//Act
Assert.Throws<ConfigurationException>(() =>
{
var results = _loader.Load();
});
//Exception
}
#endregion
#region Method - LoadFromAssembly
[Test]
public void LoadFromAssembly_TypesDefinedInThisAssembly_LoadsAtLeastOneType()
{
//Assign
var assembly = Assembly.GetExecutingAssembly();
//Act
var results = _loader.LoadFromAssembly(assembly);
//Assert
Assert.IsTrue(results.Any());
Assert.AreEqual(1, results.Count(x=>x.Type == typeof(StubClassWithTypeAttribute)));
}
[Test]
public void LoadFromAssembly_TypesDefinedInThisAssemblyWithTwoProperties_LoadsAtLeastOneTypeWithTwoProperties()
{
//Assign
var assembly = Assembly.GetExecutingAssembly();
//Act
var results = _loader.LoadFromAssembly(assembly);
//Assert
Assert.IsTrue(results.Any());
Assert.AreEqual(1, results.Count(x => x.Type == typeof(StubClassWithTypeAttributeAndProperties)));
var config = results.First(x => x.Type == typeof (StubClassWithTypeAttributeAndProperties));
Assert.AreEqual(2, config.Properties.Count());
}
#endregion
#region Stubs
public class StubTypeConfiguration : AbstractTypeConfiguration
{
}
public class StubPropertyConfiguration : AbstractPropertyConfiguration
{
protected override AbstractPropertyConfiguration CreateCopy()
{
throw new NotImplementedException();
}
}
public class StubAttributeConfigurationLoader : AttributeConfigurationLoader
{
public StubAttributeConfigurationLoader(params string [] assemblies):base(assemblies)
{
}
public IEnumerable<AbstractTypeConfiguration> LoadFromAssembly(Assembly assembly)
{
return base.LoadFromAssembly(assembly);
}
}
public class StubAbstractTypeAttribute : AbstractTypeAttribute
{
public override AbstractTypeConfiguration Configure(Type type)
{
var config = new StubTypeConfiguration();
base.Configure(type, config);
return config;
}
}
public class StubAbstractPropertyAttribute : AbstractPropertyAttribute
{
public override AbstractPropertyConfiguration Configure(PropertyInfo propertyInfo)
{
var config = new StubPropertyConfiguration();
base.Configure(propertyInfo, config);
return config;
}
}
[StubAbstractType]
public class StubClassWithTypeAttribute
{
}
[StubAbstractType]
public class StubClassWithTypeAttributeAndProperties
{
[StubAbstractProperty]
public string PropertyWithAttribute1 { get; set; }
[StubAbstractProperty]
public string PropertyWithAttribute2 { get; set; }
}
public class StubClassWithProperties
{
[StubAbstractProperty]
public string PropertyWithAttribute { get; set; }
public string PropertyWithoutAttribute { get; set; }
}
public class StubSubClassWithProperties: StubClassWithProperties
{
}
public interface StubInterfaceWithProperties
{
[StubAbstractProperty]
string PropertyWithAttribute { get; set; }
}
public interface StubSubInterfaceWithProperties : StubInterfaceWithProperties
{
}
public class StubClassFromInterface : StubSubInterfaceWithProperties
{
public string PropertyWithAttribute
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}
public class StubClassFromTwoInterfaces : StubInferfaceOne, StubInferfaceTwo
{
public string PropertyWithAttribute { get; set; }
}
public interface StubInferfaceOne
{
[StubAbstractProperty]
string PropertyWithAttribute { get; set; }
}
public interface StubInferfaceTwo
{
string PropertyWithAttribute { get; set; }
}
#endregion
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
namespace System.Abstract.Internal
{
/// <summary>
/// ServiceManagerBase
/// </summary>
/// <typeparam name="TService">The type of the service interface.</typeparam>
/// <typeparam name="TServiceManager">The type of the service.</typeparam>
/// <typeparam name="TServiceManagerLogger">The type of the service manager logger.</typeparam>
public abstract partial class ServiceManagerBase<TService, TServiceManager, TServiceManagerLogger>
where TService : class
where TServiceManager : class, new()
{
static readonly ConditionalWeakTable<Lazy<TService>, ISetupDescriptor> _setupDescriptors = new ConditionalWeakTable<Lazy<TService>, ISetupDescriptor>();
static readonly object _lock = new object();
static ServiceRegistration _registration;
// Force "precise" initialization
static ServiceManagerBase() =>
new TServiceManager();
/// <summary>
/// Gets or sets the lazy.
/// </summary>
/// <value>The lazy.</value>
public static Lazy<TService> Lazy { get; protected set; }
/// <summary>
/// Makes the by provider.
/// </summary>
/// <param name="provider">The provider.</param>
/// <param name="setupDescriptor">The setup descriptor.</param>
/// <returns>Lazy<TService>.</returns>
/// <exception cref="ArgumentNullException">provider</exception>
/// <exception cref="System.ArgumentNullException">provider</exception>
[DebuggerStepThrough]
public static Lazy<TService> MakeByProvider(Func<TService> provider, ISetupDescriptor setupDescriptor = null)
{
if (provider == null)
throw new ArgumentNullException(nameof(provider));
var lazy = new Lazy<TService>(provider, LazyThreadSafetyMode.PublicationOnly);
GetSetupDescriptor(lazy, setupDescriptor);
return lazy;
}
/// <summary>
/// Gets or sets the logger.
/// </summary>
/// <value>The logger.</value>
public static TServiceManagerLogger Logger { get; set; }
/// <summary>
/// Gets or sets the registration.
/// </summary>
/// <value>The registration.</value>
public static ServiceRegistration Registration
{
get => _registration ?? throw new InvalidOperationException("Registration Failed");
set => _registration = value;
}
/// <summary>
/// Sets the provider.
/// </summary>
/// <param name="provider">The provider.</param>
/// <param name="setupDescriptor">The setup descriptor.</param>
/// <returns>Lazy<TService>.</returns>
public static Lazy<TService> SetProvider(Func<TService> provider, ISetupDescriptor setupDescriptor = null) =>
Lazy = MakeByProvider(provider, setupDescriptor);
/// <summary>
/// Gets the current.
/// </summary>
/// <value>The current.</value>
/// <exception cref="System.InvalidOperationException">AbstractService undefined. Did you forget to SetProvider?</exception>
/// <exception cref="System.Exception"></exception>
public static TService Current
{
get
{
if (Lazy.IsValueCreated)
return Lazy.Value;
if (InflightValue != null)
return InflightValue;
if (Lazy == null)
throw new InvalidOperationException("AbstractService undefined. Did you forget to SetProvider?");
try { return Lazy.Value; }
catch (ReflectionTypeLoadException e)
{
#if NET35
var b = new StringBuilder();
foreach (var ex in e.LoaderExceptions)
b.AppendLine(ex.Message);
throw new Exception(b.ToString(), e);
#else
throw new AggregateException(e.LoaderExceptions);
#endif
}
catch (Exception) { throw; }
}
}
#region Setup
/// <summary>
/// IRegisterWithLocator
/// </summary>
public interface IRegisterWithLocator
{
/// <summary>
/// Gets the register with locator.
/// </summary>
/// <value>The register with locator.</value>
Action<IServiceLocator, string> RegisterWithLocator { get; }
}
/// <summary>
/// ServiceRegistration
/// </summary>
public class ServiceRegistration
{
Func<TService> _defaultServiceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="ServiceRegistration" /> class.
/// </summary>
public ServiceRegistration()
{
OnSetup = (service, descriptor) =>
{
if (descriptor != null)
foreach (var action in descriptor.Actions)
action(service);
return service;
};
OnChange = (service, descriptor) =>
{
if (descriptor != null)
foreach (var action in descriptor.Actions)
action(service);
};
RegisterWithLocator = (service, locator, name) =>
{
//RegisterInstance(service, locator, name);
if (service is IRegisterWithLocator registerWithLocator)
registerWithLocator.RegisterWithLocator(locator, name);
};
}
/// <summary>
/// Gets or sets the DefaultServiceProvider.
/// </summary>
/// <value>The DefaultServiceProvider.</value>
public Func<TService> DefaultServiceProvider
{
get => _defaultServiceProvider;
set
{
_defaultServiceProvider = value;
// set default provider
if (Lazy == null && value != null)
SetProvider(value);
}
}
/// <summary>
/// Gets or sets the on setup.
/// </summary>
/// <value>The on setup.</value>
public Func<TService, ISetupDescriptor, TService> OnSetup { get; set; }
/// <summary>
/// Gets or sets the on change.
/// </summary>
/// <value>The on change.</value>
public Action<TService, ISetupDescriptor> OnChange { get; set; }
/// <summary>
/// Gets or sets the on service registrar.
/// </summary>
/// <value>The on service registrar.</value>
public Action<TService, IServiceLocator, string> RegisterWithLocator { get; set; }
}
#endregion
#region IServiceSetup
/// <summary>
/// ApplySetupDescriptors
/// </summary>
static TService ApplySetupDescriptor(Lazy<TService> service, TService newInstance)
{
if (service == null)
throw new ArgumentNullException(nameof(service));
if (newInstance == null)
throw new NullReferenceException(nameof(newInstance));
var onSetup = Registration.OnSetup;
if (onSetup == null)
return newInstance;
// find descriptor
if (_setupDescriptors.TryGetValue(service, out var setupDescriptor))
_setupDescriptors.Remove(service);
return onSetup(newInstance, setupDescriptor);
}
/// <summary>
/// ApplyChangeDescriptor
/// </summary>
static void ApplyChangeDescriptor(Lazy<TService> service, ISetupDescriptor changeDescriptor)
{
if (service == null)
throw new ArgumentNullException(nameof(service));
if (!service.IsValueCreated)
throw new InvalidOperationException("Service value has not been created yet.");
Registration.OnChange?.Invoke(service.Value, changeDescriptor);
}
/// <summary>
/// InflightValue
/// </summary>
protected static TService InflightValue;
/// <summary>
/// GetSetupDescriptor
/// </summary>
[DebuggerStepThrough]
public static ISetupDescriptor GetSetupDescriptor(Lazy<TService> service, ISetupDescriptor firstDescriptor = null)
{
if (service == null)
throw new ArgumentNullException(nameof(service));
if (service.IsValueCreated)
return new SetupDescriptor(Registration, d => ApplyChangeDescriptor(service, d));
if (_setupDescriptors.TryGetValue(service, out var descriptor))
{
if (firstDescriptor == null)
return descriptor;
throw new InvalidOperationException(string.Format(Local.RedefineSetupDescriptorA, service.ToString()));
}
lock (_lock)
if (!_setupDescriptors.TryGetValue(service, out descriptor))
{
descriptor = firstDescriptor ?? new SetupDescriptor(Registration, null);
_setupDescriptors.Add(service, descriptor);
service.HookValueFactory(valueFactory => ApplySetupDescriptor(service, InflightValue = valueFactory()));
}
return descriptor;
}
/// <summary>
/// RegisterInstance
/// </summary>
public static void RegisterInstance<T>(T service, string name = null, IServiceLocator locator = null)
where T : class
{
if (service == null)
throw new ArgumentNullException(nameof(service));
if (name == null) locator.Registrar.RegisterInstance(service);
else locator.Registrar.RegisterInstance(service, name);
}
/// <summary>
/// RegisterInstance
/// </summary>
public static void RegisterInstance(object service, Type serviceType, string name = null, IServiceLocator locator = null)
{
if (service == null)
throw new ArgumentNullException(nameof(service));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
if (name == null) locator.Registrar.RegisterInstance(serviceType, service);
else locator.Registrar.RegisterInstance(serviceType, service, name);
}
/// <summary>
/// ISetupDescriptor
/// </summary>
public interface ISetupDescriptor
{
/// <summary>
/// Does the specified action.
/// </summary>
/// <param name="action">The action.</param>
void Do(Action<TService> action);
/// <summary>
/// Gets the actions.
/// </summary>
/// <value>The actions.</value>
IEnumerable<Action<TService>> Actions { get; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="name">The name.</param>
/// <param name="locator">The locator.</param>
[DebuggerStepThrough]
void RegisterWithServiceLocator<T>(Lazy<TService> service, string name = null, IServiceLocator locator = null)
where T : class, TService;
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="name">The name.</param>
/// <param name="locator">The locator.</param>
[DebuggerStepThrough]
void RegisterWithServiceLocator<T>(Lazy<TService> service, string name = null, Lazy<IServiceLocator> locator = null)
where T : class, TService;
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
/// <param name="locator">The locator.</param>
[DebuggerStepThrough]
void RegisterWithServiceLocator(Lazy<TService> service, Type serviceType, string name = null, IServiceLocator locator = null);
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
/// <param name="locator">The locator.</param>
[DebuggerStepThrough]
void RegisterWithServiceLocator(Lazy<TService> service, Type serviceType, string name = null, Lazy<IServiceLocator> locator = null);
}
/// <summary>
/// SetupDescriptor
/// </summary>
protected class SetupDescriptor : ISetupDescriptor
{
List<Action<TService>> _actions = new List<Action<TService>>();
ServiceRegistration _registration;
Action<ISetupDescriptor> _postAction;
/// <summary>
/// Initializes a new instance of the <see cref="SetupDescriptor" /> class.
/// </summary>
/// <param name="registration">The registration.</param>
/// <param name="postAction">The post action.</param>
/// <exception cref="ArgumentNullException">registration - Please ensure EnsureRegistration() has been called previously.</exception>
/// <exception cref="System.ArgumentNullException">registration;Please ensure EnsureRegistration() has been called previously.</exception>
public SetupDescriptor(ServiceRegistration registration, Action<ISetupDescriptor> postAction)
{
_registration = registration ?? throw new ArgumentNullException(nameof(registration), "Please ensure EnsureRegistration() has been called previously.");
_postAction = postAction;
}
[DebuggerStepThrough]
void ISetupDescriptor.Do(Action<TService> action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
_actions.Add(action);
_postAction?.Invoke(this);
}
IEnumerable<Action<TService>> ISetupDescriptor.Actions
{
[DebuggerStepThrough]
get => _actions;
}
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="name">The name.</param>
/// <param name="locator">The locator.</param>
/// <exception cref="ArgumentNullException">service</exception>
/// <exception cref="System.ArgumentNullException">service</exception>
[DebuggerStepThrough]
void ISetupDescriptor.RegisterWithServiceLocator<T>(Lazy<TService> service, string name, IServiceLocator locator)
{
if (service == null)
throw new ArgumentNullException(nameof(service));
RegisterInstance((T)service.Value, name, locator);
}
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
/// <param name="locator">The locator.</param>
/// <exception cref="ArgumentNullException">service
/// or
/// serviceType</exception>
/// <exception cref="System.ArgumentNullException">service
/// or
/// serviceType</exception>
[DebuggerStepThrough]
void ISetupDescriptor.RegisterWithServiceLocator(Lazy<TService> service, Type serviceType, string name, IServiceLocator locator)
{
if (service == null)
throw new ArgumentNullException(nameof(service));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
RegisterInstance(service.Value, serviceType, name, locator);
}
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="name">The name.</param>
/// <param name="locator">The locator.</param>
/// <exception cref="ArgumentNullException">service</exception>
/// <exception cref="System.ArgumentNullException">service</exception>
[DebuggerStepThrough]
void ISetupDescriptor.RegisterWithServiceLocator<T>(Lazy<TService> service, string name, Lazy<IServiceLocator> locator)
{
if (service == null)
throw new ArgumentNullException(nameof(service));
RegisterInstance((T)service.Value, name, locator.Value);
}
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
/// <param name="locator">The locator.</param>
/// <exception cref="ArgumentNullException">service
/// or
/// serviceType</exception>
/// <exception cref="System.ArgumentNullException">service
/// or
/// serviceType</exception>
[DebuggerStepThrough]
void ISetupDescriptor.RegisterWithServiceLocator(Lazy<TService> service, Type serviceType, string name, Lazy<IServiceLocator> locator)
{
if (service == null)
throw new ArgumentNullException(nameof(service));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
RegisterInstance(service.Value, serviceType, name, locator.Value);
}
}
#endregion
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class SnapshotMarkerDecoder
{
public const ushort BLOCK_LENGTH = 40;
public const ushort TEMPLATE_ID = 100;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private SnapshotMarkerDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public SnapshotMarkerDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public SnapshotMarkerDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int TypeIdId()
{
return 1;
}
public static int TypeIdSinceVersion()
{
return 0;
}
public static int TypeIdEncodingOffset()
{
return 0;
}
public static int TypeIdEncodingLength()
{
return 8;
}
public static string TypeIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long TypeIdNullValue()
{
return -9223372036854775808L;
}
public static long TypeIdMinValue()
{
return -9223372036854775807L;
}
public static long TypeIdMaxValue()
{
return 9223372036854775807L;
}
public long TypeId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int LogPositionId()
{
return 2;
}
public static int LogPositionSinceVersion()
{
return 0;
}
public static int LogPositionEncodingOffset()
{
return 8;
}
public static int LogPositionEncodingLength()
{
return 8;
}
public static string LogPositionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LogPositionNullValue()
{
return -9223372036854775808L;
}
public static long LogPositionMinValue()
{
return -9223372036854775807L;
}
public static long LogPositionMaxValue()
{
return 9223372036854775807L;
}
public long LogPosition()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int LeadershipTermIdId()
{
return 3;
}
public static int LeadershipTermIdSinceVersion()
{
return 0;
}
public static int LeadershipTermIdEncodingOffset()
{
return 16;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public long LeadershipTermId()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public static int IndexId()
{
return 4;
}
public static int IndexSinceVersion()
{
return 0;
}
public static int IndexEncodingOffset()
{
return 24;
}
public static int IndexEncodingLength()
{
return 4;
}
public static string IndexMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int IndexNullValue()
{
return -2147483648;
}
public static int IndexMinValue()
{
return -2147483647;
}
public static int IndexMaxValue()
{
return 2147483647;
}
public int Index()
{
return _buffer.GetInt(_offset + 24, ByteOrder.LittleEndian);
}
public static int MarkId()
{
return 5;
}
public static int MarkSinceVersion()
{
return 0;
}
public static int MarkEncodingOffset()
{
return 28;
}
public static int MarkEncodingLength()
{
return 4;
}
public static string MarkMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public SnapshotMark Mark()
{
return (SnapshotMark)_buffer.GetInt(_offset + 28, ByteOrder.LittleEndian);
}
public static int TimeUnitId()
{
return 6;
}
public static int TimeUnitSinceVersion()
{
return 4;
}
public static int TimeUnitEncodingOffset()
{
return 32;
}
public static int TimeUnitEncodingLength()
{
return 4;
}
public static string TimeUnitMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "optional";
}
return "";
}
public ClusterTimeUnit TimeUnit()
{
if (_actingVersion < 4) return ClusterTimeUnit.NULL_VALUE;
return (ClusterTimeUnit)_buffer.GetInt(_offset + 32, ByteOrder.LittleEndian);
}
public static int AppVersionId()
{
return 7;
}
public static int AppVersionSinceVersion()
{
return 4;
}
public static int AppVersionEncodingOffset()
{
return 36;
}
public static int AppVersionEncodingLength()
{
return 4;
}
public static string AppVersionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "optional";
}
return "";
}
public static int AppVersionNullValue()
{
return 0;
}
public static int AppVersionMinValue()
{
return 1;
}
public static int AppVersionMaxValue()
{
return 16777215;
}
public int AppVersion()
{
return _buffer.GetInt(_offset + 36, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[SnapshotMarker](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='typeId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("TypeId=");
builder.Append(TypeId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='logPosition', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LogPosition=");
builder.Append(LogPosition());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LeadershipTermId=");
builder.Append(LeadershipTermId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='index', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Index=");
builder.Append(Index());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='mark', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=28, componentTokenCount=7, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=BEGIN_ENUM, name='SnapshotMark', referencedName='null', description='Mark within a snapshot.', id=-1, version=0, deprecated=0, encodedLength=4, offset=28, componentTokenCount=5, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("Mark=");
builder.Append(Mark());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='timeUnit', referencedName='null', description='null', id=6, version=4, deprecated=0, encodedLength=0, offset=32, componentTokenCount=7, encoding=Encoding{presence=OPTIONAL, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=BEGIN_ENUM, name='ClusterTimeUnit', referencedName='null', description='Type the time unit used for timestamps.', id=-1, version=4, deprecated=0, encodedLength=4, offset=32, componentTokenCount=5, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("TimeUnit=");
builder.Append(TimeUnit());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='appVersion', referencedName='null', description='null', id=7, version=4, deprecated=0, encodedLength=0, offset=36, componentTokenCount=3, encoding=Encoding{presence=OPTIONAL, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='version_t', referencedName='null', description='Protocol or application suite version.', id=-1, version=0, deprecated=0, encodedLength=4, offset=36, componentTokenCount=1, encoding=Encoding{presence=OPTIONAL, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=1, maxValue=16777215, nullValue=0, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("AppVersion=");
builder.Append(AppVersion());
Limit(originalLimit);
return builder;
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using Axiom.Collections;
using Axiom.Graphics;
using Axiom.MathLib;
namespace Axiom.Core {
#region Base Query Implementation
/// <summary>
/// A class for performing queries on a scene.
/// </summary>
/// <remarks>
/// This is an abstract class for performing a query on a scene, i.e. to retrieve
/// a list of objects and/or world geometry sections which are potentially intersecting a
/// given region. Note the use of the word 'potentially': the results of a scene query
/// are generated based on bounding volumes, and as such are not correct at a triangle
/// level; the user of the SceneQuery is expected to filter the results further if
/// greater accuracy is required.
/// <p/>
/// Different SceneManagers will implement these queries in different ways to
/// exploit their particular scene organization, and thus will provide their own
/// concrete subclasses. In fact, these subclasses will be derived from subclasses
/// of this class rather than directly because there will be region-type classes
/// in between.
/// <p/>
/// These queries could have just been implemented as methods on the SceneManager,
/// however, they are wrapped up as objects to allow 'compilation' of queries
/// if deemed appropriate by the implementation; i.e. each concrete subclass may
/// precalculate information (such as fixed scene partitions involved in the query)
/// to speed up the repeated use of the query.
/// <p/>
/// You should never try to create a SceneQuery object yourself, they should be created
/// using the SceneManager interfaces for the type of query required, e.g.
/// SceneManager.CreateRaySceneQuery.
/// </remarks>
public abstract class SceneQuery {
#region Fields
/// <summary>
/// Reference to the SceneManager that this query was created by.
/// </summary>
protected SceneManager creator;
/// <summary>
/// User definable query bit mask which can be used to filter the results of a query.
/// </summary>
protected ulong queryMask;
/// <summary>
/// A flag enum which holds the world fragment types supported by this query.
/// </summary>
protected WorldFragmentType worldFragmentTypes;
#endregion Fields
#region Constructors
/// <summary>
/// Internal constructor.
/// </summary>
/// <param name="creator">Reference to the scene manager who created this query.</param>
internal SceneQuery(SceneManager creator) {
this.creator = creator;
// default to no world fragments queried
AddWorldFragmentType(WorldFragmentType.None);
}
#endregion Constructor
#region Methods
/// <summary>
/// Used to add a supported world fragment type to this query.
/// </summary>
public void AddWorldFragmentType(WorldFragmentType fragmentType) {
worldFragmentTypes |= fragmentType;
}
#endregion Methods
#region Properties
/// <summary>
/// Sets the mask for results of this query.
/// </summary>
/// <remarks>
/// This property allows you to set a 'mask' to limit the results of this
/// query to certain types of result. The actual meaning of this value is
/// up to the application; basically SceneObject instances will only be returned
/// from this query if a bitwise AND operation between this mask value and the
/// SceneObject.QueryFlags value is non-zero. The application will
/// have to decide what each of the bits means.
/// </remarks>
public ulong QueryMask {
get {
return queryMask;
}
set {
queryMask = value;
}
}
#endregion
#region Nested Structs
/// <summary>
/// Represents part of the world geometry that is a result of a <see cref="SceneQuery"/>.
/// </summary>
/// <remarks>
/// Since world geometry is normally vast and sprawling, we need a way of
/// retrieving parts of it based on a query. That is what this struct is for;
/// note there are potentially as many data structures for world geometry as there
/// are SceneManagers, however this structure includes a few common abstractions as
/// well as a more general format.
/// <p/>
/// The type of world fragment that is returned from a query depends on the
/// SceneManager, and the fragment types are supported on the query.
/// </remarks>
public class WorldFragment {
/// <summary>
/// The type of this world fragment.
/// </summary>
public WorldFragmentType FragmentType;
/// <summary>
/// Single intersection point, only applicable for <see cref="WorldFragmentType.SingleIntersection"/>.
/// </summary>
public Vector3 SingleIntersection;
/// <summary>
/// Planes bounding a convex region, only applicable for <see cref="WorldFragmentType.PlaneBoundedRegion"/>.
/// </summary>
public List<Plane> Planes;
/// <summary>
/// General render operation structure. Fallback if nothing else is available.
/// </summary>
public RenderOperation RenderOp;
}
#endregion Nested Structs
}
/// <summary>
/// Abstract class defining a query which returns single results from within a region.
/// </summary>
/// <remarks>
/// This class is simply a generalization of the subtypes of query that return
/// a set of individual results in a region. See the <see cref="SceneQuery"/> class for
/// abstract information, and subclasses for the detail of each query type.
/// </remarks>
public abstract class RegionSceneQuery : SceneQuery, ISceneQueryListener {
#region Fields
/// <summary>
/// List of results from the last non-listener query.
/// </summary>
protected SceneQueryResult lastResult = new SceneQueryResult();
#endregion Fields
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="creator">SceneManager who created this query.</param>
internal RegionSceneQuery(SceneManager creator) : base(creator) {}
#endregion Constructor
#region Methods
/// <summary>
/// Clears out any cached results from the last query.
/// </summary>
public virtual void ClearResults() {
lastResult.objects.Clear();
lastResult.worldFragments.Clear();
}
/// <summary>
/// Executes the query, returning the results back in one list.
/// </summary>
/// <remarks>
/// This method executes the scene query as configured, gathers the results
/// into one structure and returns a reference to that structure. These
/// results will also persist in this query object until the next query is
/// executed, or <see cref="ClearResults"/> is called. An more lightweight version of
/// this method that returns results through a listener is also available.
/// </remarks>
/// <returns></returns>
public virtual SceneQueryResult Execute() {
ClearResults();
// invoke callback method with ourself as the listener
Execute(this);
return lastResult;
}
/// <summary>
/// Executes the query and returns each match through a listener interface.
/// </summary>
/// <remarks>
/// Note that this method does not store the results of the query internally
/// so does not update the 'last result' value. This means that this version of
/// execute is more lightweight and therefore more efficient than the version
/// which returns the results as a collection.
/// </remarks>
/// <param name="listener"></param>
public abstract void Execute(ISceneQueryListener listener);
#endregion Methods
#region ISceneQueryListener Members
/// <summary>
/// Self-callback in order to deal with execute which returns collection.
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public bool OnQueryResult(MovableObject sceneObject) {
lastResult.objects.Add(sceneObject);
// continue
return true;
}
/// <summary>
/// Self-callback in order to deal with execute which returns collection.
/// </summary>
/// <param name="fragment"></param>
/// <returns></returns>
public bool OnQueryResult(Axiom.Core.SceneQuery.WorldFragment fragment) {
lastResult.worldFragments.Add(fragment);
// continue
return true;
}
#endregion
}
/// <summary>
/// Holds the results of a single scene query.
/// </summary>
public class SceneQueryResult {
/// <summary>
/// List of scene objects in the query (entities, particle systems etc).
/// </summary>
public MovableObjectCollection objects = new MovableObjectCollection();
/// <summary>
/// List of world fragments.
/// </summary>
public ArrayList worldFragments = new ArrayList();
}
/// <summary>
/// This optional class allows you to receive per-result callbacks from
/// SceneQuery executions instead of a single set of consolidated results.
/// </summary>
public interface ISceneQueryListener {
/// <summary>
/// Called when a <see cref="SceneObject"/> is returned by a query.
/// </summary>
/// <remarks>
/// The implementor should return 'true' to continue returning objects,
/// or 'false' to abandon any further results from this query.
/// </remarks>
/// <param name="sceneObject">Object found by the query.</param>
/// <returns></returns>
bool OnQueryResult(MovableObject sceneObject);
/// <summary>
/// Called when a <see cref="SceneQuery.WorldFragment"/> is returned by a query.
/// </summary>
/// <param name="fragment">Fragment found by the query.</param>
/// <returns></returns>
bool OnQueryResult(SceneQuery.WorldFragment fragment);
}
#endregion Base Query Implementation
#region RaySceneQuery Implementation
/// <summary>
/// Specializes the SceneQuery class for querying for objects along a ray.
/// </summary>
public abstract class RaySceneQuery : SceneQuery, IRaySceneQueryListener {
#region Fields
/// <summary>
/// Reference to a ray to use for this query.
/// </summary>
protected Ray ray;
/// <summary>
/// If true, results returned in the list
/// </summary>
protected bool sortByDistance;
/// <summary>
/// Maximum results to return when executing the query.
/// </summary>
protected int maxResults;
/// <summary>
/// List of query results from the last execution of this query.
/// </summary>
protected List<RaySceneQueryResultEntry> lastResults = new List<RaySceneQueryResultEntry>();
#endregion Fields
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
/// <param name="creator">Scene manager who created this query.</param>
internal RaySceneQuery(SceneManager creator) : base(creator) {}
#endregion Constructor
#region Properties
/// <summary>
/// Gets/Sets the Ray being used for this query.
/// </summary>
public Ray Ray {
get {
return ray;
}
set {
ray = value;
}
}
/// <summary>
/// Gets/Sets whether this queries results are sorted by distance.
/// </summary>
/// <remarks>
/// Often you want to know what was the first object a ray intersected with, and this
/// method allows you to ask the query to sort the results so that the nearest results
/// are listed first.
/// <p/>
/// Note that because the query returns results based on bounding volumes, the ray may not
/// actually intersect the detail of the objects returned from the query, just their
/// bounding volumes. For this reason the caller is advised to use more detailed
/// intersection tests on the results if a more accurate result is required; we use
/// bounds checking in order to give the most speedy results since not all applications
/// need extreme accuracy.
/// </remarks>
public bool SortByDistance {
get {
return sortByDistance;
}
set {
sortByDistance = value;
}
}
/// <summary>
/// Gets/Sets the maximum number of results to return from this query when
/// sorting is enabled.
/// </summary>
/// <remarks>
/// If sorting by distance is not enabled, then this value has no affect.
/// </remarks>
public int MaxResults {
get {
return maxResults;
}
set {
maxResults = value;
// size the arraylist to hold the maximum results
lastResults.Capacity = maxResults;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Clears out any cached results from the last query.
/// </summary>
public virtual void ClearResults() {
lastResults.Clear();
}
/// <summary>
/// Executes the query, returning the results back in one list.
/// </summary>
/// <remarks>
/// This method executes the scene query as configured, gathers the results
/// into one structure and returns a reference to that structure. These
/// results will also persist in this query object until the next query is
/// executed, or <see cref="ClearResults"/>. A more lightweight version of
/// this method that returns results through a listener is also available.
/// </remarks>
/// <returns></returns>
public virtual List<RaySceneQueryResultEntry> Execute() {
ClearResults();
// execute the callback version using ourselves as the listener
Execute(this);
if(sortByDistance) {
lastResults.Sort();
if(maxResults != 0 && lastResults.Count > maxResults) {
// remove the results greater than the desired amount
lastResults.RemoveRange(maxResults, lastResults.Count - maxResults);
}
}
return lastResults;
}
/// <summary>
/// Executes the query and returns each match through a listener interface.
/// </summary>
/// <remarks>
/// Note that this method does not store the results of the query internally
/// so does not update the 'last result' value. This means that this version of
/// execute is more lightweight and therefore more efficient than the version
/// which returns the results as a collection.
/// </remarks>
/// <param name="listener">Listener object to handle the result callbacks.</param>
public abstract void Execute(IRaySceneQueryListener listener);
#endregion Methods
#region IRaySceneQueryListener Members
public bool OnQueryResult(MovableObject sceneObject, float distance) {
// create an entry and add it to the cached result list
RaySceneQueryResultEntry entry = new RaySceneQueryResultEntry();
entry.Distance = distance;
entry.SceneObject = sceneObject;
entry.worldFragment = null;
lastResults.Add(entry);
// continue gathering results
return true;
}
bool Axiom.Core.IRaySceneQueryListener.OnQueryResult(SceneQuery.WorldFragment fragment, float distance) {
// create an entry and add it to the cached result list
RaySceneQueryResultEntry entry = new RaySceneQueryResultEntry();
entry.Distance = distance;
entry.SceneObject = null;
entry.worldFragment = fragment;
lastResults.Add(entry);
// continue gathering results
return true;
}
#endregion
}
/// <summary>
/// Alternative listener interface for dealing with <see cref="RaySceneQuery"/>.
/// </summary>
public interface IRaySceneQueryListener {
/// <summary>
/// Called when a scene objects intersect the ray.
/// </summary>
/// <param name="sceneObject">Reference to the object hit by the ray.</param>
/// <param name="distance">Distance from the origin of the ray where the intersection took place.</param>
/// <returns>Should return false to abandon returning additional results, or true to continue.</returns>
bool OnQueryResult(MovableObject sceneObject, float distance);
/// <summary>
/// Called when a world fragment is intersected by the ray.
/// </summary>
/// <param name="fragment">World fragment hit by the ray.</param>
/// <param name="distance">Distance from the origin of the ray where the intersection took place.</param>
/// <returns>Should return false to abandon returning additional results, or true to continue.</returns>
bool OnQueryResult(SceneQuery.WorldFragment fragment, float distance);
}
/// <summary>
/// This struct allows a single comparison of result data no matter what the type.
/// </summary>
public class RaySceneQueryResultEntry : IComparable {
/// <summary>
/// Distance along the ray.
/// </summary>
public float Distance;
/// <summary>
/// The object, or null if this is not a scene object result.
/// </summary>
public MovableObject SceneObject;
/// <summary>
/// The world fragment, or null if this is not a fragment result.
/// </summary>
public SceneQuery.WorldFragment worldFragment;
#region IComparable Members
/// <summary>
/// Implemented to allow sorting of results based on distance.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int CompareTo(object obj) {
RaySceneQueryResultEntry entry = obj as RaySceneQueryResultEntry;
if(Distance < entry.Distance) {
// this result is less than
return -1;
}
else if(Distance > entry.Distance) {
// this result is greater than
return 1;
}
// they are equal
return 0;
}
#endregion
}
#endregion RaySceneQuery Implementation
#region AxisAlignedBoxRegionSceneQuery Implementation
/// <summary>
/// Specializes the SceneQuery class for querying items within an AxisAlignedBox.
/// </summary>
public abstract class AxisAlignedBoxRegionSceneQuery : RegionSceneQuery {
#region Fields
/// <summary>
/// Sphere to query items within.
/// </summary>
protected AxisAlignedBox box;
#endregion Fields
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="creator">SceneManager who created this query.</param>
internal AxisAlignedBoxRegionSceneQuery(SceneManager creator) : base(creator) {}
#endregion Constructor
#region Properties
/// <summary>
/// Gets/Sets the sphere to use for the query.
/// </summary>
public AxisAlignedBox Box {
get {
return box;
}
set {
box = value;
}
}
#endregion Properties
}
#endregion AxisAlignedBoxRegionSceneQuery Implementation
#region SphereRegionSceneQuery Implementation
/// <summary>
/// Specializes the SceneQuery class for querying items within a sphere.
/// </summary>
public abstract class SphereRegionSceneQuery : RegionSceneQuery {
#region Fields
/// <summary>
/// Sphere to query items within.
/// </summary>
protected Sphere sphere;
#endregion Fields
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="creator">SceneManager who created this query.</param>
internal SphereRegionSceneQuery(SceneManager creator) : base(creator) {}
#endregion Constructor
#region Properties
/// <summary>
/// Gets/Sets the sphere to use for the query.
/// </summary>
public Sphere Sphere {
get {
return sphere;
}
set {
sphere = value;
}
}
#endregion Properties
}
#endregion SphereRegionSceneQuery Implementation
#region PlaneBoundedVolumeListSceneQuery Implementation
/// <summary>
/// Specializes the SceneQuery class for querying items within PlaneBoundedVolumes.
/// </summary>
public abstract class PlaneBoundedVolumeListSceneQuery : RegionSceneQuery {
#region Fields
/// <summary>
/// Sphere to query items within.
/// </summary>
protected List<PlaneBoundedVolume> volumes;
#endregion Fields
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="creator">SceneManager who created this query.</param>
internal PlaneBoundedVolumeListSceneQuery(SceneManager creator) : base(creator) {}
#endregion Constructor
#region Properties
/// <summary>
/// Gets/Sets the sphere to use for the query.
/// </summary>
public List<PlaneBoundedVolume> Volumes {
get {
return volumes;
}
set {
volumes = value;
}
}
#endregion Properties
}
#endregion PlaneBoundedVolumeListSceneQuery Implementation
#region IntersectionSceneQuery Implementation
/// <summary>
/// Separate SceneQuery class to query for pairs of objects which are
/// possibly intersecting one another.
/// </summary>
/// <remarks>
/// This SceneQuery subclass considers the whole world and returns pairs of objects
/// which are close enough to each other that they may be intersecting. Because of
/// this slightly different focus, the return types and listener interface are
/// different for this class.
/// </remarks>
public abstract class IntersectionSceneQuery : SceneQuery, IIntersectionSceneQueryListener {
#region Fields
/// <summary>
/// List of query results from the last execution of this query.
/// </summary>
protected IntersectionSceneQueryResult lastResults = new IntersectionSceneQueryResult();
#endregion Fields
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
/// <param name="creator">Scene manager who created this query.</param>
internal IntersectionSceneQuery(SceneManager creator) : base(creator) {}
#endregion Constructor
#region Methods
/// <summary>
/// Clears out any cached results from the last query.
/// </summary>
public virtual void ClearResults() {
lastResults.Clear();
}
/// <summary>
/// Executes the query, returning the results back in one list.
/// </summary>
/// <remarks>
/// This method executes the scene query as configured, gathers the results
/// into one structure and returns a reference to that structure. These
/// results will also persist in this query object until the next query is
/// executed, or <see cref="ClearResults"/>. A more lightweight version of
/// this method that returns results through a listener is also available.
/// </remarks>
/// <returns></returns>
public virtual IntersectionSceneQueryResult Execute() {
ClearResults();
// execute the callback version using ourselves as the listener
Execute(this);
return lastResults;
}
/// <summary>
/// Executes the query and returns each match through a listener interface.
/// </summary>
/// <remarks>
/// Note that this method does not store the results of the query internally
/// so does not update the 'last result' value. This means that this version of
/// execute is more lightweight and therefore more efficient than the version
/// which returns the results as a collection.
/// </remarks>
/// <param name="listener">Listener object to handle the result callbacks.</param>
public abstract void Execute(IIntersectionSceneQueryListener listener);
#endregion Methods
#region IIntersectionSceneQueryListener Members
bool Axiom.Core.IIntersectionSceneQueryListener.OnQueryResult(MovableObject first, MovableObject second) {
// create an entry and add it to the cached result list
lastResults.Objects2Objects.Add(new SceneQueryMovableObjectPair(first,second));
// continue gathering results
return true;
}
bool Axiom.Core.IIntersectionSceneQueryListener.OnQueryResult(MovableObject obj, SceneQuery.WorldFragment fragment) {
// create an entry and add it to the cached result list
lastResults.Objects2World.Add(new SceneQueryMovableObjectWorldFragmentPair(obj,fragment));
// continue gathering results
return true;
}
#endregion
}
/// <summary>
/// Alternative listener interface for dealing with <see cref="IntersectionSceneQuery"/>.
/// </summary>
/// <remarks>
/// Because the IntersectionSceneQuery returns results in pairs, rather than singularly,
/// the listener interface must be customised from the standard SceneQueryListener.
/// </remarks>
public interface IIntersectionSceneQueryListener {
/// <summary>
/// Called when 2 movable objects intersect one another.
/// </summary>
/// <param name="first">Reference to the first intersecting object.</param>
/// <param name="second">Reference to the second intersecting object.</param>
/// <returns>Should return false to abandon returning additional results, or true to continue.</returns>
bool OnQueryResult(MovableObject first, MovableObject second);
/// <summary>
/// Called when a movable intersects a world fragment.
/// </summary>
/// <param name="obj">Intersecting object.</param>
/// <param name="fragment">Intersecting world fragment.</param>
/// <returns>Should return false to abandon returning additional results, or true to continue.</returns>
bool OnQueryResult(MovableObject obj, SceneQuery.WorldFragment fragment);
}
/// <summary>Holds the results of an intersection scene query (pair values).</summary>
public class IntersectionSceneQueryResult {
protected List<SceneQueryMovableObjectPair> objects2Objects = new List<SceneQueryMovableObjectPair>();
protected List<SceneQueryMovableObjectWorldFragmentPair> objects2World = new List<SceneQueryMovableObjectWorldFragmentPair>();
public List<SceneQueryMovableObjectPair> Objects2Objects {
get {
return objects2Objects;
}
}
public List<SceneQueryMovableObjectWorldFragmentPair> Objects2World {
get {
return objects2World;
}
}
public void Clear() {
objects2Objects.Clear();
objects2World.Clear();
}
}
#endregion IntersectionSceneQuery Implementation
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.StreamAnalytics;
using Microsoft.Azure.Management.StreamAnalytics.Models;
namespace Microsoft.Azure.Management.StreamAnalytics
{
public static partial class OutputOperationsExtensions
{
/// <summary>
/// Test an output for a stream analytics job. Asynchronous call.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <returns>
/// The test result of the input or output data source.
/// </returns>
public static ResourceTestConnectionResponse BeginTestConnection(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IOutputOperations)s).BeginTestConnectionAsync(resourceGroupName, jobName, outputName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test an output for a stream analytics job. Asynchronous call.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <returns>
/// The test result of the input or output data source.
/// </returns>
public static Task<ResourceTestConnectionResponse> BeginTestConnectionAsync(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName)
{
return operations.BeginTestConnectionAsync(resourceGroupName, jobName, outputName, CancellationToken.None);
}
/// <summary>
/// Create or update an output for a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update an output for
/// a stream analytics job.
/// </param>
/// <returns>
/// The response of the output CreateOrUpdate operation.
/// </returns>
public static OutputCreateOrUpdateResponse CreateOrUpdate(this IOutputOperations operations, string resourceGroupName, string jobName, OutputCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IOutputOperations)s).CreateOrUpdateAsync(resourceGroupName, jobName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update an output for a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update an output for
/// a stream analytics job.
/// </param>
/// <returns>
/// The response of the output CreateOrUpdate operation.
/// </returns>
public static Task<OutputCreateOrUpdateResponse> CreateOrUpdateAsync(this IOutputOperations operations, string resourceGroupName, string jobName, OutputCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, jobName, parameters, CancellationToken.None);
}
/// <summary>
/// Create or update an output for a stream analytics job. The raw json
/// content will be used.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update an output for
/// a stream analytics job. It is in json format
/// </param>
/// <returns>
/// The response of the output CreateOrUpdate operation.
/// </returns>
public static OutputCreateOrUpdateResponse CreateOrUpdateWithRawJsonContent(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName, OutputCreateOrUpdateWithRawJsonContentParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IOutputOperations)s).CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, jobName, outputName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update an output for a stream analytics job. The raw json
/// content will be used.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update an output for
/// a stream analytics job. It is in json format
/// </param>
/// <returns>
/// The response of the output CreateOrUpdate operation.
/// </returns>
public static Task<OutputCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName, OutputCreateOrUpdateWithRawJsonContentParameters parameters)
{
return operations.CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, jobName, outputName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete an output for a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <returns>
/// The common operation response.
/// </returns>
public static CommonOperationResponse Delete(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IOutputOperations)s).DeleteAsync(resourceGroupName, jobName, outputName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete an output for a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <returns>
/// The common operation response.
/// </returns>
public static Task<CommonOperationResponse> DeleteAsync(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName)
{
return operations.DeleteAsync(resourceGroupName, jobName, outputName, CancellationToken.None);
}
/// <summary>
/// Get an output for a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <returns>
/// The response of the output get operation.
/// </returns>
public static OutputGetResponse Get(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IOutputOperations)s).GetAsync(resourceGroupName, jobName, outputName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get an output for a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <returns>
/// The response of the output get operation.
/// </returns>
public static Task<OutputGetResponse> GetAsync(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName)
{
return operations.GetAsync(resourceGroupName, jobName, outputName, CancellationToken.None);
}
/// <summary>
/// Get a list of the outputs defined in a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to list all the outputs in the
/// specified stream analytics job.
/// </param>
/// <returns>
/// The response of the output list operation.
/// </returns>
public static OutputListResponse ListOutputInJob(this IOutputOperations operations, string resourceGroupName, string jobName, OutputListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IOutputOperations)s).ListOutputInJobAsync(resourceGroupName, jobName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of the outputs defined in a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to list all the outputs in the
/// specified stream analytics job.
/// </param>
/// <returns>
/// The response of the output list operation.
/// </returns>
public static Task<OutputListResponse> ListOutputInJobAsync(this IOutputOperations operations, string resourceGroupName, string jobName, OutputListParameters parameters)
{
return operations.ListOutputInJobAsync(resourceGroupName, jobName, parameters, CancellationToken.None);
}
/// <summary>
/// Update an output for a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update an output for
/// a stream analytics job.
/// </param>
/// <returns>
/// The response of the output patch operation.
/// </returns>
public static OutputPatchResponse Patch(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName, OutputPatchParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IOutputOperations)s).PatchAsync(resourceGroupName, jobName, outputName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update an output for a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update an output for
/// a stream analytics job.
/// </param>
/// <returns>
/// The response of the output patch operation.
/// </returns>
public static Task<OutputPatchResponse> PatchAsync(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName, OutputPatchParameters parameters)
{
return operations.PatchAsync(resourceGroupName, jobName, outputName, parameters, CancellationToken.None);
}
/// <summary>
/// Test an output for a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <returns>
/// The test result of the input or output data source.
/// </returns>
public static ResourceTestConnectionResponse TestConnection(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IOutputOperations)s).TestConnectionAsync(resourceGroupName, jobName, outputName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test an output for a stream analytics job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.StreamAnalytics.IOutputOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='outputName'>
/// Required. The name of the output for the stream analytics job.
/// </param>
/// <returns>
/// The test result of the input or output data source.
/// </returns>
public static Task<ResourceTestConnectionResponse> TestConnectionAsync(this IOutputOperations operations, string resourceGroupName, string jobName, string outputName)
{
return operations.TestConnectionAsync(resourceGroupName, jobName, outputName, CancellationToken.None);
}
}
}
| |
#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
#if !PocketPC && !SILVERLIGHT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
internal class DynamicReflectionDelegateFactory : ReflectionDelegateFactory
{
public static DynamicReflectionDelegateFactory Instance = new DynamicReflectionDelegateFactory();
private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner)
{
DynamicMethod dynamicMethod = !owner.IsInterface
? new DynamicMethod(name, returnType, parameterTypes, owner, true)
: new DynamicMethod(name, returnType, parameterTypes, owner.Module, true);
return dynamicMethod;
}
public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
{
DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateMethodCallIL(method, generator);
return (MethodCall<T, object>)dynamicMethod.CreateDelegate(typeof(MethodCall<T, object>));
}
private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator)
{
ParameterInfo[] args = method.GetParameters();
Label argsOk = generator.DefineLabel();
generator.Emit(OpCodes.Ldarg_1);
generator.Emit(OpCodes.Ldlen);
generator.Emit(OpCodes.Ldc_I4, args.Length);
generator.Emit(OpCodes.Beq, argsOk);
generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(Type.EmptyTypes));
generator.Emit(OpCodes.Throw);
generator.MarkLabel(argsOk);
if (!method.IsConstructor && !method.IsStatic)
generator.PushInstance(method.DeclaringType);
for (int i = 0; i < args.Length; i++)
{
generator.Emit(OpCodes.Ldarg_1);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Ldelem_Ref);
generator.UnboxIfNeeded(args[i].ParameterType);
}
if (method.IsConstructor)
generator.Emit(OpCodes.Newobj, (ConstructorInfo)method);
else if (method.IsFinal || !method.IsVirtual)
generator.CallMethod((MethodInfo)method);
Type returnType = method.IsConstructor
? method.DeclaringType
: ((MethodInfo)method).ReturnType;
if (returnType != typeof(void))
generator.BoxIfNeeded(returnType);
else
generator.Emit(OpCodes.Ldnull);
generator.Return();
}
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
DynamicMethod dynamicMethod = CreateDynamicMethod("Create" + type.FullName, typeof(T), Type.EmptyTypes, type);
dynamicMethod.InitLocals = true;
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateDefaultConstructorIL(type, generator);
return (Func<T>)dynamicMethod.CreateDelegate(typeof(Func<T>));
}
private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator)
{
if (type.IsValueType)
{
generator.DeclareLocal(type);
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Box, type);
}
else
{
ConstructorInfo constructorInfo =
type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null,
Type.EmptyTypes, null);
if (constructorInfo == null)
throw new Exception("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type));
generator.Emit(OpCodes.Newobj, constructorInfo);
}
generator.Return();
}
public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(T), new[] { typeof(object) }, propertyInfo.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateGetPropertyIL(propertyInfo, generator);
return (Func<T, object>)dynamicMethod.CreateDelegate(typeof(Func<T, object>));
}
private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator)
{
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod == null)
throw new Exception("Property '{0}' does not have a getter.".FormatWith(CultureInfo.InvariantCulture, propertyInfo.Name));
if (!getMethod.IsStatic)
generator.PushInstance(propertyInfo.DeclaringType);
generator.CallMethod(getMethod);
generator.BoxIfNeeded(propertyInfo.PropertyType);
generator.Return();
}
public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateGetFieldIL(fieldInfo, generator);
return (Func<T, object>)dynamicMethod.CreateDelegate(typeof(Func<T, object>));
}
private void GenerateCreateGetFieldIL(FieldInfo fieldInfo, ILGenerator generator)
{
if (!fieldInfo.IsStatic)
generator.PushInstance(fieldInfo.DeclaringType);
generator.Emit(OpCodes.Ldfld, fieldInfo);
generator.BoxIfNeeded(fieldInfo.FieldType);
generator.Return();
}
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateSetFieldIL(fieldInfo, generator);
return (Action<T, object>)dynamicMethod.CreateDelegate(typeof(Action<T, object>));
}
internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator generator)
{
if (!fieldInfo.IsStatic)
generator.PushInstance(fieldInfo.DeclaringType);
generator.Emit(OpCodes.Ldarg_1);
generator.UnboxIfNeeded(fieldInfo.FieldType);
generator.Emit(OpCodes.Stfld, fieldInfo);
generator.Return();
}
public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateSetPropertyIL(propertyInfo, generator);
return (Action<T, object>)dynamicMethod.CreateDelegate(typeof(Action<T, object>));
}
internal static void GenerateCreateSetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator)
{
MethodInfo setMethod = propertyInfo.GetSetMethod(true);
if (!setMethod.IsStatic)
generator.PushInstance(propertyInfo.DeclaringType);
generator.Emit(OpCodes.Ldarg_1);
generator.UnboxIfNeeded(propertyInfo.PropertyType);
generator.CallMethod(setMethod);
generator.Return();
}
}
}
#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 log4net.Config;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using System.Text;
using log4net;
using System.Reflection;
using System.Data.Common;
// DBMS-specific:
using MySql.Data.MySqlClient;
using OpenSim.Data.MySQL;
using System.Data.SqlClient;
using OpenSim.Data.MSSQL;
using Mono.Data.Sqlite;
using OpenSim.Data.SQLite;
namespace OpenSim.Data.Tests
{
#if NUNIT25
[TestFixture(typeof(MySqlConnection), typeof(MySQLEstateStore), Description = "Estate store tests (MySQL)")]
[TestFixture(typeof(SqlConnection), typeof(MSSQLEstateStore), Description = "Estate store tests (MS SQL Server)")]
[TestFixture(typeof(SqliteConnection), typeof(SQLiteEstateStore), Description = "Estate store tests (SQLite)")]
#else
[TestFixture(Description = "Estate store tests (SQLite)")]
public class SQLiteEstateTests : EstateTests<SqliteConnection, SQLiteEstateStore>
{
}
[TestFixture(Description = "Estate store tests (MySQL)")]
public class MySqlEstateTests : EstateTests<MySqlConnection, MySQLEstateStore>
{
}
[TestFixture(Description = "Estate store tests (MS SQL Server)")]
public class MSSQLEstateTests : EstateTests<SqlConnection, MSSQLEstateStore>
{
}
#endif
public class EstateTests<TConn, TEstateStore> : BasicDataServiceTest<TConn, TEstateStore>
where TConn : DbConnection, new()
where TEstateStore : class, IEstateDataStore, new()
{
public IEstateDataStore db;
public static UUID REGION_ID = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed7");
public static UUID USER_ID_1 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed1");
public static UUID USER_ID_2 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed2");
public static UUID MANAGER_ID_1 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed3");
public static UUID MANAGER_ID_2 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed4");
public static UUID GROUP_ID_1 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed5");
public static UUID GROUP_ID_2 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed6");
protected override void InitService(object service)
{
ClearDB();
db = (IEstateDataStore)service;
db.Initialise(m_connStr);
}
private void ClearDB()
{
// if a new table is added, it has to be dropped here
DropTables(
"estate_managers",
"estate_groups",
"estate_users",
"estateban",
"estate_settings",
"estate_map"
);
ResetMigrations("EstateStore");
}
#region 0Tests
[Test]
public void T010_EstateSettingsSimpleStorage_MinimumParameterSet()
{
EstateSettingsSimpleStorage(
REGION_ID,
DataTestUtil.STRING_MIN,
DataTestUtil.UNSIGNED_INTEGER_MIN,
DataTestUtil.FLOAT_MIN,
DataTestUtil.INTEGER_MIN,
DataTestUtil.INTEGER_MIN,
DataTestUtil.INTEGER_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.DOUBLE_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.STRING_MIN,
DataTestUtil.UUID_MIN
);
}
[Test]
public void T011_EstateSettingsSimpleStorage_MaximumParameterSet()
{
EstateSettingsSimpleStorage(
REGION_ID,
DataTestUtil.STRING_MAX(64),
DataTestUtil.UNSIGNED_INTEGER_MAX,
DataTestUtil.FLOAT_MAX,
DataTestUtil.INTEGER_MAX,
DataTestUtil.INTEGER_MAX,
DataTestUtil.INTEGER_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.DOUBLE_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.STRING_MAX(255),
DataTestUtil.UUID_MAX
);
}
[Test]
public void T012_EstateSettingsSimpleStorage_AccurateParameterSet()
{
EstateSettingsSimpleStorage(
REGION_ID,
DataTestUtil.STRING_MAX(1),
DataTestUtil.UNSIGNED_INTEGER_MIN,
DataTestUtil.FLOAT_ACCURATE,
DataTestUtil.INTEGER_MIN,
DataTestUtil.INTEGER_MIN,
DataTestUtil.INTEGER_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.DOUBLE_ACCURATE,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.STRING_MAX(1),
DataTestUtil.UUID_MIN
);
}
[Test]
public void T012_EstateSettingsRandomStorage()
{
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true);
new PropertyScrambler<EstateSettings>()
.DontScramble(x=>x.EstateID)
.Scramble(originalSettings);
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(REGION_ID, true);
// Checking that loaded values are correct.
Assert.That(loadedSettings, Constraints.PropertyCompareConstraint(originalSettings));
}
[Test]
public void T020_EstateSettingsManagerList()
{
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true);
originalSettings.EstateManagers = new UUID[] { MANAGER_ID_1, MANAGER_ID_2 };
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(REGION_ID, true);
Assert.AreEqual(2, loadedSettings.EstateManagers.Length);
Assert.AreEqual(MANAGER_ID_1, loadedSettings.EstateManagers[0]);
Assert.AreEqual(MANAGER_ID_2, loadedSettings.EstateManagers[1]);
}
[Test]
public void T021_EstateSettingsUserList()
{
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true);
originalSettings.EstateAccess = new UUID[] { USER_ID_1, USER_ID_2 };
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(REGION_ID, true);
Assert.AreEqual(2, loadedSettings.EstateAccess.Length);
Assert.AreEqual(USER_ID_1, loadedSettings.EstateAccess[0]);
Assert.AreEqual(USER_ID_2, loadedSettings.EstateAccess[1]);
}
[Test]
public void T022_EstateSettingsGroupList()
{
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true);
originalSettings.EstateGroups = new UUID[] { GROUP_ID_1, GROUP_ID_2 };
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(REGION_ID, true);
Assert.AreEqual(2, loadedSettings.EstateAccess.Length);
Assert.AreEqual(GROUP_ID_1, loadedSettings.EstateGroups[0]);
Assert.AreEqual(GROUP_ID_2, loadedSettings.EstateGroups[1]);
}
[Test]
public void T022_EstateSettingsBanList()
{
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true);
EstateBan estateBan1 = new EstateBan();
estateBan1.BannedUserID = DataTestUtil.UUID_MIN;
EstateBan estateBan2 = new EstateBan();
estateBan2.BannedUserID = DataTestUtil.UUID_MAX;
originalSettings.EstateBans = new EstateBan[] { estateBan1, estateBan2 };
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(REGION_ID, true);
Assert.AreEqual(2, loadedSettings.EstateBans.Length);
Assert.AreEqual(DataTestUtil.UUID_MIN, loadedSettings.EstateBans[0].BannedUserID);
Assert.AreEqual(DataTestUtil.UUID_MAX, loadedSettings.EstateBans[1].BannedUserID);
}
#endregion
#region Parametrizable Test Implementations
private void EstateSettingsSimpleStorage(
UUID regionId,
string estateName,
uint parentEstateID,
float billableFactor,
int pricePerMeter,
int redirectGridX,
int redirectGridY,
bool useGlobalTime,
bool fixedSun,
double sunPosition,
bool allowVoice,
bool allowDirectTeleport,
bool resetHomeOnTeleport,
bool denyAnonymous,
bool denyIdentified,
bool denyTransacted,
bool denyMinors,
bool abuseEmailToEstateOwner,
bool blockDwell,
bool estateSkipScripts,
bool taxFree,
bool publicAccess,
string abuseEmail,
UUID estateOwner
)
{
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(regionId, true);
SetEstateSettings(originalSettings,
estateName,
parentEstateID,
billableFactor,
pricePerMeter,
redirectGridX,
redirectGridY,
useGlobalTime,
fixedSun,
sunPosition,
allowVoice,
allowDirectTeleport,
resetHomeOnTeleport,
denyAnonymous,
denyIdentified,
denyTransacted,
denyMinors,
abuseEmailToEstateOwner,
blockDwell,
estateSkipScripts,
taxFree,
publicAccess,
abuseEmail,
estateOwner
);
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(regionId, true);
// Checking that loaded values are correct.
ValidateEstateSettings(loadedSettings,
estateName,
parentEstateID,
billableFactor,
pricePerMeter,
redirectGridX,
redirectGridY,
useGlobalTime,
fixedSun,
sunPosition,
allowVoice,
allowDirectTeleport,
resetHomeOnTeleport,
denyAnonymous,
denyIdentified,
denyTransacted,
denyMinors,
abuseEmailToEstateOwner,
blockDwell,
estateSkipScripts,
taxFree,
publicAccess,
abuseEmail,
estateOwner
);
}
#endregion
#region EstateSetting Initialization and Validation Methods
private void SetEstateSettings(
EstateSettings estateSettings,
string estateName,
uint parentEstateID,
float billableFactor,
int pricePerMeter,
int redirectGridX,
int redirectGridY,
bool useGlobalTime,
bool fixedSun,
double sunPosition,
bool allowVoice,
bool allowDirectTeleport,
bool resetHomeOnTeleport,
bool denyAnonymous,
bool denyIdentified,
bool denyTransacted,
bool denyMinors,
bool abuseEmailToEstateOwner,
bool blockDwell,
bool estateSkipScripts,
bool taxFree,
bool publicAccess,
string abuseEmail,
UUID estateOwner
)
{
estateSettings.EstateName = estateName;
estateSettings.ParentEstateID = parentEstateID;
estateSettings.BillableFactor = billableFactor;
estateSettings.PricePerMeter = pricePerMeter;
estateSettings.RedirectGridX = redirectGridX;
estateSettings.RedirectGridY = redirectGridY;
estateSettings.UseGlobalTime = useGlobalTime;
estateSettings.FixedSun = fixedSun;
estateSettings.SunPosition = sunPosition;
estateSettings.AllowVoice = allowVoice;
estateSettings.AllowDirectTeleport = allowDirectTeleport;
estateSettings.ResetHomeOnTeleport = resetHomeOnTeleport;
estateSettings.DenyAnonymous = denyAnonymous;
estateSettings.DenyIdentified = denyIdentified;
estateSettings.DenyTransacted = denyTransacted;
estateSettings.DenyMinors = denyMinors;
estateSettings.AbuseEmailToEstateOwner = abuseEmailToEstateOwner;
estateSettings.BlockDwell = blockDwell;
estateSettings.EstateSkipScripts = estateSkipScripts;
estateSettings.TaxFree = taxFree;
estateSettings.PublicAccess = publicAccess;
estateSettings.AbuseEmail = abuseEmail;
estateSettings.EstateOwner = estateOwner;
}
private void ValidateEstateSettings(
EstateSettings estateSettings,
string estateName,
uint parentEstateID,
float billableFactor,
int pricePerMeter,
int redirectGridX,
int redirectGridY,
bool useGlobalTime,
bool fixedSun,
double sunPosition,
bool allowVoice,
bool allowDirectTeleport,
bool resetHomeOnTeleport,
bool denyAnonymous,
bool denyIdentified,
bool denyTransacted,
bool denyMinors,
bool abuseEmailToEstateOwner,
bool blockDwell,
bool estateSkipScripts,
bool taxFree,
bool publicAccess,
string abuseEmail,
UUID estateOwner
)
{
Assert.AreEqual(estateName, estateSettings.EstateName);
Assert.AreEqual(parentEstateID, estateSettings.ParentEstateID);
DataTestUtil.AssertFloatEqualsWithTolerance(billableFactor, estateSettings.BillableFactor);
Assert.AreEqual(pricePerMeter, estateSettings.PricePerMeter);
Assert.AreEqual(redirectGridX, estateSettings.RedirectGridX);
Assert.AreEqual(redirectGridY, estateSettings.RedirectGridY);
Assert.AreEqual(useGlobalTime, estateSettings.UseGlobalTime);
Assert.AreEqual(fixedSun, estateSettings.FixedSun);
DataTestUtil.AssertDoubleEqualsWithTolerance(sunPosition, estateSettings.SunPosition);
Assert.AreEqual(allowVoice, estateSettings.AllowVoice);
Assert.AreEqual(allowDirectTeleport, estateSettings.AllowDirectTeleport);
Assert.AreEqual(resetHomeOnTeleport, estateSettings.ResetHomeOnTeleport);
Assert.AreEqual(denyAnonymous, estateSettings.DenyAnonymous);
Assert.AreEqual(denyIdentified, estateSettings.DenyIdentified);
Assert.AreEqual(denyTransacted, estateSettings.DenyTransacted);
Assert.AreEqual(denyMinors, estateSettings.DenyMinors);
Assert.AreEqual(abuseEmailToEstateOwner, estateSettings.AbuseEmailToEstateOwner);
Assert.AreEqual(blockDwell, estateSettings.BlockDwell);
Assert.AreEqual(estateSkipScripts, estateSettings.EstateSkipScripts);
Assert.AreEqual(taxFree, estateSettings.TaxFree);
Assert.AreEqual(publicAccess, estateSettings.PublicAccess);
Assert.AreEqual(abuseEmail, estateSettings.AbuseEmail);
Assert.AreEqual(estateOwner, estateSettings.EstateOwner);
}
#endregion
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* Implements OpenPGP's rather strange version of Cipher-FeedBack (CFB) mode
* on top of a simple cipher. This class assumes the IV has been prepended
* to the data stream already, and just accomodates the reset after
* (blockSize + 2) bytes have been read.
* <p>
* For further info see <a href="http://www.ietf.org/rfc/rfc2440.html">RFC 2440</a>.
* </p>
*/
public class OpenPgpCfbBlockCipher
: IBlockCipher
{
private byte[] IV;
private byte[] FR;
private byte[] FRE;
private readonly IBlockCipher cipher;
private readonly int blockSize;
private int count;
private bool forEncryption;
/**
* Basic constructor.
*
* @param cipher the block cipher to be used as the basis of the
* feedback mode.
*/
public OpenPgpCfbBlockCipher(
IBlockCipher cipher)
{
this.cipher = cipher;
this.blockSize = cipher.GetBlockSize();
this.IV = new byte[blockSize];
this.FR = new byte[blockSize];
this.FRE = new byte[blockSize];
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
/**
* return the algorithm name and mode.
*
* @return the name of the underlying algorithm followed by "/PGPCFB"
* and the block size in bits.
*/
public string AlgorithmName
{
get { return cipher.AlgorithmName + "/OpenPGPCFB"; }
}
public bool IsPartialBlockOkay
{
get { return true; }
}
/**
* return the block size we are operating at.
*
* @return the block size we are operating at (in bytes).
*/
public int GetBlockSize()
{
return cipher.GetBlockSize();
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
return (forEncryption) ? EncryptBlock(input, inOff, output, outOff) : DecryptBlock(input, inOff, output, outOff);
}
/**
* reset the chaining vector back to the IV and reset the underlying
* cipher.
*/
public void Reset()
{
count = 0;
Array.Copy(IV, 0, FR, 0, FR.Length);
cipher.Reset();
}
/**
* Initialise the cipher and, possibly, the initialisation vector (IV).
* If an IV isn't passed as part of the parameter, the IV will be all zeros.
* An IV which is too short is handled in FIPS compliant fashion.
*
* @param forEncryption if true the cipher is initialised for
* encryption, if false for decryption.
* @param parameters the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.forEncryption = forEncryption;
if (parameters is ParametersWithIV)
{
ParametersWithIV ivParam = (ParametersWithIV)parameters;
byte[] iv = ivParam.GetIV();
if (iv.Length < IV.Length)
{
// prepend the supplied IV with zeros (per FIPS PUB 81)
Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
for (int i = 0; i < IV.Length - iv.Length; i++)
{
IV[i] = 0;
}
}
else
{
Array.Copy(iv, 0, IV, 0, IV.Length);
}
parameters = ivParam.Parameters;
}
Reset();
cipher.Init(true, parameters);
}
/**
* Encrypt one byte of data according to CFB mode.
* @param data the byte to encrypt
* @param blockOff offset in the current block
* @returns the encrypted byte
*/
private byte EncryptByte(byte data, int blockOff)
{
return (byte)(FRE[blockOff] ^ data);
}
/**
* Do the appropriate processing for CFB IV mode encryption.
*
* @param in the array containing the data to be encrypted.
* @param inOff offset into the in array the data starts at.
* @param out the array the encrypted data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
private int EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
if ((inOff + blockSize) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + blockSize) > outBytes.Length)
{
throw new DataLengthException("output buffer too short");
}
if (count > blockSize)
{
FR[blockSize - 2] = outBytes[outOff] = EncryptByte(input[inOff], blockSize - 2);
FR[blockSize - 1] = outBytes[outOff + 1] = EncryptByte(input[inOff + 1], blockSize - 1);
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 2; n < blockSize; n++)
{
FR[n - 2] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n - 2);
}
}
else if (count == 0)
{
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 0; n < blockSize; n++)
{
FR[n] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n);
}
count += blockSize;
}
else if (count == blockSize)
{
cipher.ProcessBlock(FR, 0, FRE, 0);
outBytes[outOff] = EncryptByte(input[inOff], 0);
outBytes[outOff + 1] = EncryptByte(input[inOff + 1], 1);
//
// do reset
//
Array.Copy(FR, 2, FR, 0, blockSize - 2);
Array.Copy(outBytes, outOff, FR, blockSize - 2, 2);
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 2; n < blockSize; n++)
{
FR[n - 2] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n - 2);
}
count += blockSize;
}
return blockSize;
}
/**
* Do the appropriate processing for CFB IV mode decryption.
*
* @param in the array containing the data to be decrypted.
* @param inOff offset into the in array the data starts at.
* @param out the array the encrypted data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
private int DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
if ((inOff + blockSize) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + blockSize) > outBytes.Length)
{
throw new DataLengthException("output buffer too short");
}
if (count > blockSize)
{
byte inVal = input[inOff];
FR[blockSize - 2] = inVal;
outBytes[outOff] = EncryptByte(inVal, blockSize - 2);
inVal = input[inOff + 1];
FR[blockSize - 1] = inVal;
outBytes[outOff + 1] = EncryptByte(inVal, blockSize - 1);
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 2; n < blockSize; n++)
{
inVal = input[inOff + n];
FR[n - 2] = inVal;
outBytes[outOff + n] = EncryptByte(inVal, n - 2);
}
}
else if (count == 0)
{
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 0; n < blockSize; n++)
{
FR[n] = input[inOff + n];
outBytes[n] = EncryptByte(input[inOff + n], n);
}
count += blockSize;
}
else if (count == blockSize)
{
cipher.ProcessBlock(FR, 0, FRE, 0);
byte inVal1 = input[inOff];
byte inVal2 = input[inOff + 1];
outBytes[outOff ] = EncryptByte(inVal1, 0);
outBytes[outOff + 1] = EncryptByte(inVal2, 1);
Array.Copy(FR, 2, FR, 0, blockSize - 2);
FR[blockSize - 2] = inVal1;
FR[blockSize - 1] = inVal2;
cipher.ProcessBlock(FR, 0, FRE, 0);
for (int n = 2; n < blockSize; n++)
{
byte inVal = input[inOff + n];
FR[n - 2] = inVal;
outBytes[outOff + n] = EncryptByte(inVal, n - 2);
}
count += blockSize;
}
return blockSize;
}
}
}
#endif
| |
using System;
using System.Linq;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Migrations.Initial;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Services;
namespace Umbraco.Core.Persistence
{
/// <summary>
/// Helper class for working with databases and schemas.
/// </summary>
public class DatabaseSchemaHelper
{
private readonly Database _db;
private readonly ILogger _logger;
private readonly ISqlSyntaxProvider _syntaxProvider;
private readonly BaseDataCreation _baseDataCreation;
/// <summary>
/// Intializes a new helper instance.
/// </summary>
/// <param name="db">The database to be used.</param>
/// <param name="logger">The logger.</param>
/// <param name="syntaxProvider">The syntax provider.</param>
/// <example>
/// A new instance could be initialized like:
/// <code>
/// var schemaHelper = new DatabaseSchemaHelper(
/// ApplicationContext.Current.DatabaseContext.Database,
/// ApplicationContext.Current.ProfilingLogger.Logger,
/// ApplicationContext.Current.DatabaseContext.SqlSyntax
/// );
/// </code>
/// </example>
public DatabaseSchemaHelper(Database db, ILogger logger, ISqlSyntaxProvider syntaxProvider)
{
_db = db;
_logger = logger;
_syntaxProvider = syntaxProvider;
_baseDataCreation = new BaseDataCreation(db, logger);
}
/// <summary>
/// Returns whether a table with the specified <paramref name="tableName"/> exists in the database.
/// </summary>
/// <param name="tableName">The name of the table.</param>
/// <returns><c>true</c> if the table exists; otherwise <c>false</c>.</returns>
/// <example>
/// <code>
/// if (schemaHelper.TableExist("MyTable"))
/// {
/// // do something when the table exists
/// }
/// </code>
/// </example>
public bool TableExist(string tableName)
{
return _syntaxProvider.DoesTableExist(_db, tableName);
}
/// <summary>
/// Returns whether the table for the specified <typeparamref name="T"/> exists in the database.
///
/// If <typeparamref name="T"/> has been decorated with an <see cref="TableNameAttribute"/>, the name from that
/// attribute will be used for the table name. If the attribute is not present, the name
/// <typeparamref name="T"/> will be used instead.
/// </summary>
/// <typeparam name="T">The type representing the DTO/table.</typeparam>
/// <returns><c>true</c> if the table exists; otherwise <c>false</c>.</returns>
/// <example>
/// <code>
/// if (schemaHelper.TableExist<MyDto>)
/// {
/// // do something when the table exists
/// }
/// </code>
/// </example>
public bool TableExist<T>()
{
var poco = Database.PocoData.ForType(typeof(T));
var tableName = poco.TableInfo.TableName;
return TableExist(tableName);
}
internal void UninstallDatabaseSchema()
{
var creation = new DatabaseSchemaCreation(_db, _logger, _syntaxProvider);
creation.UninstallDatabaseSchema();
}
/// <summary>
/// Creates the Umbraco db schema in the Database of the current Database.
/// Safe method that is only able to create the schema in non-configured
/// umbraco instances.
/// </summary>
public void CreateDatabaseSchema(ApplicationContext applicationContext)
{
if (applicationContext == null) throw new ArgumentNullException("applicationContext");
CreateDatabaseSchema(true, applicationContext);
}
/// <summary>
/// Creates the Umbraco db schema in the Database of the current Database
/// with the option to guard the db from having the schema created
/// multiple times.
/// </summary>
/// <param name="guardConfiguration"></param>
/// <param name="applicationContext"></param>
public void CreateDatabaseSchema(bool guardConfiguration, ApplicationContext applicationContext)
{
if (applicationContext == null) throw new ArgumentNullException("applicationContext");
if (guardConfiguration && applicationContext.IsConfigured)
throw new Exception("Umbraco is already configured!");
CreateDatabaseSchemaDo(applicationContext.Services.MigrationEntryService);
}
internal void CreateDatabaseSchemaDo(bool guardConfiguration, ApplicationContext applicationContext)
{
if (guardConfiguration && applicationContext.IsConfigured)
throw new Exception("Umbraco is already configured!");
CreateDatabaseSchemaDo(applicationContext.Services.MigrationEntryService);
}
internal void CreateDatabaseSchemaDo(IMigrationEntryService migrationEntryService)
{
_logger.Info<Database>("Initializing database schema creation");
var creation = new DatabaseSchemaCreation(_db, _logger, _syntaxProvider);
creation.InitializeDatabaseSchema();
_logger.Info<Database>("Finalized database schema creation");
}
/// Creates a new table in the database based on the type of <typeparamref name="T"/>.
///
/// If <typeparamref name="T"/> has been decorated with an <see cref="TableNameAttribute"/>, the name from that
/// attribute will be used for the table name. If the attribute is not present, the name
/// <typeparamref name="T"/> will be used instead.
///
/// If a table with the same name already exists, the <paramref name="overwrite"/> parameter will determine
/// whether the table is overwritten. If <c>true</c>, the table will be overwritten, whereas this method will
/// not do anything if the parameter is <c>false</c>.
/// <typeparam name="T">The type representing the DTO/table.</typeparam>
/// <param name="overwrite">Whether the table should be overwritten if it already exists.</param>
public void CreateTable<T>(bool overwrite)
where T : new()
{
var tableType = typeof(T);
CreateTable(overwrite, tableType);
}
/// <summary>
/// Creates a new table in the database based on the type of <typeparamref name="T"/>.
///
/// If <typeparamref name="T"/> has been decorated with an <see cref="TableNameAttribute"/>, the name from that
/// attribute will be used for the table name. If the attribute is not present, the name
/// <typeparamref name="T"/> will be used instead.
///
/// If a table with the same name already exists, this method will not do anything.
/// </summary>
/// <typeparam name="T">The type representing the DTO/table.</typeparam>
public void CreateTable<T>()
where T : new()
{
var tableType = typeof(T);
CreateTable(false, tableType);
}
/// <summary>
/// Creates a new table in the database for the specified <paramref name="modelType"/>.
///
/// If <paramref name="modelType"/> has been decorated with an <see cref="TableNameAttribute"/>, the name from
/// that attribute will be used for the table name. If the attribute is not present, the name
/// <paramref name="modelType"/> will be used instead.
///
/// If a table with the same name already exists, the <paramref name="overwrite"/> parameter will determine
/// whether the table is overwritten. If <c>true</c>, the table will be overwritten, whereas this method will
/// not do anything if the parameter is <c>false</c>.
/// </summary>
/// <param name="overwrite">Whether the table should be overwritten if it already exists.</param>
/// <param name="modelType">The the representing the table.</param>
public void CreateTable(bool overwrite, Type modelType)
{
var tableDefinition = DefinitionFactory.GetTableDefinition(_syntaxProvider, modelType);
var tableName = tableDefinition.Name;
string createSql = _syntaxProvider.Format(tableDefinition);
string createPrimaryKeySql = _syntaxProvider.FormatPrimaryKey(tableDefinition);
var foreignSql = _syntaxProvider.Format(tableDefinition.ForeignKeys);
var indexSql = _syntaxProvider.Format(tableDefinition.Indexes);
var tableExist = TableExist(tableName);
if (overwrite && tableExist)
{
_logger.Info<Database>(string.Format("Table '{0}' already exists, but will be recreated", tableName));
DropTable(tableName);
tableExist = false;
}
if (tableExist == false)
{
using (var transaction = _db.GetTransaction())
{
//Execute the Create Table sql
int created = _db.Execute(new Sql(createSql));
_logger.Info<Database>(string.Format("Create Table sql {0}:\n {1}", created, createSql));
//If any statements exists for the primary key execute them here
if (!string.IsNullOrEmpty(createPrimaryKeySql))
{
int createdPk = _db.Execute(new Sql(createPrimaryKeySql));
_logger.Info<Database>(string.Format("Primary Key sql {0}:\n {1}", createdPk, createPrimaryKeySql));
}
//Turn on identity insert if db provider is not mysql
if (_syntaxProvider.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity))
_db.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} ON ", _syntaxProvider.GetQuotedTableName(tableName))));
//Call the NewTable-event to trigger the insert of base/default data
//OnNewTable(tableName, _db, e, _logger);
_baseDataCreation.InitializeBaseData(tableName);
//Turn off identity insert if db provider is not mysql
if (_syntaxProvider.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity))
_db.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} OFF;", _syntaxProvider.GetQuotedTableName(tableName))));
//Special case for MySql
if (_syntaxProvider is MySqlSyntaxProvider && tableName.Equals("umbracoUser"))
{
_db.Update<UserDto>("SET id = @IdAfter WHERE id = @IdBefore AND userLogin = @Login", new { IdAfter = 0, IdBefore = 1, Login = "admin" });
}
//Loop through index statements and execute sql
foreach (var sql in indexSql)
{
int createdIndex = _db.Execute(new Sql(sql));
_logger.Info<Database>(string.Format("Create Index sql {0}:\n {1}", createdIndex, sql));
}
//Loop through foreignkey statements and execute sql
foreach (var sql in foreignSql)
{
int createdFk = _db.Execute(new Sql(sql));
_logger.Info<Database>(string.Format("Create Foreign Key sql {0}:\n {1}", createdFk, sql));
}
transaction.Complete();
if (overwrite)
{
_logger.Info<Database>(string.Format("Table '{0}' was recreated", tableName));
}
else
{
_logger.Info<Database>(string.Format("New table '{0}' was created", tableName));
}
}
}
else
{
// The table exists and was not recreated/overwritten.
_logger.Info<Database>(string.Format("Table '{0}' already exists - no changes were made", tableName));
}
}
/// <summary>
/// Drops the table for the specified <typeparamref name="T"/>.
///
/// If <typeparamref name="T"/> has been decorated with an <see cref="TableNameAttribute"/>, the name from that
/// attribute will be used for the table name. If the attribute is not present, the name
/// <typeparamref name="T"/> will be used instead.
/// </summary>
/// <typeparam name="T">The type representing the DTO/table.</typeparam>
/// <example>
/// <code>
/// schemaHelper.DropTable<MyDto>);
/// </code>
/// </example>
public void DropTable<T>()
where T : new()
{
Type type = typeof(T);
var tableNameAttribute = type.FirstAttribute<TableNameAttribute>();
if (tableNameAttribute == null)
throw new Exception(
string.Format(
"The Type '{0}' does not contain a TableNameAttribute, which is used to find the name of the table to drop. The operation could not be completed.",
type.Name));
string tableName = tableNameAttribute.Value;
DropTable(tableName);
}
/// <summary>
/// Drops the table with the specified <paramref name="tableName"/>.
/// </summary>
/// <param name="tableName">The name of the table.</param>
/// <example>
/// <code>
/// schemaHelper.DropTable("MyTable");
/// </code>
/// </example>
public void DropTable(string tableName)
{
var sql = new Sql(string.Format(
_syntaxProvider.DropTable,
_syntaxProvider.GetQuotedTableName(tableName)));
_db.Execute(sql);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//=============================================================================
//
//
// Purpose: Define HResult constants. Every exception has one of these.
//
//
//===========================================================================*/
// Note: FACILITY_URT is defined as 0x13 (0x8013xxxx). Within that
// range, 0x1yyy is for Runtime errors (used for Security, Metadata, etc).
// In that subrange, 0x15zz and 0x16zz have been allocated for classlib-type
// HResults. Also note that some of our HResults have to map to certain
// COM HR's, etc.
// Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f.
// Security will use 0x1640 -> 0x165f
using System;
namespace System
{
internal static partial class HResults
{
[Bridge.InlineConst]
internal const int COR_E_ABANDONEDMUTEX = unchecked((int)0x8013152D);
[Bridge.InlineConst]
internal const int COR_E_AMBIGUOUSMATCH = unchecked((int)0x8000211D);
[Bridge.InlineConst]
internal const int COR_E_APPDOMAINUNLOADED = unchecked((int)0x80131014);
[Bridge.InlineConst]
internal const int COR_E_APPLICATION = unchecked((int)0x80131600);
[Bridge.InlineConst]
internal const int COR_E_ARGUMENT = unchecked((int)0x80070057);
[Bridge.InlineConst]
internal const int COR_E_ARGUMENTOUTOFRANGE = unchecked((int)0x80131502);
[Bridge.InlineConst]
internal const int COR_E_ARITHMETIC = unchecked((int)0x80070216);
[Bridge.InlineConst]
internal const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503);
[Bridge.InlineConst]
internal const int COR_E_BADEXEFORMAT = unchecked((int)0x800700C1);
[Bridge.InlineConst]
internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B);
[Bridge.InlineConst]
internal const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015);
[Bridge.InlineConst]
internal const int COR_E_COMEMULATE = unchecked((int)0x80131535);
[Bridge.InlineConst]
internal const int COR_E_CONTEXTMARSHAL = unchecked((int)0x80131504);
[Bridge.InlineConst]
internal const int COR_E_CUSTOMATTRIBUTEFORMAT = unchecked((int)0x80131605);
[Bridge.InlineConst]
internal const int COR_E_DATAMISALIGNED = unchecked((int)0x80131541);
[Bridge.InlineConst]
internal const int COR_E_DIRECTORYNOTFOUND = unchecked((int)0x80070003);
[Bridge.InlineConst]
internal const int COR_E_DIVIDEBYZERO = unchecked((int)0x80020012); // DISP_E_DIVBYZERO
[Bridge.InlineConst]
internal const int COR_E_DLLNOTFOUND = unchecked((int)0x80131524);
[Bridge.InlineConst]
internal const int COR_E_DUPLICATEWAITOBJECT = unchecked((int)0x80131529);
[Bridge.InlineConst]
internal const int COR_E_ENDOFSTREAM = unchecked((int)0x80070026); // OS defined
[Bridge.InlineConst]
internal const int COR_E_ENTRYPOINTNOTFOUND = unchecked((int)0x80131523);
[Bridge.InlineConst]
internal const int COR_E_EXCEPTION = unchecked((int)0x80131500);
[Bridge.InlineConst]
internal const int COR_E_EXECUTIONENGINE = unchecked((int)0x80131506);
[Bridge.InlineConst]
internal const int COR_E_FIELDACCESS = unchecked((int)0x80131507);
[Bridge.InlineConst]
internal const int COR_E_FILELOAD = unchecked((int)0x80131621);
[Bridge.InlineConst]
internal const int COR_E_FILENOTFOUND = unchecked((int)0x80070002);
[Bridge.InlineConst]
internal const int COR_E_FORMAT = unchecked((int)0x80131537);
[Bridge.InlineConst]
internal const int COR_E_HOSTPROTECTION = unchecked((int)0x80131640);
[Bridge.InlineConst]
internal const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508);
[Bridge.InlineConst]
internal const int COR_E_INSUFFICIENTEXECUTIONSTACK = unchecked((int)0x80131578);
[Bridge.InlineConst]
internal const int COR_E_INSUFFICIENTMEMORY = unchecked((int)0x8013153D);
[Bridge.InlineConst]
internal const int COR_E_INVALIDCAST = unchecked((int)0x80004002);
[Bridge.InlineConst]
internal const int COR_E_INVALIDCOMOBJECT = unchecked((int)0x80131527);
[Bridge.InlineConst]
internal const int COR_E_INVALIDFILTERCRITERIA = unchecked((int)0x80131601);
[Bridge.InlineConst]
internal const int COR_E_INVALIDOLEVARIANTTYPE = unchecked((int)0x80131531);
[Bridge.InlineConst]
internal const int COR_E_INVALIDOPERATION = unchecked((int)0x80131509);
[Bridge.InlineConst]
internal const int COR_E_INVALIDPROGRAM = unchecked((int)0x8013153A);
[Bridge.InlineConst]
internal const int COR_E_IO = unchecked((int)0x80131620);
[Bridge.InlineConst]
internal const int COR_E_KEYNOTFOUND = unchecked((int)0x80131577);
[Bridge.InlineConst]
internal const int COR_E_MARSHALDIRECTIVE = unchecked((int)0x80131535);
[Bridge.InlineConst]
internal const int COR_E_MEMBERACCESS = unchecked((int)0x8013151A);
[Bridge.InlineConst]
internal const int COR_E_METHODACCESS = unchecked((int)0x80131510);
[Bridge.InlineConst]
internal const int COR_E_MISSINGFIELD = unchecked((int)0x80131511);
[Bridge.InlineConst]
internal const int COR_E_MISSINGMANIFESTRESOURCE = unchecked((int)0x80131532);
[Bridge.InlineConst]
internal const int COR_E_MISSINGMEMBER = unchecked((int)0x80131512);
[Bridge.InlineConst]
internal const int COR_E_MISSINGMETHOD = unchecked((int)0x80131513);
[Bridge.InlineConst]
internal const int COR_E_MISSINGSATELLITEASSEMBLY = unchecked((int)0x80131536);
[Bridge.InlineConst]
internal const int CvOR_E_MULTICASTNOTSUPPORTED = unchecked((int)0x80131514);
[Bridge.InlineConst]
internal const int COR_E_NOTFINITENUMBER = unchecked((int)0x80131528);
[Bridge.InlineConst]
internal const int COR_E_NOTSUPPORTED = unchecked((int)0x80131515);
[Bridge.InlineConst]
internal const int COR_E_NULLREFERENCE = unchecked((int)0x80004003);
[Bridge.InlineConst]
internal const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622);
[Bridge.InlineConst]
internal const int COR_E_OPERATIONCANCELED = unchecked((int)0x8013153B);
[Bridge.InlineConst]
internal const int COR_E_OUTOFMEMORY = unchecked((int)0x8007000E);
[Bridge.InlineConst]
internal const int COR_E_OVERFLOW = unchecked((int)0x80131516);
[Bridge.InlineConst]
internal const int COR_E_PATHTOOLONG = unchecked((int)0x800700CE);
[Bridge.InlineConst]
internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539);
[Bridge.InlineConst]
internal const int COR_E_RANK = unchecked((int)0x80131517);
[Bridge.InlineConst]
internal const int COR_E_REFLECTIONTYPELOAD = unchecked((int)0x80131602);
[Bridge.InlineConst]
internal const int COR_E_RUNTIMEWRAPPED = unchecked((int)0x8013153E);
[Bridge.InlineConst]
internal const int COR_E_SAFEARRAYRANKMISMATCH = unchecked((int)0x80131538);
[Bridge.InlineConst]
internal const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked((int)0x80131533);
[Bridge.InlineConst]
internal const int COR_E_SAFEHANDLEMISSINGATTRIBUTE = unchecked((int)0x80131623);
[Bridge.InlineConst]
internal const int COR_E_SECURITY = unchecked((int)0x8013150A);
[Bridge.InlineConst]
internal const int COR_E_SEMAPHOREFULL = unchecked((int)0x8013152B);
[Bridge.InlineConst]
internal const int COR_E_SERIALIZATION = unchecked((int)0x8013150C);
[Bridge.InlineConst]
internal const int COR_E_STACKOVERFLOW = unchecked((int)0x800703E9);
[Bridge.InlineConst]
internal const int COR_E_SYNCHRONIZATIONLOCK = unchecked((int)0x80131518);
[Bridge.InlineConst]
internal const int COR_E_SYSTEM = unchecked((int)0x80131501);
[Bridge.InlineConst]
internal const int COR_E_TARGET = unchecked((int)0x80131603);
[Bridge.InlineConst]
internal const int COR_E_TARGETINVOCATION = unchecked((int)0x80131604);
[Bridge.InlineConst]
internal const int COR_E_TARGETPARAMCOUNT = unchecked((int)0x8002000E);
[Bridge.InlineConst]
internal const int COR_E_THREADABORTED = unchecked((int)0x80131530);
[Bridge.InlineConst]
internal const int COR_E_THREADINTERRUPTED = unchecked((int)0x80131519);
[Bridge.InlineConst]
internal const int COR_E_THREADSTART = unchecked((int)0x80131525);
[Bridge.InlineConst]
internal const int COvR_E_THREADSTATE = unchecked((int)0x80131520);
[Bridge.InlineConst]
internal const int COR_E_THREADSTOP = unchecked((int)0x80131521);
[Bridge.InlineConst]
internal const int COR_E_TIMEOUT = unchecked((int)0x80131505);
[Bridge.InlineConst]
internal const int COR_E_TYPEACCESS = unchecked((int)0x80131543);
[Bridge.InlineConst]
internal const int COR_E_TYPEINITIALIZATION = unchecked((int)0x80131534);
[Bridge.InlineConst]
internal const int COR_E_TYPELOAD = unchecked((int)0x80131522);
[Bridge.InlineConst]
internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013);
[Bridge.InlineConst]
internal const int COR_E_UNAUTHORIZEDACCESS = unchecked((int)0x80070005);
[Bridge.InlineConst]
internal const int COR_E_UNSUPPORTEDFORMAT = unchecked((int)0x80131523);
[Bridge.InlineConst]
internal const int COR_E_VERIFICATION = unchecked((int)0x8013150D);
[Bridge.InlineConst]
internal const int COR_E_WAITHANDLECANNOTBEOPENED = unchecked((int)0x8013152C);
[Bridge.InlineConst]
internal const int DISP_E_OVERFLOW = unchecked((int)0x8002000A);
[Bridge.InlineConst]
internal const int E_BOUNDS = unchecked((int)0x8000000B);
[Bridge.InlineConst]
internal const int E_CHANGED_STATE = unchecked((int)0x8000000C);
[Bridge.InlineConst]
internal const int E_FAIL = unchecked((int)0x80004005);
[Bridge.InlineConst]
internal const int E_HANDLE = unchecked((int)0x80070006);
[Bridge.InlineConst]
internal const int E_INVALIDARG = unchecked((int)0x80070057);
[Bridge.InlineConst]
internal const int E_NOTIMPL = unchecked((int)0x80004001);
[Bridge.InlineConst]
internal const int E_POINTER = unchecked((int)0x80004003);
[Bridge.InlineConst]
internal const int ERROR_MRM_MAP_NOT_FOUND = unchecked((int)0x80073B1F);
[Bridge.InlineConst]
internal const int RO_E_CLOSED = unchecked((int)0x80000013);
[Bridge.InlineConst]
internal const int TYPE_E_TYPEMISMATCH = unchecked((int)0x80028CA0);
}
}
| |
// Keep this file CodeMaid organised and cleaned
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
namespace ClosedXML.Excel
{
public interface IXLWorkbook : IXLProtectable<IXLWorkbookProtection, XLWorkbookProtectionElements>, IDisposable
{
String Author { get; set; }
/// <summary>
/// Gets or sets the workbook's calculation mode.
/// </summary>
XLCalculateMode CalculateMode { get; set; }
Boolean CalculationOnSave { get; set; }
/// <summary>
/// Gets or sets the default column width for the workbook.
/// <para>All new worksheets will use this column width.</para>
/// </summary>
Double ColumnWidth { get; set; }
IXLCustomProperties CustomProperties { get; }
Boolean DefaultRightToLeft { get; }
Boolean DefaultShowFormulas { get; }
Boolean DefaultShowGridLines { get; }
Boolean DefaultShowOutlineSymbols { get; }
Boolean DefaultShowRowColHeaders { get; }
Boolean DefaultShowRuler { get; }
Boolean DefaultShowWhiteSpace { get; }
Boolean DefaultShowZeros { get; }
IXLFileSharing FileSharing { get; }
Boolean ForceFullCalculation { get; set; }
Boolean FullCalculationOnLoad { get; set; }
Boolean FullPrecision { get; set; }
//Boolean IsPasswordProtected { get; }
//Boolean IsProtected { get; }
Boolean LockStructure { get; set; }
Boolean LockWindows { get; set; }
/// <summary>
/// Gets an object to manipulate this workbook's named ranges.
/// </summary>
IXLNamedRanges NamedRanges { get; }
/// <summary>
/// Gets or sets the default outline options for the workbook.
/// <para>All new worksheets will use these outline options.</para>
/// </summary>
IXLOutline Outline { get; set; }
/// <summary>
/// Gets or sets the default page options for the workbook.
/// <para>All new worksheets will use these page options.</para>
/// </summary>
IXLPageSetup PageOptions { get; set; }
/// <summary>
/// Gets or sets the workbook's properties.
/// </summary>
XLWorkbookProperties Properties { get; set; }
/// <summary>
/// Gets or sets the workbook's reference style.
/// </summary>
XLReferenceStyle ReferenceStyle { get; set; }
Boolean RightToLeft { get; set; }
/// <summary>
/// Gets or sets the default row height for the workbook.
/// <para>All new worksheets will use this row height.</para>
/// </summary>
Double RowHeight { get; set; }
Boolean ShowFormulas { get; set; }
Boolean ShowGridLines { get; set; }
Boolean ShowOutlineSymbols { get; set; }
Boolean ShowRowColHeaders { get; set; }
Boolean ShowRuler { get; set; }
Boolean ShowWhiteSpace { get; set; }
Boolean ShowZeros { get; set; }
/// <summary>
/// Gets or sets the default style for the workbook.
/// <para>All new worksheets will use this style.</para>
/// </summary>
IXLStyle Style { get; set; }
/// <summary>
/// Gets an object to manipulate this workbook's theme.
/// </summary>
IXLTheme Theme { get; }
Boolean Use1904DateSystem { get; set; }
/// <summary>
/// Gets an object to manipulate the worksheets.
/// </summary>
IXLWorksheets Worksheets { get; }
IXLWorksheet AddWorksheet();
IXLWorksheet AddWorksheet(Int32 position);
IXLWorksheet AddWorksheet(String sheetName);
IXLWorksheet AddWorksheet(String sheetName, Int32 position);
IXLWorksheet AddWorksheet(DataTable dataTable);
void AddWorksheet(DataSet dataSet);
void AddWorksheet(IXLWorksheet worksheet);
IXLWorksheet AddWorksheet(DataTable dataTable, String sheetName);
IXLCell Cell(String namedCell);
IXLCells Cells(String namedCells);
IXLCustomProperty CustomProperty(String name);
Object Evaluate(String expression);
IXLCells FindCells(Func<IXLCell, Boolean> predicate);
IXLColumns FindColumns(Func<IXLColumn, Boolean> predicate);
IXLRows FindRows(Func<IXLRow, Boolean> predicate);
IXLNamedRange NamedRange(String rangeName);
[Obsolete("Use Protect(String password, Algorithm algorithm, TElement allowedElements)")]
IXLWorkbookProtection Protect(Boolean lockStructure, Boolean lockWindows, String password);
[Obsolete("Use Protect(String password, Algorithm algorithm, TElement allowedElements)")]
IXLWorkbookProtection Protect(Boolean lockStructure);
[Obsolete("Use Protect(String password, Algorithm algorithm, TElement allowedElements)")]
IXLWorkbookProtection Protect(Boolean lockStructure, Boolean lockWindows);
IXLRange Range(String range);
IXLRange RangeFromFullAddress(String rangeAddress, out IXLWorksheet ws);
IXLRanges Ranges(String ranges);
/// <summary>
/// Force recalculation of all cell formulas.
/// </summary>
void RecalculateAllFormulas();
/// <summary>
/// Saves the current workbook.
/// </summary>
void Save();
/// <summary>
/// Saves the current workbook and optionally performs validation
/// </summary>
void Save(Boolean validate, Boolean evaluateFormulae = false);
void Save(SaveOptions options);
/// <summary>
/// Saves the current workbook to a file.
/// </summary>
void SaveAs(String file);
/// <summary>
/// Saves the current workbook to a file and optionally validates it.
/// </summary>
void SaveAs(String file, Boolean validate, Boolean evaluateFormulae = false);
void SaveAs(String file, SaveOptions options);
/// <summary>
/// Saves the current workbook to a stream.
/// </summary>
void SaveAs(Stream stream);
/// <summary>
/// Saves the current workbook to a stream and optionally validates it.
/// </summary>
void SaveAs(Stream stream, Boolean validate, Boolean evaluateFormulae = false);
void SaveAs(Stream stream, SaveOptions options);
/// <summary>
/// Searches the cells' contents for a given piece of text
/// </summary>
/// <param name="searchText">The search text.</param>
/// <param name="compareOptions">The compare options.</param>
/// <param name="searchFormulae">if set to <c>true</c> search formulae instead of cell values.</param>
/// <returns></returns>
IEnumerable<IXLCell> Search(String searchText, CompareOptions compareOptions = CompareOptions.Ordinal, Boolean searchFormulae = false);
XLWorkbook SetLockStructure(Boolean value);
XLWorkbook SetLockWindows(Boolean value);
XLWorkbook SetUse1904DateSystem();
XLWorkbook SetUse1904DateSystem(Boolean value);
/// <summary>
/// Gets the Excel table of the given name
/// </summary>
/// <param name="tableName">Name of the table to return.</param>
/// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param>
/// <returns>The table with given name</returns>
/// <exception cref="ArgumentOutOfRangeException">If no tables with this name could be found in the workbook.</exception>
IXLTable Table(String tableName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase);
Boolean TryGetWorksheet(String name, out IXLWorksheet worksheet);
IXLWorksheet Worksheet(String name);
IXLWorksheet Worksheet(Int32 position);
}
}
| |
// Copyright 2017, Google Inc. 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.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Trace.V1
{
/// <summary>
/// Settings for a <see cref="TraceServiceClient"/>.
/// </summary>
public sealed partial class TraceServiceSettings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="TraceServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="TraceServiceSettings"/>.
/// </returns>
public static TraceServiceSettings GetDefault() => new TraceServiceSettings();
/// <summary>
/// Constructs a new <see cref="TraceServiceSettings"/> object with default settings.
/// </summary>
public TraceServiceSettings() { }
private TraceServiceSettings(TraceServiceSettings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
PatchTracesSettings = existing.PatchTracesSettings;
GetTraceSettings = existing.GetTraceSettings;
ListTracesSettings = existing.ListTracesSettings;
OnCopy(existing);
}
partial void OnCopy(TraceServiceSettings existing);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="TraceServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="TraceServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "NonIdempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.Unavailable);
/// <summary>
/// "Default" retry backoff for <see cref="TraceServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="TraceServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="TraceServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 1000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.2</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(1000),
delayMultiplier: 1.2
);
/// <summary>
/// "Default" timeout backoff for <see cref="TraceServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="TraceServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="TraceServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Maximum timeout: 30000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(20000),
maxDelay: TimeSpan.FromMilliseconds(30000),
delayMultiplier: 1.5
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>TraceServiceClient.PatchTraces</c> and <c>TraceServiceClient.PatchTracesAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>TraceServiceClient.PatchTraces</c> and
/// <c>TraceServiceClient.PatchTracesAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings PatchTracesSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>TraceServiceClient.GetTrace</c> and <c>TraceServiceClient.GetTraceAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>TraceServiceClient.GetTrace</c> and
/// <c>TraceServiceClient.GetTraceAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings GetTraceSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>TraceServiceClient.ListTraces</c> and <c>TraceServiceClient.ListTracesAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>TraceServiceClient.ListTraces</c> and
/// <c>TraceServiceClient.ListTracesAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.2</description></item>
/// <item><description>Retry maximum delay: 1000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.5</description></item>
/// <item><description>Timeout maximum delay: 30000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 45000 milliseconds.
/// </remarks>
public CallSettings ListTracesSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(45000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="TraceServiceSettings"/> object.</returns>
public TraceServiceSettings Clone() => new TraceServiceSettings(this);
}
/// <summary>
/// TraceService client wrapper, for convenient use.
/// </summary>
public abstract partial class TraceServiceClient
{
/// <summary>
/// The default endpoint for the TraceService service, which is a host of "cloudtrace.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("cloudtrace.googleapis.com", 443);
/// <summary>
/// The default TraceService scopes.
/// </summary>
/// <remarks>
/// The default TraceService scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// <item><description>"https://www.googleapis.com/auth/trace.append"</description></item>
/// <item><description>"https://www.googleapis.com/auth/trace.readonly"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/trace.append",
"https://www.googleapis.com/auth/trace.readonly",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="TraceServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="TraceServiceSettings"/>.</param>
/// <returns>The task representing the created <see cref="TraceServiceClient"/>.</returns>
public static async Task<TraceServiceClient> CreateAsync(ServiceEndpoint endpoint = null, TraceServiceSettings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="TraceServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="TraceServiceSettings"/>.</param>
/// <returns>The created <see cref="TraceServiceClient"/>.</returns>
public static TraceServiceClient Create(ServiceEndpoint endpoint = null, TraceServiceSettings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="TraceServiceClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="TraceServiceSettings"/>.</param>
/// <returns>The created <see cref="TraceServiceClient"/>.</returns>
public static TraceServiceClient Create(Channel channel, TraceServiceSettings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
TraceService.TraceServiceClient grpcClient = new TraceService.TraceServiceClient(channel);
return new TraceServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, TraceServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, TraceServiceSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, TraceServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, TraceServiceSettings)"/> 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 Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC TraceService client.
/// </summary>
public virtual TraceService.TraceServiceClient GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traces">
/// The body of the message.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task PatchTracesAsync(
string projectId,
Traces traces,
CallSettings callSettings = null) => PatchTracesAsync(
new PatchTracesRequest
{
ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Traces = GaxPreconditions.CheckNotNull(traces, nameof(traces)),
},
callSettings);
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traces">
/// The body of the message.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task PatchTracesAsync(
string projectId,
Traces traces,
CancellationToken cancellationToken) => PatchTracesAsync(
projectId,
traces,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traces">
/// The body of the message.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual void PatchTraces(
string projectId,
Traces traces,
CallSettings callSettings = null) => PatchTraces(
new PatchTracesRequest
{
ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
Traces = GaxPreconditions.CheckNotNull(traces, nameof(traces)),
},
callSettings);
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </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 Task PatchTracesAsync(
PatchTracesRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </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 void PatchTraces(
PatchTracesRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traceId">
/// ID of the trace to return.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<Trace> GetTraceAsync(
string projectId,
string traceId,
CallSettings callSettings = null) => GetTraceAsync(
new GetTraceRequest
{
ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
TraceId = GaxPreconditions.CheckNotNullOrEmpty(traceId, nameof(traceId)),
},
callSettings);
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traceId">
/// ID of the trace to return.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<Trace> GetTraceAsync(
string projectId,
string traceId,
CancellationToken cancellationToken) => GetTraceAsync(
projectId,
traceId,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets a single trace by its ID.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="traceId">
/// ID of the trace to return.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual Trace GetTrace(
string projectId,
string traceId,
CallSettings callSettings = null) => GetTrace(
new GetTraceRequest
{
ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
TraceId = GaxPreconditions.CheckNotNullOrEmpty(traceId, nameof(traceId)),
},
callSettings);
/// <summary>
/// Gets a single trace by its ID.
/// </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 Task<Trace> GetTraceAsync(
GetTraceRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets a single trace by its ID.
/// </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 Trace GetTrace(
GetTraceRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="Trace"/> resources.
/// </returns>
public virtual PagedAsyncEnumerable<ListTracesResponse, Trace> ListTracesAsync(
string projectId,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null) => ListTracesAsync(
new ListTracesRequest
{
ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
},
callSettings);
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </summary>
/// <param name="projectId">
/// ID of the Cloud project where the trace data is stored.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="Trace"/> resources.
/// </returns>
public virtual PagedEnumerable<ListTracesResponse, Trace> ListTraces(
string projectId,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null) => ListTraces(
new ListTracesRequest
{
ProjectId = GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
},
callSettings);
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </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 pageable asynchronous sequence of <see cref="Trace"/> resources.
/// </returns>
public virtual PagedAsyncEnumerable<ListTracesResponse, Trace> ListTracesAsync(
ListTracesRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </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 pageable sequence of <see cref="Trace"/> resources.
/// </returns>
public virtual PagedEnumerable<ListTracesResponse, Trace> ListTraces(
ListTracesRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// TraceService client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class TraceServiceClientImpl : TraceServiceClient
{
private readonly ApiCall<PatchTracesRequest, Empty> _callPatchTraces;
private readonly ApiCall<GetTraceRequest, Trace> _callGetTrace;
private readonly ApiCall<ListTracesRequest, ListTracesResponse> _callListTraces;
/// <summary>
/// Constructs a client wrapper for the TraceService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="TraceServiceSettings"/> used within this client </param>
public TraceServiceClientImpl(TraceService.TraceServiceClient grpcClient, TraceServiceSettings settings)
{
this.GrpcClient = grpcClient;
TraceServiceSettings effectiveSettings = settings ?? TraceServiceSettings.GetDefault();
ClientHelper clientHelper = new ClientHelper(effectiveSettings);
_callPatchTraces = clientHelper.BuildApiCall<PatchTracesRequest, Empty>(
GrpcClient.PatchTracesAsync, GrpcClient.PatchTraces, effectiveSettings.PatchTracesSettings);
_callGetTrace = clientHelper.BuildApiCall<GetTraceRequest, Trace>(
GrpcClient.GetTraceAsync, GrpcClient.GetTrace, effectiveSettings.GetTraceSettings);
_callListTraces = clientHelper.BuildApiCall<ListTracesRequest, ListTracesResponse>(
GrpcClient.ListTracesAsync, GrpcClient.ListTraces, effectiveSettings.ListTracesSettings);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void OnConstruction(TraceService.TraceServiceClient grpcClient, TraceServiceSettings effectiveSettings, ClientHelper clientHelper);
/// <summary>
/// The underlying gRPC TraceService client.
/// </summary>
public override TraceService.TraceServiceClient GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_PatchTracesRequest(ref PatchTracesRequest request, ref CallSettings settings);
partial void Modify_GetTraceRequest(ref GetTraceRequest request, ref CallSettings settings);
partial void Modify_ListTracesRequest(ref ListTracesRequest request, ref CallSettings settings);
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </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 Task PatchTracesAsync(
PatchTracesRequest request,
CallSettings callSettings = null)
{
Modify_PatchTracesRequest(ref request, ref callSettings);
return _callPatchTraces.Async(request, callSettings);
}
/// <summary>
/// Sends new traces to Stackdriver Trace or updates existing traces. If the ID
/// of a trace that you send matches that of an existing trace, any fields
/// in the existing trace and its spans are overwritten by the provided values,
/// and any new fields provided are merged with the existing trace data. If the
/// ID does not match, a new trace is created.
/// </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 void PatchTraces(
PatchTracesRequest request,
CallSettings callSettings = null)
{
Modify_PatchTracesRequest(ref request, ref callSettings);
_callPatchTraces.Sync(request, callSettings);
}
/// <summary>
/// Gets a single trace by its ID.
/// </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 Task<Trace> GetTraceAsync(
GetTraceRequest request,
CallSettings callSettings = null)
{
Modify_GetTraceRequest(ref request, ref callSettings);
return _callGetTrace.Async(request, callSettings);
}
/// <summary>
/// Gets a single trace by its ID.
/// </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 Trace GetTrace(
GetTraceRequest request,
CallSettings callSettings = null)
{
Modify_GetTraceRequest(ref request, ref callSettings);
return _callGetTrace.Sync(request, callSettings);
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </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 pageable asynchronous sequence of <see cref="Trace"/> resources.
/// </returns>
public override PagedAsyncEnumerable<ListTracesResponse, Trace> ListTracesAsync(
ListTracesRequest request,
CallSettings callSettings = null)
{
Modify_ListTracesRequest(ref request, ref callSettings);
return new GrpcPagedAsyncEnumerable<ListTracesRequest, ListTracesResponse, Trace>(_callListTraces, request, callSettings);
}
/// <summary>
/// Returns of a list of traces that match the specified filter conditions.
/// </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 pageable sequence of <see cref="Trace"/> resources.
/// </returns>
public override PagedEnumerable<ListTracesResponse, Trace> ListTraces(
ListTracesRequest request,
CallSettings callSettings = null)
{
Modify_ListTracesRequest(ref request, ref callSettings);
return new GrpcPagedEnumerable<ListTracesRequest, ListTracesResponse, Trace>(_callListTraces, request, callSettings);
}
}
// Partial classes to enable page-streaming
public partial class ListTracesRequest : IPageRequest { }
public partial class ListTracesResponse : IPageResponse<Trace>
{
/// <summary>
/// Returns an enumerator that iterates through the resources in this response.
/// </summary>
public IEnumerator<Trace> GetEnumerator() => Traces.GetEnumerator();
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// Container for the parameters to the DescribeScheduledActions operation.
/// <para> Lists all the actions scheduled for your Auto Scaling group that haven't been executed. To see a list of actions already executed,
/// see the activity record returned in DescribeScalingActivities. </para>
/// </summary>
/// <seealso cref="Amazon.AutoScaling.AmazonAutoScaling.DescribeScheduledActions"/>
public class DescribeScheduledActionsRequest : AmazonWebServiceRequest
{
private string autoScalingGroupName;
private List<string> scheduledActionNames = new List<string>();
private DateTime? startTime;
private DateTime? endTime;
private string nextToken;
private int? maxRecords;
/// <summary>
/// The name of the Auto Scaling group.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 1600</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string AutoScalingGroupName
{
get { return this.autoScalingGroupName; }
set { this.autoScalingGroupName = value; }
}
/// <summary>
/// Sets the AutoScalingGroupName property
/// </summary>
/// <param name="autoScalingGroupName">The value to set for the AutoScalingGroupName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeScheduledActionsRequest WithAutoScalingGroupName(string autoScalingGroupName)
{
this.autoScalingGroupName = autoScalingGroupName;
return this;
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this.autoScalingGroupName != null;
}
/// <summary>
/// A list of scheduled actions to be described. If this list is omitted, all scheduled actions are described. The list of requested scheduled
/// actions cannot contain more than 50 items. If an auto scaling group name is provided, the results are limited to that group. If unknown
/// scheduled actions are requested, they are ignored with no error.
///
/// </summary>
public List<string> ScheduledActionNames
{
get { return this.scheduledActionNames; }
set { this.scheduledActionNames = value; }
}
/// <summary>
/// Adds elements to the ScheduledActionNames collection
/// </summary>
/// <param name="scheduledActionNames">The values to add to the ScheduledActionNames collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeScheduledActionsRequest WithScheduledActionNames(params string[] scheduledActionNames)
{
foreach (string element in scheduledActionNames)
{
this.scheduledActionNames.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the ScheduledActionNames collection
/// </summary>
/// <param name="scheduledActionNames">The values to add to the ScheduledActionNames collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeScheduledActionsRequest WithScheduledActionNames(IEnumerable<string> scheduledActionNames)
{
foreach (string element in scheduledActionNames)
{
this.scheduledActionNames.Add(element);
}
return this;
}
// Check to see if ScheduledActionNames property is set
internal bool IsSetScheduledActionNames()
{
return this.scheduledActionNames.Count > 0;
}
/// <summary>
/// The earliest scheduled start time to return. If scheduled action names are provided, this field will be ignored.
///
/// </summary>
public DateTime StartTime
{
get { return this.startTime ?? default(DateTime); }
set { this.startTime = value; }
}
/// <summary>
/// Sets the StartTime property
/// </summary>
/// <param name="startTime">The value to set for the StartTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeScheduledActionsRequest WithStartTime(DateTime startTime)
{
this.startTime = startTime;
return this;
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this.startTime.HasValue;
}
/// <summary>
/// The latest scheduled start time to return. If scheduled action names are provided, this field is ignored.
///
/// </summary>
public DateTime EndTime
{
get { return this.endTime ?? default(DateTime); }
set { this.endTime = value; }
}
/// <summary>
/// Sets the EndTime property
/// </summary>
/// <param name="endTime">The value to set for the EndTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeScheduledActionsRequest WithEndTime(DateTime endTime)
{
this.endTime = endTime;
return this;
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this.endTime.HasValue;
}
/// <summary>
/// A string that marks the start of the next batch of returned results.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string NextToken
{
get { return this.nextToken; }
set { this.nextToken = value; }
}
/// <summary>
/// Sets the NextToken property
/// </summary>
/// <param name="nextToken">The value to set for the NextToken property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeScheduledActionsRequest WithNextToken(string nextToken)
{
this.nextToken = nextToken;
return this;
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this.nextToken != null;
}
/// <summary>
/// The maximum number of scheduled actions to return.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>1 - 50</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int MaxRecords
{
get { return this.maxRecords ?? default(int); }
set { this.maxRecords = value; }
}
/// <summary>
/// Sets the MaxRecords property
/// </summary>
/// <param name="maxRecords">The value to set for the MaxRecords property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeScheduledActionsRequest WithMaxRecords(int maxRecords)
{
this.maxRecords = maxRecords;
return this;
}
// Check to see if MaxRecords property is set
internal bool IsSetMaxRecords()
{
return this.maxRecords.HasValue;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataGridViewTopLeftHeaderCell.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms
{
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms.VisualStyles;
using System.ComponentModel;
using System.Windows.Forms.Internal;
using System.Security.Permissions;
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCell"]/*' />
/// <devdoc>
/// <para></para>
/// </devdoc>
public class DataGridViewTopLeftHeaderCell : DataGridViewColumnHeaderCell
{
private static readonly VisualStyleElement HeaderElement = VisualStyleElement.Header.Item.Normal;
private const byte DATAGRIDVIEWTOPLEFTHEADERCELL_horizontalTextMarginLeft = 1;
private const byte DATAGRIDVIEWTOPLEFTHEADERCELL_horizontalTextMarginRight = 2;
private const byte DATAGRIDVIEWTOPLEFTHEADERCELL_verticalTextMargin = 1;
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCell.DataGridViewTopLeftHeaderCell"]/*' />
public DataGridViewTopLeftHeaderCell()
{
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCell.CreateAccessibilityInstance"]/*' />
protected override AccessibleObject CreateAccessibilityInstance()
{
return new DataGridViewTopLeftHeaderCellAccessibleObject(this);
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCell.GetContentBounds"]/*' />
protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
{
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
if (rowIndex != -1)
{
throw new ArgumentOutOfRangeException("rowIndex");
}
if (this.DataGridView == null)
{
return Rectangle.Empty;
}
object value = GetValue(rowIndex);
// Intentionally not using GetFormattedValue because header cells don't typically perform formatting.
// the content bounds are computed on demand
// we mimic a lot of the painting code
// get the borders
DataGridViewAdvancedBorderStyle dgvabsEffective;
DataGridViewElementStates cellState;
Rectangle cellBounds;
ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds);
Rectangle contentBounds = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
value,
null /*errorText*/, // contentBounds is independent of errorText
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
true /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
false /*paint*/);
#if DEBUG
Rectangle contentBoundsDebug = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
value,
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
true /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
false /*paint*/);
Debug.Assert(contentBoundsDebug.Equals(contentBounds));
#endif
return contentBounds;
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCell.GetErrorIconBounds"]/*' />
protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
{
if (rowIndex != -1)
{
throw new ArgumentOutOfRangeException("rowIndex");
}
if (this.DataGridView == null)
{
return Rectangle.Empty;
}
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
DataGridViewAdvancedBorderStyle dgvabsEffective;
DataGridViewElementStates cellState;
Rectangle cellBounds;
ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds);
Rectangle errorBounds = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
null /*formattedValue*/, // errorIconBounds is independent of formattedValue
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
false /*computeContentBounds*/,
true /*computeErrorIconBounds*/,
false /*paint*/);
#if DEBUG
object value = GetValue(rowIndex);
Rectangle errorBoundsDebug = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
value,
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
false /*computeContentBounds*/,
true /*computeErrorIconBounds*/,
false /*paint*/);
Debug.Assert(errorBoundsDebug.Equals(errorBounds));
#endif
return errorBounds;
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCell.GetPreferredSize"]/*' />
protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
{
if (rowIndex != -1)
{
throw new ArgumentOutOfRangeException("rowIndex");
}
if (this.DataGridView == null)
{
return new Size(-1, -1);
}
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
Rectangle borderWidthsRect = BorderWidths(this.DataGridView.AdjustedTopLeftHeaderBorderStyle);
int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal;
int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical;
TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
// Intentionally not using GetFormattedValue because header cells don't typically perform formatting.
object val = GetValue(rowIndex);
if (!(val is string))
{
val = null;
}
return DataGridViewUtilities.GetPreferredRowHeaderSize(graphics,
(string) val,
cellStyle,
borderAndPaddingWidths,
borderAndPaddingHeights,
this.DataGridView.ShowCellErrors,
false /*showGlyph*/,
constraintSize,
flags);
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCell.Paint"]/*' />
protected override void Paint(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates cellState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
PaintPrivate(graphics,
clipBounds,
cellBounds,
rowIndex,
cellState,
formattedValue,
errorText,
cellStyle,
advancedBorderStyle,
paintParts,
false /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
true /*paint*/);
}
// PaintPrivate is used in three places that need to duplicate the paint code:
// 1. DataGridViewCell::Paint method
// 2. DataGridViewCell::GetContentBounds
// 3. DataGridViewCell::GetErrorIconBounds
//
// if computeContentBounds is true then PaintPrivate returns the contentBounds
// else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds
// else it returns Rectangle.Empty;
private Rectangle PaintPrivate(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates cellState,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts,
bool computeContentBounds,
bool computeErrorIconBounds,
bool paint)
{
// Parameter checking.
// One bit and one bit only should be turned on
Debug.Assert(paint || computeContentBounds || computeErrorIconBounds);
Debug.Assert(!paint || !computeContentBounds || !computeErrorIconBounds);
Debug.Assert(!computeContentBounds || !computeErrorIconBounds || !paint);
Debug.Assert(!computeErrorIconBounds || !paint || !computeContentBounds);
Debug.Assert(cellStyle != null);
// If computeContentBounds == TRUE then resultBounds will be the contentBounds.
// If computeErrorIconBounds == TRUE then resultBounds will be the error icon bounds.
// Else resultBounds will be Rectangle.Empty;
Rectangle resultBounds = Rectangle.Empty;
Rectangle valBounds = cellBounds;
Rectangle borderWidths = BorderWidths(advancedBorderStyle);
valBounds.Offset(borderWidths.X, borderWidths.Y);
valBounds.Width -= borderWidths.Right;
valBounds.Height -= borderWidths.Bottom;
bool cellSelected = (cellState & DataGridViewElementStates.Selected) != 0;
if (paint && DataGridViewCell.PaintBackground(paintParts))
{
if (this.DataGridView.ApplyVisualStylesToHeaderCells)
{
// XP Theming
int state = (int)HeaderItemState.Normal;
if (this.ButtonState != ButtonState.Normal)
{
Debug.Assert(this.ButtonState == ButtonState.Pushed);
state = (int)HeaderItemState.Pressed;
}
else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex)
{
state = (int)HeaderItemState.Hot;
}
valBounds.Inflate(16, 16);
DataGridViewTopLeftHeaderCellRenderer.DrawHeader(graphics, valBounds, state);
valBounds.Inflate(-16, -16);
}
else
{
SolidBrush br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor);
if (br.Color.A == 255)
{
graphics.FillRectangle(br, valBounds);
}
}
}
if (paint && DataGridViewCell.PaintBorder(paintParts))
{
PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
}
if (cellStyle.Padding != Padding.Empty)
{
if (this.DataGridView.RightToLeftInternal)
{
valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
}
else
{
valBounds.Offset(cellStyle.Padding.Left, cellStyle.Padding.Top);
}
valBounds.Width -= cellStyle.Padding.Horizontal;
valBounds.Height -= cellStyle.Padding.Vertical;
}
Rectangle errorBounds = valBounds;
string formattedValueStr = formattedValue as string;
// Font independent margins
valBounds.Offset(DATAGRIDVIEWTOPLEFTHEADERCELL_horizontalTextMarginLeft, DATAGRIDVIEWTOPLEFTHEADERCELL_verticalTextMargin);
valBounds.Width -= DATAGRIDVIEWTOPLEFTHEADERCELL_horizontalTextMarginLeft + DATAGRIDVIEWTOPLEFTHEADERCELL_horizontalTextMarginRight;
valBounds.Height -= 2 * DATAGRIDVIEWTOPLEFTHEADERCELL_verticalTextMargin;
if (valBounds.Width > 0 &&
valBounds.Height > 0 &&
!String.IsNullOrEmpty(formattedValueStr) &&
(paint || computeContentBounds))
{
Color textColor;
if (this.DataGridView.ApplyVisualStylesToHeaderCells)
{
textColor = DataGridViewTopLeftHeaderCellRenderer.VisualStyleRenderer.GetColor(ColorProperty.TextColor);
}
else
{
textColor = cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor;
}
TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
if (paint)
{
if (DataGridViewCell.PaintContentForeground(paintParts))
{
if ((flags & TextFormatFlags.SingleLine) != 0)
{
flags |= TextFormatFlags.EndEllipsis;
}
TextRenderer.DrawText(graphics,
formattedValueStr,
cellStyle.Font,
valBounds,
textColor,
flags);
}
}
else
{
Debug.Assert(computeContentBounds);
resultBounds = DataGridViewUtilities.GetTextBounds(valBounds, formattedValueStr, flags, cellStyle);
}
}
else if (computeErrorIconBounds && !String.IsNullOrEmpty(errorText))
{
resultBounds = ComputeErrorIconBounds(errorBounds);
}
if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts))
{
PaintErrorIcon(graphics, cellStyle, rowIndex, cellBounds, errorBounds, errorText);
}
return resultBounds;
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCell.PaintBorder"]/*' />
protected override void PaintBorder(Graphics graphics,
Rectangle clipBounds,
Rectangle bounds,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle)
{
if (this.DataGridView == null)
{
return;
}
base.PaintBorder(graphics, clipBounds, bounds, cellStyle, advancedBorderStyle);
if (!this.DataGridView.RightToLeftInternal &&
this.DataGridView.ApplyVisualStylesToHeaderCells)
{
if (this.DataGridView.AdvancedColumnHeadersBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Inset)
{
Pen penControlDark = null, penControlLightLight = null;
GetContrastedPens(cellStyle.BackColor, ref penControlDark, ref penControlLightLight);
graphics.DrawLine(penControlDark, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
graphics.DrawLine(penControlDark, bounds.X, bounds.Y, bounds.Right - 1, bounds.Y);
}
else if (this.DataGridView.AdvancedColumnHeadersBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Outset)
{
Pen penControlDark = null, penControlLightLight = null;
GetContrastedPens(cellStyle.BackColor, ref penControlDark, ref penControlLightLight);
graphics.DrawLine(penControlLightLight, bounds.X, bounds.Y, bounds.X, bounds.Bottom - 1);
graphics.DrawLine(penControlLightLight, bounds.X, bounds.Y, bounds.Right - 1, bounds.Y);
}
else if (this.DataGridView.AdvancedColumnHeadersBorderStyle.All == DataGridViewAdvancedCellBorderStyle.InsetDouble)
{
Pen penControlDark = null, penControlLightLight = null;
GetContrastedPens(cellStyle.BackColor, ref penControlDark, ref penControlLightLight);
graphics.DrawLine(penControlDark, bounds.X + 1, bounds.Y + 1, bounds.X + 1, bounds.Bottom - 1);
graphics.DrawLine(penControlDark, bounds.X + 1, bounds.Y + 1, bounds.Right - 1, bounds.Y + 1);
}
}
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCell.ToString"]/*' />
/// <devdoc>
/// <para></para>
/// </devdoc>
public override string ToString()
{
return "DataGridViewTopLeftHeaderCell";
}
private class DataGridViewTopLeftHeaderCellRenderer
{
private static VisualStyleRenderer visualStyleRenderer;
private DataGridViewTopLeftHeaderCellRenderer()
{
}
public static VisualStyleRenderer VisualStyleRenderer
{
get
{
if (visualStyleRenderer == null)
{
visualStyleRenderer = new VisualStyleRenderer(HeaderElement);
}
return visualStyleRenderer;
}
}
public static void DrawHeader(Graphics g, Rectangle bounds, int headerState)
{
VisualStyleRenderer.SetParameters(HeaderElement.ClassName, HeaderElement.Part, headerState);
VisualStyleRenderer.DrawBackground(g, bounds, Rectangle.Truncate(g.ClipBounds));
}
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCellAccessibleObject"]/*' />
protected class DataGridViewTopLeftHeaderCellAccessibleObject : DataGridViewColumnHeaderCellAccessibleObject
{
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCellAccessibleObject.DataGridViewTopLeftHeaderCellAccessibleObject"]/*' />
public DataGridViewTopLeftHeaderCellAccessibleObject(DataGridViewTopLeftHeaderCell owner) : base (owner)
{
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCellAccessibleObject.Bounds"]/*' />
public override Rectangle Bounds
{
get
{
Rectangle cellRect = this.Owner.DataGridView.GetCellDisplayRectangle(-1, -1, false /*cutOverflow*/);
return this.Owner.DataGridView.RectangleToScreen(cellRect);
}
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCellAccessibleObject.DefaultAction"]/*' />
public override string DefaultAction
{
get
{
if (this.Owner.DataGridView.MultiSelect)
{
return SR.GetString(SR.DataGridView_AccTopLeftColumnHeaderCellDefaultAction);
}
else
{
return String.Empty;
}
}
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCellAccessibleObject.Name"]/*' />
public override string Name
{
get
{
object value = this.Owner.Value;
if (value != null && !(value is String))
{
// The user set the Value on the DataGridViewTopLeftHeaderCell and it did not set it to a string.
// Then the name of the DataGridViewTopLeftHeaderAccessibleObject is String.Empty;
//
return String.Empty;
}
string strValue = value as string;
if (String.IsNullOrEmpty(strValue))
{
if (this.Owner.DataGridView != null)
{
if (this.Owner.DataGridView.RightToLeft == RightToLeft.No)
{
return SR.GetString(SR.DataGridView_AccTopLeftColumnHeaderCellName);
}
else
{
return SR.GetString(SR.DataGridView_AccTopLeftColumnHeaderCellNameRTL);
}
}
else
{
return String.Empty;
}
}
else
{
return String.Empty;
}
}
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCellAccessibleObject.Value"]/*' />
public override AccessibleStates State
{
get
{
AccessibleStates resultState = AccessibleStates.Selectable;
// get the Offscreen state from the base method.
AccessibleStates state = base.State;
if ((state & AccessibleStates.Offscreen) == AccessibleStates.Offscreen)
{
resultState |= AccessibleStates.Offscreen;
}
// If all the cells are selected, then the top left header cell accessible object is considered to be selected as well.
if (this.Owner.DataGridView.AreAllCellsSelected(false /*includeInvisibleCells*/))
{
resultState |= AccessibleStates.Selected;
}
return resultState;
}
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCellAccessibleObject.Value"]/*' />
public override string Value
{
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
// We changed DataGridViewTopLeftHeaderCellAccessibleObject::Name to return a string : vsw 393122
// However, DataGridViewTopLeftHeaderCellAccessibleObject::Value should still return String.Empty.
return String.Empty;
}
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCellAccessibleObject.DoDefaultAction"]/*' />
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override void DoDefaultAction()
{
this.Owner.DataGridView.SelectAll();
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCellAccessibleObject.Navigate"]/*' />
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override AccessibleObject Navigate(AccessibleNavigation navigationDirection)
{
Debug.Assert(this.Owner.DataGridView.RowHeadersVisible, "if the row headers are not visible how did you get the top left header cell acc object?");
switch (navigationDirection)
{
case AccessibleNavigation.Previous:
return null;
case AccessibleNavigation.Left:
if (this.Owner.DataGridView.RightToLeft == RightToLeft.No)
{
return null;
}
else
{
return NavigateForward();
}
case AccessibleNavigation.Next:
return NavigateForward();
case AccessibleNavigation.Right:
if (this.Owner.DataGridView.RightToLeft == RightToLeft.No)
{
return NavigateForward();
}
else
{
return null;
}
default:
return null;
}
}
private AccessibleObject NavigateForward()
{
if (this.Owner.DataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible) == 0)
{
return null;
}
// return the acc object for the first visible column
return this.Owner.DataGridView.AccessibilityObject.GetChild(0).GetChild(1);
}
/// <include file='doc\DataGridViewTopLeftHeaderCell.uex' path='docs/doc[@for="DataGridViewTopLeftHeaderCellAccessibleObject.Select"]/*' />
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override void Select(AccessibleSelection flags)
{
if (this.Owner == null)
{
throw new InvalidOperationException(SR.GetString(SR.DataGridViewCellAccessibleObject_OwnerNotSet));
}
// AccessibleSelection.TakeFocus should focus the grid and then focus the first data grid view data cell
if ((flags & AccessibleSelection.TakeFocus) == AccessibleSelection.TakeFocus)
{
// Focus the grid
this.Owner.DataGridView.FocusInternal();
if (this.Owner.DataGridView.Columns.GetColumnCount(DataGridViewElementStates.Visible) > 0 &&
this.Owner.DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible) > 0)
{
// This means that there are visible rows and columns.
// Focus the first data cell.
DataGridViewRow row = this.Owner.DataGridView.Rows[this.Owner.DataGridView.Rows.GetFirstRow(DataGridViewElementStates.Visible)];
DataGridViewColumn col = this.Owner.DataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
// DataGridView::set_CurrentCell clears the previous selection.
// So use SetCurrenCellAddressCore directly.
this.Owner.DataGridView.SetCurrentCellAddressCoreInternal(col.Index, row.Index, false /*setAnchorCellAddress*/, true /*validateCurrentCell*/, false /*thoughMouseClick*/);
}
}
// AddSelection selects the entire grid.
if ((flags & AccessibleSelection.AddSelection) == AccessibleSelection.AddSelection)
{
if (this.Owner.DataGridView.MultiSelect)
{
this.Owner.DataGridView.SelectAll();
}
}
// RemoveSelection clears the selection on the entire grid.
// But only if AddSelection is not set.
if ((flags & AccessibleSelection.RemoveSelection) == AccessibleSelection.RemoveSelection &&
(flags & AccessibleSelection.AddSelection) == 0)
{
this.Owner.DataGridView.ClearSelection();
}
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmRPpriceCompare
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmRPpriceCompare() : base()
{
KeyPress += frmRPpriceCompare_KeyPress;
Load += frmRPpriceCompare_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.TextBox withEventsField_txtAbove;
public System.Windows.Forms.TextBox txtAbove {
get { return withEventsField_txtAbove; }
set {
if (withEventsField_txtAbove != null) {
withEventsField_txtAbove.Enter -= txtAbove_Enter;
withEventsField_txtAbove.KeyPress -= txtAbove_KeyPress;
withEventsField_txtAbove.Leave -= txtAbove_Leave;
}
withEventsField_txtAbove = value;
if (withEventsField_txtAbove != null) {
withEventsField_txtAbove.Enter += txtAbove_Enter;
withEventsField_txtAbove.KeyPress += txtAbove_KeyPress;
withEventsField_txtAbove.Leave += txtAbove_Leave;
}
}
}
public System.Windows.Forms.CheckBox chkAbove;
public System.Windows.Forms.TextBox txtBelow;
public System.Windows.Forms.CheckBox chkBelow;
private System.Windows.Forms.CheckBox withEventsField_chkQuantity;
public System.Windows.Forms.CheckBox chkQuantity {
get { return withEventsField_chkQuantity; }
set {
if (withEventsField_chkQuantity != null) {
withEventsField_chkQuantity.CheckStateChanged -= chkQuantity_CheckStateChanged;
}
withEventsField_chkQuantity = value;
if (withEventsField_chkQuantity != null) {
withEventsField_chkQuantity.CheckStateChanged += chkQuantity_CheckStateChanged;
}
}
}
public System.Windows.Forms.CheckBox chkDifferent;
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdPrint;
public System.Windows.Forms.Button cmdPrint {
get { return withEventsField_cmdPrint; }
set {
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click -= cmdPrint_Click;
}
withEventsField_cmdPrint = value;
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click += cmdPrint_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdNamespace;
public System.Windows.Forms.Button cmdNamespace {
get { return withEventsField_cmdNamespace; }
set {
if (withEventsField_cmdNamespace != null) {
withEventsField_cmdNamespace.Click -= cmdNamespace_Click;
}
withEventsField_cmdNamespace = value;
if (withEventsField_cmdNamespace != null) {
withEventsField_cmdNamespace.Click += cmdNamespace_Click;
}
}
}
private myDataGridView withEventsField_cmbChannel;
public myDataGridView cmbChannel {
get { return withEventsField_cmbChannel; }
set {
if (withEventsField_cmbChannel != null) {
withEventsField_cmbChannel.KeyPress -= cmbChannel_KeyPress;
}
withEventsField_cmbChannel = value;
if (withEventsField_cmbChannel != null) {
withEventsField_cmbChannel.KeyPress += cmbChannel_KeyPress;
}
}
}
private myDataGridView withEventsField_cmbShrink;
public myDataGridView cmbShrink {
get { return withEventsField_cmbShrink; }
set {
if (withEventsField_cmbShrink != null) {
withEventsField_cmbShrink.KeyPress -= cmbShrink_KeyPress;
}
withEventsField_cmbShrink = value;
if (withEventsField_cmbShrink != null) {
withEventsField_cmbShrink.KeyPress += cmbShrink_KeyPress;
}
}
}
public System.Windows.Forms.Label _lbl_2;
public System.Windows.Forms.Label _lbl_1;
public System.Windows.Forms.Label lblHeading;
public System.Windows.Forms.Label _lbl_0;
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmRPpriceCompare));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.txtAbove = new System.Windows.Forms.TextBox();
this.chkAbove = new System.Windows.Forms.CheckBox();
this.txtBelow = new System.Windows.Forms.TextBox();
this.chkBelow = new System.Windows.Forms.CheckBox();
this.chkQuantity = new System.Windows.Forms.CheckBox();
this.chkDifferent = new System.Windows.Forms.CheckBox();
this.cmdExit = new System.Windows.Forms.Button();
this.cmdPrint = new System.Windows.Forms.Button();
this.cmdNamespace = new System.Windows.Forms.Button();
this.cmbChannel = new myDataGridView();
this.cmbShrink = new myDataGridView();
this._lbl_2 = new System.Windows.Forms.Label();
this._lbl_1 = new System.Windows.Forms.Label();
this.lblHeading = new System.Windows.Forms.Label();
this._lbl_0 = new System.Windows.Forms.Label();
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.cmbChannel).BeginInit();
((System.ComponentModel.ISupportInitialize)this.cmbShrink).BeginInit();
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.Text = "Setup Price Comparison Report";
this.ClientSize = new System.Drawing.Size(462, 215);
this.Location = new System.Drawing.Point(4, 23);
this.ControlBox = false;
this.KeyPreview = true;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
this.Enabled = true;
this.MaximizeBox = true;
this.MinimizeBox = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmRPpriceCompare";
this.txtAbove.AutoSize = false;
this.txtAbove.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtAbove.Size = new System.Drawing.Size(28, 19);
this.txtAbove.Location = new System.Drawing.Point(252, 168);
this.txtAbove.TabIndex = 13;
this.txtAbove.Text = "0";
this.txtAbove.AcceptsReturn = true;
this.txtAbove.BackColor = System.Drawing.SystemColors.Window;
this.txtAbove.CausesValidation = true;
this.txtAbove.Enabled = true;
this.txtAbove.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtAbove.HideSelection = true;
this.txtAbove.ReadOnly = false;
this.txtAbove.MaxLength = 0;
this.txtAbove.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtAbove.Multiline = false;
this.txtAbove.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtAbove.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtAbove.TabStop = true;
this.txtAbove.Visible = true;
this.txtAbove.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtAbove.Name = "txtAbove";
this.chkAbove.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkAbove.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.chkAbove.Text = "Show stock Items where exit price above";
this.chkAbove.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkAbove.Size = new System.Drawing.Size(217, 13);
this.chkAbove.Location = new System.Drawing.Point(33, 171);
this.chkAbove.TabIndex = 12;
this.chkAbove.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkAbove.CausesValidation = true;
this.chkAbove.Enabled = true;
this.chkAbove.Cursor = System.Windows.Forms.Cursors.Default;
this.chkAbove.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkAbove.Appearance = System.Windows.Forms.Appearance.Normal;
this.chkAbove.TabStop = true;
this.chkAbove.CheckState = System.Windows.Forms.CheckState.Unchecked;
this.chkAbove.Visible = true;
this.chkAbove.Name = "chkAbove";
this.txtBelow.AutoSize = false;
this.txtBelow.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtBelow.Size = new System.Drawing.Size(28, 19);
this.txtBelow.Location = new System.Drawing.Point(252, 189);
this.txtBelow.TabIndex = 10;
this.txtBelow.Text = "0";
this.txtBelow.AcceptsReturn = true;
this.txtBelow.BackColor = System.Drawing.SystemColors.Window;
this.txtBelow.CausesValidation = true;
this.txtBelow.Enabled = true;
this.txtBelow.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtBelow.HideSelection = true;
this.txtBelow.ReadOnly = false;
this.txtBelow.MaxLength = 0;
this.txtBelow.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtBelow.Multiline = false;
this.txtBelow.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtBelow.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtBelow.TabStop = true;
this.txtBelow.Visible = true;
this.txtBelow.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtBelow.Name = "txtBelow";
this.chkBelow.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkBelow.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.chkBelow.Text = "Show stock Items where exit price below ";
this.chkBelow.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkBelow.Size = new System.Drawing.Size(217, 13);
this.chkBelow.Location = new System.Drawing.Point(33, 192);
this.chkBelow.TabIndex = 9;
this.chkBelow.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkBelow.CausesValidation = true;
this.chkBelow.Enabled = true;
this.chkBelow.Cursor = System.Windows.Forms.Cursors.Default;
this.chkBelow.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkBelow.Appearance = System.Windows.Forms.Appearance.Normal;
this.chkBelow.TabStop = true;
this.chkBelow.CheckState = System.Windows.Forms.CheckState.Unchecked;
this.chkBelow.Visible = true;
this.chkBelow.Name = "chkBelow";
this.chkQuantity.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkQuantity.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.chkQuantity.Text = "Show stock Items where quantity is exactly ";
this.chkQuantity.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkQuantity.Size = new System.Drawing.Size(226, 13);
this.chkQuantity.Location = new System.Drawing.Point(33, 141);
this.chkQuantity.TabIndex = 5;
this.chkQuantity.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkQuantity.CausesValidation = true;
this.chkQuantity.Enabled = true;
this.chkQuantity.Cursor = System.Windows.Forms.Cursors.Default;
this.chkQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkQuantity.Appearance = System.Windows.Forms.Appearance.Normal;
this.chkQuantity.TabStop = true;
this.chkQuantity.CheckState = System.Windows.Forms.CheckState.Unchecked;
this.chkQuantity.Visible = true;
this.chkQuantity.Name = "chkQuantity";
this.chkDifferent.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkDifferent.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.chkDifferent.Text = "Only show stock item where prices are different";
this.chkDifferent.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkDifferent.Size = new System.Drawing.Size(268, 13);
this.chkDifferent.Location = new System.Drawing.Point(33, 111);
this.chkDifferent.TabIndex = 4;
this.chkDifferent.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkDifferent.CausesValidation = true;
this.chkDifferent.Enabled = true;
this.chkDifferent.Cursor = System.Windows.Forms.Cursors.Default;
this.chkDifferent.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkDifferent.Appearance = System.Windows.Forms.Appearance.Normal;
this.chkDifferent.TabStop = true;
this.chkDifferent.CheckState = System.Windows.Forms.CheckState.Unchecked;
this.chkDifferent.Visible = true;
this.chkDifferent.Name = "chkDifferent";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Size = new System.Drawing.Size(97, 52);
this.cmdExit.Location = new System.Drawing.Point(363, 156);
this.cmdExit.TabIndex = 8;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPrint.Text = "&Print";
this.cmdPrint.Size = new System.Drawing.Size(97, 52);
this.cmdPrint.Location = new System.Drawing.Point(363, 96);
this.cmdPrint.TabIndex = 7;
this.cmdPrint.BackColor = System.Drawing.SystemColors.Control;
this.cmdPrint.CausesValidation = true;
this.cmdPrint.Enabled = true;
this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPrint.TabStop = true;
this.cmdPrint.Name = "cmdPrint";
this.cmdNamespace.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNamespace.Text = "&Filter";
this.cmdNamespace.Size = new System.Drawing.Size(97, 52);
this.cmdNamespace.Location = new System.Drawing.Point(363, 3);
this.cmdNamespace.TabIndex = 1;
this.cmdNamespace.TabStop = false;
this.cmdNamespace.BackColor = System.Drawing.SystemColors.Control;
this.cmdNamespace.CausesValidation = true;
this.cmdNamespace.Enabled = true;
this.cmdNamespace.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNamespace.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNamespace.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNamespace.Name = "cmdNamespace";
//cmbChannel.OcxState = CType(resources.GetObject("cmbChannel.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbChannel.Size = new System.Drawing.Size(124, 21);
this.cmbChannel.Location = new System.Drawing.Point(153, 60);
this.cmbChannel.TabIndex = 3;
this.cmbChannel.Name = "cmbChannel";
//cmbShrink.OcxState = CType(resources.GetObject("cmbShrink.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbShrink.Size = new System.Drawing.Size(67, 21);
this.cmbShrink.Location = new System.Drawing.Point(261, 138);
this.cmbShrink.TabIndex = 6;
this.cmbShrink.Name = "cmbShrink";
this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_2.Text = "%";
this._lbl_2.Size = new System.Drawing.Size(11, 13);
this._lbl_2.Location = new System.Drawing.Point(282, 171);
this._lbl_2.TabIndex = 14;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Enabled = true;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.UseMnemonic = true;
this._lbl_2.Visible = true;
this._lbl_2.AutoSize = true;
this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_2.Name = "_lbl_2";
this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_1.Text = "%";
this._lbl_1.Size = new System.Drawing.Size(11, 13);
this._lbl_1.Location = new System.Drawing.Point(282, 192);
this._lbl_1.TabIndex = 11;
this._lbl_1.BackColor = System.Drawing.Color.Transparent;
this._lbl_1.Enabled = true;
this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_1.UseMnemonic = true;
this._lbl_1.Visible = true;
this._lbl_1.AutoSize = true;
this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_1.Name = "_lbl_1";
this.lblHeading.Text = "Using the \"Stock Item Selector\" .....";
this.lblHeading.Size = new System.Drawing.Size(349, 52);
this.lblHeading.Location = new System.Drawing.Point(3, 3);
this.lblHeading.TabIndex = 0;
this.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblHeading.BackColor = System.Drawing.SystemColors.Control;
this.lblHeading.Enabled = true;
this.lblHeading.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default;
this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblHeading.UseMnemonic = true;
this.lblHeading.Visible = true;
this.lblHeading.AutoSize = false;
this.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblHeading.Name = "lblHeading";
this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_0.Text = "For which Sale Channel";
this._lbl_0.Size = new System.Drawing.Size(112, 13);
this._lbl_0.Location = new System.Drawing.Point(34, 63);
this._lbl_0.TabIndex = 2;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Enabled = true;
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.UseMnemonic = true;
this._lbl_0.Visible = true;
this._lbl_0.AutoSize = true;
this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_0.Name = "_lbl_0";
this.Controls.Add(txtAbove);
this.Controls.Add(chkAbove);
this.Controls.Add(txtBelow);
this.Controls.Add(chkBelow);
this.Controls.Add(chkQuantity);
this.Controls.Add(chkDifferent);
this.Controls.Add(cmdExit);
this.Controls.Add(cmdPrint);
this.Controls.Add(cmdNamespace);
this.Controls.Add(cmbChannel);
this.Controls.Add(cmbShrink);
this.Controls.Add(_lbl_2);
this.Controls.Add(_lbl_1);
this.Controls.Add(lblHeading);
this.Controls.Add(_lbl_0);
//Me.lbl.SetIndex(_lbl_2, CType(2, Short))
//Me.lbl.SetIndex(_lbl_1, CType(1, Short))
//Me.lbl.SetIndex(_lbl_0, CType(0, Short))
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
((System.ComponentModel.ISupportInitialize)this.cmbShrink).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbChannel).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using pCampBot.Interfaces;
namespace pCampBot
{
public enum BotManagerBotConnectingState
{
Initializing,
Ready,
Connecting,
Disconnecting
}
/// <summary>
/// Thread/Bot manager for the application
/// </summary>
public class BotManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const int DefaultLoginDelay = 5000;
/// <summary>
/// Is pCampbot ready to connect or currently in the process of connecting or disconnecting bots?
/// </summary>
public BotManagerBotConnectingState BotConnectingState { get; private set; }
/// <summary>
/// Used to control locking as we can't lock an enum.
/// </summary>
private object BotConnectingStateChangeObject = new object();
/// <summary>
/// Delay between logins of multiple bots.
/// </summary>
/// <remarks>TODO: This value needs to be configurable by a command line argument.</remarks>
public int LoginDelay { get; set; }
/// <summary>
/// Command console
/// </summary>
protected CommandConsole m_console;
/// <summary>
/// Controls whether bots start out sending agent updates on connection.
/// </summary>
public bool InitBotSendAgentUpdates { get; set; }
/// <summary>
/// Controls whether bots request textures for the object information they receive
/// </summary>
public bool InitBotRequestObjectTextures { get; set; }
/// <summary>
/// Created bots, whether active or inactive.
/// </summary>
protected List<Bot> m_bots;
/// <summary>
/// Random number generator.
/// </summary>
public Random Rng { get; private set; }
/// <summary>
/// Track the assets we have and have not received so we don't endlessly repeat requests.
/// </summary>
public Dictionary<UUID, bool> AssetsReceived { get; private set; }
/// <summary>
/// The regions that we know about.
/// </summary>
public Dictionary<ulong, GridRegion> RegionsKnown { get; private set; }
/// <summary>
/// First name for bots
/// </summary>
private string m_firstName;
/// <summary>
/// Last name stem for bots
/// </summary>
private string m_lastNameStem;
/// <summary>
/// Password for bots
/// </summary>
private string m_password;
/// <summary>
/// Login URI for bots.
/// </summary>
private string m_loginUri;
/// <summary>
/// Start location for bots.
/// </summary>
private string m_startUri;
/// <summary>
/// Postfix bot number at which bot sequence starts.
/// </summary>
private int m_fromBotNumber;
/// <summary>
/// Wear setting for bots.
/// </summary>
private string m_wearSetting;
/// <summary>
/// Behaviour switches for bots.
/// </summary>
private HashSet<string> m_defaultBehaviourSwitches = new HashSet<string>();
/// <summary>
/// Collects general information on this server (which reveals this to be a misnamed class).
/// </summary>
private ServerStatsCollector m_serverStatsCollector;
/// <summary>
/// Constructor Creates MainConsole.Instance to take commands and provide the place to write data
/// </summary>
public BotManager()
{
// We set this to avoid issues with bots running out of HTTP connections if many are run from a single machine
// to multiple regions.
Settings.MAX_HTTP_CONNECTIONS = int.MaxValue;
// System.Threading.ThreadPool.SetMaxThreads(600, 240);
//
// int workerThreads, iocpThreads;
// System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
// Console.WriteLine("ThreadPool.GetMaxThreads {0} {1}", workerThreads, iocpThreads);
InitBotSendAgentUpdates = true;
InitBotRequestObjectTextures = true;
LoginDelay = DefaultLoginDelay;
Rng = new Random(Environment.TickCount);
AssetsReceived = new Dictionary<UUID, bool>();
RegionsKnown = new Dictionary<ulong, GridRegion>();
m_console = CreateConsole();
MainConsole.Instance = m_console;
// Make log4net see the console
//
ILoggerRepository repository = LogManager.GetRepository();
IAppender[] appenders = repository.GetAppenders();
OpenSimAppender consoleAppender = null;
foreach (IAppender appender in appenders)
{
if (appender.Name == "Console")
{
consoleAppender = (OpenSimAppender)appender;
consoleAppender.Console = m_console;
break;
}
}
m_console.Commands.AddCommand(
"Bots", false, "shutdown", "shutdown", "Shutdown bots and exit", HandleShutdown);
m_console.Commands.AddCommand(
"Bots", false, "quit", "quit", "Shutdown bots and exit", HandleShutdown);
m_console.Commands.AddCommand(
"Bots", false, "connect", "connect [<n>]", "Connect bots",
"If an <n> is given, then the first <n> disconnected bots by postfix number are connected.\n"
+ "If no <n> is given, then all currently disconnected bots are connected.",
HandleConnect);
m_console.Commands.AddCommand(
"Bots", false, "disconnect", "disconnect [<n>]", "Disconnect bots",
"Disconnecting bots will interupt any bot connection process, including connection on startup.\n"
+ "If an <n> is given, then the last <n> connected bots by postfix number are disconnected.\n"
+ "If no <n> is given, then all currently connected bots are disconnected.",
HandleDisconnect);
m_console.Commands.AddCommand(
"Bots", false, "add behaviour", "add behaviour <abbreviated-name> [<bot-number>]",
"Add a behaviour to a bot",
"If no bot number is specified then behaviour is added to all bots.\n"
+ "Can be performed on connected or disconnected bots.",
HandleAddBehaviour);
m_console.Commands.AddCommand(
"Bots", false, "remove behaviour", "remove behaviour <abbreviated-name> [<bot-number>]",
"Remove a behaviour from a bot",
"If no bot number is specified then behaviour is added to all bots.\n"
+ "Can be performed on connected or disconnected bots.",
HandleRemoveBehaviour);
m_console.Commands.AddCommand(
"Bots", false, "sit", "sit", "Sit all bots on the ground.",
HandleSit);
m_console.Commands.AddCommand(
"Bots", false, "stand", "stand", "Stand all bots.",
HandleStand);
m_console.Commands.AddCommand(
"Bots", false, "set bots", "set bots <key> <value>", "Set a setting for all bots.", HandleSetBots);
m_console.Commands.AddCommand(
"Bots", false, "show regions", "show regions", "Show regions known to bots", HandleShowRegions);
m_console.Commands.AddCommand(
"Bots", false, "show bots", "show bots", "Shows the status of all bots.", HandleShowBotsStatus);
m_console.Commands.AddCommand(
"Bots", false, "show bot", "show bot <bot-number>",
"Shows the detailed status and settings of a particular bot.", HandleShowBotStatus);
m_console.Commands.AddCommand(
"Debug",
false,
"debug lludp packet",
"debug lludp packet <level> <avatar-first-name> <avatar-last-name>",
"Turn on received packet logging.",
"If level > 0 then all received packets that are not duplicates are logged.\n"
+ "If level <= 0 then no received packets are logged.",
HandleDebugLludpPacketCommand);
m_console.Commands.AddCommand(
"Bots", false, "show status", "show status", "Shows pCampbot status.", HandleShowStatus);
m_bots = new List<Bot>();
Watchdog.Enabled = true;
StatsManager.RegisterConsoleCommands(m_console);
m_serverStatsCollector = new ServerStatsCollector();
m_serverStatsCollector.Initialise(null);
m_serverStatsCollector.Enabled = true;
m_serverStatsCollector.Start();
BotConnectingState = BotManagerBotConnectingState.Ready;
}
/// <summary>
/// Startup number of bots specified in the starting arguments
/// </summary>
/// <param name="botcount">How many bots to start up</param>
/// <param name="cs">The configuration for the bots to use</param>
public void CreateBots(int botcount, IConfig startupConfig)
{
m_firstName = startupConfig.GetString("firstname");
m_lastNameStem = startupConfig.GetString("lastname");
m_password = startupConfig.GetString("password");
m_loginUri = startupConfig.GetString("loginuri");
m_fromBotNumber = startupConfig.GetInt("from", 0);
m_wearSetting = startupConfig.GetString("wear", "no");
m_startUri = ParseInputStartLocationToUri(startupConfig.GetString("start", "last"));
Array.ForEach<string>(
startupConfig.GetString("behaviours", "p").Split(new char[] { ',' }), b => m_defaultBehaviourSwitches.Add(b));
for (int i = 0; i < botcount; i++)
{
lock (m_bots)
{
string lastName = string.Format("{0}_{1}", m_lastNameStem, i + m_fromBotNumber);
CreateBot(
this,
CreateBehavioursFromAbbreviatedNames(m_defaultBehaviourSwitches),
m_firstName, lastName, m_password, m_loginUri, m_startUri, m_wearSetting);
}
}
}
private List<IBehaviour> CreateBehavioursFromAbbreviatedNames(HashSet<string> abbreviatedNames)
{
// We must give each bot its own list of instantiated behaviours since they store state.
List<IBehaviour> behaviours = new List<IBehaviour>();
// Hard-coded for now
foreach (string abName in abbreviatedNames)
{
IBehaviour newBehaviour = null;
if (abName == "c")
newBehaviour = new CrossBehaviour();
if (abName == "g")
newBehaviour = new GrabbingBehaviour();
if (abName == "n")
newBehaviour = new NoneBehaviour();
if (abName == "p")
newBehaviour = new PhysicsBehaviour();
if (abName == "t")
newBehaviour = new TeleportBehaviour();
if (abName == "tw")
newBehaviour = new TwitchyBehaviour();
if (abName == "ph2")
newBehaviour = new PhysicsBehaviour2();
if (abName == "inv")
newBehaviour = new InventoryDownloadBehaviour();
if (newBehaviour != null)
{
behaviours.Add(newBehaviour);
}
else
{
MainConsole.Instance.OutputFormat("No behaviour with abbreviated name {0} found", abName);
}
}
return behaviours;
}
public void ConnectBots(int botcount)
{
lock (BotConnectingStateChangeObject)
{
if (BotConnectingState != BotManagerBotConnectingState.Ready)
{
MainConsole.Instance.OutputFormat(
"Bot connecting status is {0}. Please wait for previous process to complete.", BotConnectingState);
return;
}
BotConnectingState = BotManagerBotConnectingState.Connecting;
}
Thread connectBotThread = new Thread(o => ConnectBotsInternal(botcount));
connectBotThread.Name = "Bots connection thread";
connectBotThread.Start();
}
private void ConnectBotsInternal(int botCount)
{
m_log.InfoFormat(
"[BOT MANAGER]: Starting {0} bots connecting to {1}, location {2}, named {3} {4}_<n>",
botCount,
m_loginUri,
m_startUri,
m_firstName,
m_lastNameStem);
m_log.DebugFormat("[BOT MANAGER]: Delay between logins is {0}ms", LoginDelay);
m_log.DebugFormat("[BOT MANAGER]: BotsSendAgentUpdates is {0}", InitBotSendAgentUpdates);
m_log.DebugFormat("[BOT MANAGER]: InitBotRequestObjectTextures is {0}", InitBotRequestObjectTextures);
List<Bot> botsToConnect = new List<Bot>();
lock (m_bots)
{
foreach (Bot bot in m_bots)
{
if (bot.ConnectionState == ConnectionState.Disconnected)
botsToConnect.Add(bot);
if (botsToConnect.Count >= botCount)
break;
}
}
foreach (Bot bot in botsToConnect)
{
lock (BotConnectingStateChangeObject)
{
if (BotConnectingState != BotManagerBotConnectingState.Connecting)
{
MainConsole.Instance.Output(
"[BOT MANAGER]: Aborting bot connection due to user-initiated disconnection");
return;
}
}
bot.Connect();
// Stagger logins
Thread.Sleep(LoginDelay);
}
lock (BotConnectingStateChangeObject)
{
if (BotConnectingState == BotManagerBotConnectingState.Connecting)
BotConnectingState = BotManagerBotConnectingState.Ready;
}
}
/// <summary>
/// Parses the command line start location to a start string/uri that the login mechanism will recognize.
/// </summary>
/// <returns>
/// The input start location to URI.
/// </returns>
/// <param name='startLocation'>
/// Start location.
/// </param>
private string ParseInputStartLocationToUri(string startLocation)
{
if (startLocation == "home" || startLocation == "last")
return startLocation;
string regionName;
// Just a region name or only one (!) extra component. Like a viewer, we will stick 128/128/0 on the end
Vector3 startPos = new Vector3(128, 128, 0);
string[] startLocationComponents = startLocation.Split('/');
regionName = startLocationComponents[0];
if (startLocationComponents.Length >= 2)
{
float.TryParse(startLocationComponents[1], out startPos.X);
if (startLocationComponents.Length >= 3)
{
float.TryParse(startLocationComponents[2], out startPos.Y);
if (startLocationComponents.Length >= 4)
float.TryParse(startLocationComponents[3], out startPos.Z);
}
}
return string.Format("uri:{0}&{1}&{2}&{3}", regionName, startPos.X, startPos.Y, startPos.Z);
}
/// <summary>
/// This creates a bot but does not start it.
/// </summary>
/// <param name="bm"></param>
/// <param name="behaviours">Behaviours for this bot to perform.</param>
/// <param name="firstName">First name</param>
/// <param name="lastName">Last name</param>
/// <param name="password">Password</param>
/// <param name="loginUri">Login URI</param>
/// <param name="startLocation">Location to start the bot. Can be "last", "home" or a specific sim name.</param>
/// <param name="wearSetting"></param>
public void CreateBot(
BotManager bm, List<IBehaviour> behaviours,
string firstName, string lastName, string password, string loginUri, string startLocation, string wearSetting)
{
MainConsole.Instance.OutputFormat(
"[BOT MANAGER]: Creating bot {0} {1}, behaviours are {2}",
firstName, lastName, string.Join(",", behaviours.ConvertAll<string>(b => b.Name).ToArray()));
Bot pb = new Bot(bm, behaviours, firstName, lastName, password, startLocation, loginUri);
pb.wear = wearSetting;
pb.Client.Settings.SEND_AGENT_UPDATES = InitBotSendAgentUpdates;
pb.RequestObjectTextures = InitBotRequestObjectTextures;
pb.OnConnected += handlebotEvent;
pb.OnDisconnected += handlebotEvent;
m_bots.Add(pb);
}
/// <summary>
/// High level connnected/disconnected events so we can keep track of our threads by proxy
/// </summary>
/// <param name="callbot"></param>
/// <param name="eventt"></param>
private void handlebotEvent(Bot callbot, EventType eventt)
{
switch (eventt)
{
case EventType.CONNECTED:
{
m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Connected");
break;
}
case EventType.DISCONNECTED:
{
m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Disconnected");
break;
}
}
}
/// <summary>
/// Standard CreateConsole routine
/// </summary>
/// <returns></returns>
protected CommandConsole CreateConsole()
{
return new LocalConsole("pCampbot");
}
private void HandleConnect(string module, string[] cmd)
{
lock (m_bots)
{
int botsToConnect;
int disconnectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Disconnected);
if (cmd.Length == 1)
{
botsToConnect = disconnectedBots;
}
else
{
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToConnect))
return;
botsToConnect = Math.Min(botsToConnect, disconnectedBots);
}
MainConsole.Instance.OutputFormat("Connecting {0} bots", botsToConnect);
ConnectBots(botsToConnect);
}
}
private void HandleAddBehaviour(string module, string[] cmd)
{
if (cmd.Length < 3 || cmd.Length > 4)
{
MainConsole.Instance.OutputFormat("Usage: add behaviour <abbreviated-behaviour> [<bot-number>]");
return;
}
string rawBehaviours = cmd[2];
List<Bot> botsToEffect = new List<Bot>();
if (cmd.Length == 3)
{
lock (m_bots)
botsToEffect.AddRange(m_bots);
}
else
{
int botNumber;
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
botsToEffect.Add(bot);
}
HashSet<string> rawAbbreviatedSwitchesToAdd = new HashSet<string>();
Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => rawAbbreviatedSwitchesToAdd.Add(b));
foreach (Bot bot in botsToEffect)
{
List<IBehaviour> behavioursAdded = new List<IBehaviour>();
foreach (IBehaviour behaviour in CreateBehavioursFromAbbreviatedNames(rawAbbreviatedSwitchesToAdd))
{
if (bot.AddBehaviour(behaviour))
behavioursAdded.Add(behaviour);
}
MainConsole.Instance.OutputFormat(
"Added behaviours {0} to bot {1}",
string.Join(", ", behavioursAdded.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
}
}
private void HandleRemoveBehaviour(string module, string[] cmd)
{
if (cmd.Length < 3 || cmd.Length > 4)
{
MainConsole.Instance.OutputFormat("Usage: remove behaviour <abbreviated-behaviour> [<bot-number>]");
return;
}
string rawBehaviours = cmd[2];
List<Bot> botsToEffect = new List<Bot>();
if (cmd.Length == 3)
{
lock (m_bots)
botsToEffect.AddRange(m_bots);
}
else
{
int botNumber;
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
botsToEffect.Add(bot);
}
HashSet<string> abbreviatedBehavioursToRemove = new HashSet<string>();
Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => abbreviatedBehavioursToRemove.Add(b));
foreach (Bot bot in botsToEffect)
{
List<IBehaviour> behavioursRemoved = new List<IBehaviour>();
foreach (string b in abbreviatedBehavioursToRemove)
{
IBehaviour behaviour;
if (bot.TryGetBehaviour(b, out behaviour))
{
bot.RemoveBehaviour(b);
behavioursRemoved.Add(behaviour);
}
}
MainConsole.Instance.OutputFormat(
"Removed behaviours {0} from bot {1}",
string.Join(", ", behavioursRemoved.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
}
}
private void HandleDisconnect(string module, string[] cmd)
{
List<Bot> connectedBots;
int botsToDisconnectCount;
lock (m_bots)
connectedBots = m_bots.FindAll(b => b.ConnectionState == ConnectionState.Connected);
if (cmd.Length == 1)
{
botsToDisconnectCount = connectedBots.Count;
}
else
{
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToDisconnectCount))
return;
botsToDisconnectCount = Math.Min(botsToDisconnectCount, connectedBots.Count);
}
lock (BotConnectingStateChangeObject)
BotConnectingState = BotManagerBotConnectingState.Disconnecting;
Thread disconnectBotThread = new Thread(o => DisconnectBotsInternal(connectedBots, botsToDisconnectCount));
disconnectBotThread.Name = "Bots disconnection thread";
disconnectBotThread.Start();
}
private void DisconnectBotsInternal(List<Bot> connectedBots, int disconnectCount)
{
MainConsole.Instance.OutputFormat("Disconnecting {0} bots", disconnectCount);
int disconnectedBots = 0;
for (int i = connectedBots.Count - 1; i >= 0; i--)
{
if (disconnectedBots >= disconnectCount)
break;
Bot thisBot = connectedBots[i];
if (thisBot.ConnectionState == ConnectionState.Connected)
{
ThreadPool.QueueUserWorkItem(o => thisBot.Disconnect());
disconnectedBots++;
}
}
lock (BotConnectingStateChangeObject)
BotConnectingState = BotManagerBotConnectingState.Ready;
}
private void HandleSit(string module, string[] cmd)
{
lock (m_bots)
{
foreach (Bot bot in m_bots)
{
if (bot.ConnectionState == ConnectionState.Connected)
{
MainConsole.Instance.OutputFormat("Sitting bot {0} on ground.", bot.Name);
bot.SitOnGround();
}
}
}
}
private void HandleStand(string module, string[] cmd)
{
lock (m_bots)
{
foreach (Bot bot in m_bots)
{
if (bot.ConnectionState == ConnectionState.Connected)
{
MainConsole.Instance.OutputFormat("Standing bot {0} from ground.", bot.Name);
bot.Stand();
}
}
}
}
private void HandleShutdown(string module, string[] cmd)
{
lock (m_bots)
{
int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
if (connectedBots > 0)
{
MainConsole.Instance.OutputFormat("Please disconnect {0} connected bots first", connectedBots);
return;
}
}
MainConsole.Instance.Output("Shutting down");
m_serverStatsCollector.Close();
Environment.Exit(0);
}
private void HandleSetBots(string module, string[] cmd)
{
string key = cmd[2];
string rawValue = cmd[3];
if (key == "SEND_AGENT_UPDATES")
{
bool newSendAgentUpdatesSetting;
if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newSendAgentUpdatesSetting))
return;
MainConsole.Instance.OutputFormat(
"Setting SEND_AGENT_UPDATES to {0} for all bots", newSendAgentUpdatesSetting);
lock (m_bots)
m_bots.ForEach(b => b.Client.Settings.SEND_AGENT_UPDATES = newSendAgentUpdatesSetting);
}
else
{
MainConsole.Instance.Output("Error: Only setting currently available is SEND_AGENT_UPDATES");
}
}
private void HandleDebugLludpPacketCommand(string module, string[] args)
{
if (args.Length != 6)
{
MainConsole.Instance.OutputFormat("Usage: debug lludp packet <level> <bot-first-name> <bot-last-name>");
return;
}
int level;
if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[3], out level))
return;
string botFirstName = args[4];
string botLastName = args[5];
Bot bot;
lock (m_bots)
bot = m_bots.FirstOrDefault(b => b.FirstName == botFirstName && b.LastName == botLastName);
if (bot == null)
{
MainConsole.Instance.OutputFormat("No bot named {0} {1}", botFirstName, botLastName);
return;
}
bot.PacketDebugLevel = level;
MainConsole.Instance.OutputFormat("Set debug level of {0} to {1}", bot.Name, bot.PacketDebugLevel);
}
private void HandleShowRegions(string module, string[] cmd)
{
string outputFormat = "{0,-30} {1, -20} {2, -5} {3, -5}";
MainConsole.Instance.OutputFormat(outputFormat, "Name", "Handle", "X", "Y");
lock (RegionsKnown)
{
foreach (GridRegion region in RegionsKnown.Values)
{
MainConsole.Instance.OutputFormat(
outputFormat, region.Name, region.RegionHandle, region.X, region.Y);
}
}
}
private void HandleShowStatus(string module, string[] cmd)
{
ConsoleDisplayList cdl = new ConsoleDisplayList();
cdl.AddRow("Bot connecting state", BotConnectingState);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleShowBotsStatus(string module, string[] cmd)
{
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("Name", 24);
cdt.AddColumn("Region", 24);
cdt.AddColumn("Status", 13);
cdt.AddColumn("Conns", 5);
cdt.AddColumn("Behaviours", 20);
Dictionary<ConnectionState, int> totals = new Dictionary<ConnectionState, int>();
foreach (object o in Enum.GetValues(typeof(ConnectionState)))
totals[(ConnectionState)o] = 0;
lock (m_bots)
{
foreach (Bot bot in m_bots)
{
Simulator currentSim = bot.Client.Network.CurrentSim;
totals[bot.ConnectionState]++;
cdt.AddRow(
bot.Name,
currentSim != null ? currentSim.Name : "(none)",
bot.ConnectionState,
bot.SimulatorsCount,
string.Join(",", bot.Behaviours.Keys.ToArray()));
}
}
MainConsole.Instance.Output(cdt.ToString());
ConsoleDisplayList cdl = new ConsoleDisplayList();
foreach (KeyValuePair<ConnectionState, int> kvp in totals)
cdl.AddRow(kvp.Key, kvp.Value);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleShowBotStatus(string module, string[] cmd)
{
if (cmd.Length != 3)
{
MainConsole.Instance.Output("Usage: show bot <n>");
return;
}
int botNumber;
if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, cmd[2], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
ConsoleDisplayList cdl = new ConsoleDisplayList();
cdl.AddRow("Name", bot.Name);
cdl.AddRow("Status", bot.ConnectionState);
Simulator currentSim = bot.Client.Network.CurrentSim;
cdl.AddRow("Region", currentSim != null ? currentSim.Name : "(none)");
List<Simulator> connectedSimulators = bot.Simulators;
List<string> simulatorNames = connectedSimulators.ConvertAll<string>(cs => cs.Name);
cdl.AddRow("Connections", string.Join(", ", simulatorNames.ToArray()));
MainConsole.Instance.Output(cdl.ToString());
MainConsole.Instance.Output("Settings");
ConsoleDisplayList statusCdl = new ConsoleDisplayList();
statusCdl.AddRow(
"Behaviours",
string.Join(", ", bot.Behaviours.Values.ToList().ConvertAll<string>(b => b.Name).ToArray()));
GridClient botClient = bot.Client;
statusCdl.AddRow("SEND_AGENT_UPDATES", botClient.Settings.SEND_AGENT_UPDATES);
MainConsole.Instance.Output(statusCdl.ToString());
}
/// <summary>
/// Get a specific bot from its number.
/// </summary>
/// <returns>null if no bot was found</returns>
/// <param name='botNumber'></param>
private Bot GetBotFromNumber(int botNumber)
{
string name = GenerateBotNameFromNumber(botNumber);
Bot bot;
lock (m_bots)
bot = m_bots.Find(b => b.Name == name);
return bot;
}
private string GenerateBotNameFromNumber(int botNumber)
{
return string.Format("{0} {1}_{2}", m_firstName, m_lastNameStem, botNumber);
}
internal void Grid_GridRegion(object o, GridRegionEventArgs args)
{
lock (RegionsKnown)
{
GridRegion newRegion = args.Region;
if (RegionsKnown.ContainsKey(newRegion.RegionHandle))
{
return;
}
else
{
m_log.DebugFormat(
"[BOT MANAGER]: Adding {0} {1} to known regions", newRegion.Name, newRegion.RegionHandle);
RegionsKnown[newRegion.RegionHandle] = newRegion;
}
}
}
}
}
| |
//
// System.Web.Services.Description.SoapProtocolImporter.cs
//
// Author:
// Tim Coleman (tim@timcoleman.com)
// Lluis Sanchez Gual (lluis@ximian.com)
//
// Copyright (C) Tim Coleman, 2002
//
//
// 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.CodeDom;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Services.Configuration;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Configuration;
using System.Collections;
namespace System.Web.Services.Description {
public class SoapProtocolImporter : ProtocolImporter {
#region Fields
SoapBinding soapBinding;
SoapCodeExporter soapExporter;
SoapSchemaImporter soapImporter;
XmlCodeExporter xmlExporter;
XmlSchemaImporter xmlImporter;
CodeIdentifiers memberIds;
ArrayList extensionImporters;
Hashtable headerVariables;
XmlSchemas xmlSchemas;
XmlSchemas soapSchemas;
#endregion // Fields
#region Constructors
public SoapProtocolImporter ()
{
extensionImporters = ExtensionManager.BuildExtensionImporters ();
}
void SetBinding (SoapBinding soapBinding)
{
this.soapBinding = soapBinding;
}
#endregion // Constructors
#region Properties
public override string ProtocolName {
get { return "Soap"; }
}
public SoapBinding SoapBinding {
get { return soapBinding; }
}
public SoapCodeExporter SoapExporter {
get { return soapExporter; }
}
public SoapSchemaImporter SoapImporter {
get { return soapImporter; }
}
public XmlCodeExporter XmlExporter {
get { return xmlExporter; }
}
public XmlSchemaImporter XmlImporter {
get { return xmlImporter; }
}
#endregion // Properties
#region Methods
protected override CodeTypeDeclaration BeginClass ()
{
soapBinding = (SoapBinding) Binding.Extensions.Find (typeof(SoapBinding));
CodeTypeDeclaration codeClass = new CodeTypeDeclaration (ClassName);
string location = null;
if (Port != null) {
SoapAddressBinding sab = (SoapAddressBinding) Port.Extensions.Find (typeof(SoapAddressBinding));
if (sab != null) location = sab.Location;
}
string namspace = (Port != null ? Port.Binding.Namespace : Binding.ServiceDescription.TargetNamespace);
string name = (Port != null ? Port.Name : Binding.Name);
if (Style == ServiceDescriptionImportStyle.Client) {
CodeTypeReference ctr = new CodeTypeReference ("System.Web.Services.Protocols.SoapHttpClientProtocol");
codeClass.BaseTypes.Add (ctr);
}
else {
CodeTypeReference ctr = new CodeTypeReference ("System.Web.Services.WebService");
codeClass.BaseTypes.Add (ctr);
CodeAttributeDeclaration attws = new CodeAttributeDeclaration ("System.Web.Services.WebServiceAttribute");
attws.Arguments.Add (GetArg ("Namespace", namspace));
AddCustomAttribute (codeClass, attws, true);
}
CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Web.Services.WebServiceBinding");
att.Arguments.Add (GetArg ("Name", name));
att.Arguments.Add (GetArg ("Namespace", namspace));
AddCustomAttribute (codeClass, att, true);
if (Style == ServiceDescriptionImportStyle.Client) {
CodeConstructor cc = new CodeConstructor ();
cc.Attributes = MemberAttributes.Public;
GenerateServiceUrl (location, cc.Statements);
codeClass.Members.Add (cc);
}
memberIds = new CodeIdentifiers ();
headerVariables = new Hashtable ();
return codeClass;
}
protected override void BeginNamespace ()
{
#if NET_2_0
xmlImporter = new XmlSchemaImporter (LiteralSchemas, base.CodeGenerationOptions, base.CodeGenerator, base.ImportContext);
soapImporter = new SoapSchemaImporter (EncodedSchemas, base.CodeGenerationOptions, base.CodeGenerator, base.ImportContext);
xmlExporter = new XmlCodeExporter (CodeNamespace, null, base.CodeGenerator, base.CodeGenerationOptions, null);
soapExporter = new SoapCodeExporter (CodeNamespace, null, base.CodeGenerator, base.CodeGenerationOptions, null);
#else
xmlImporter = new XmlSchemaImporter (LiteralSchemas, ClassNames);
soapImporter = new SoapSchemaImporter (EncodedSchemas, ClassNames);
xmlExporter = new XmlCodeExporter (CodeNamespace, null);
soapExporter = new SoapCodeExporter (CodeNamespace, null);
#endif
}
protected override void EndClass ()
{
SoapTransportImporter transportImporter = SoapTransportImporter.FindTransportImporter (soapBinding.Transport);
if (transportImporter == null) throw new InvalidOperationException ("Transport '" + soapBinding.Transport + "' not supported");
transportImporter.ImportContext = this;
transportImporter.ImportClass ();
if (xmlExporter.IncludeMetadata.Count > 0 || soapExporter.IncludeMetadata.Count > 0)
{
if (CodeTypeDeclaration.CustomAttributes == null)
CodeTypeDeclaration.CustomAttributes = new CodeAttributeDeclarationCollection ();
CodeTypeDeclaration.CustomAttributes.AddRange (xmlExporter.IncludeMetadata);
CodeTypeDeclaration.CustomAttributes.AddRange (soapExporter.IncludeMetadata);
}
}
protected override void EndNamespace ()
{
}
protected override bool IsBindingSupported ()
{
return Binding.Extensions.Find (typeof(SoapBinding)) != null;
}
[MonoTODO]
protected override bool IsOperationFlowSupported (OperationFlow flow)
{
throw new NotImplementedException ();
}
[MonoTODO]
protected virtual bool IsSoapEncodingPresent (string uriList)
{
throw new NotImplementedException ();
}
protected override CodeMemberMethod GenerateMethod ()
{
try
{
SoapOperationBinding soapOper = OperationBinding.Extensions.Find (typeof (SoapOperationBinding)) as SoapOperationBinding;
if (soapOper == null) throw new InvalidOperationException ("Soap operation binding not found");
SoapBindingStyle style = soapOper.Style != SoapBindingStyle.Default ? soapOper.Style : soapBinding.Style;
SoapBodyBinding isbb = null;
XmlMembersMapping inputMembers = null;
isbb = OperationBinding.Input.Extensions.Find (typeof(SoapBodyBinding)) as SoapBodyBinding;
if (isbb == null) throw new InvalidOperationException ("Soap body binding not found");
inputMembers = ImportMembersMapping (InputMessage, isbb, style, false);
if (inputMembers == null) throw new InvalidOperationException ("Input message not declared");
// If OperationBinding.Output is null, it is an OneWay operation
SoapBodyBinding osbb = null;
XmlMembersMapping outputMembers = null;
if (OperationBinding.Output != null) {
osbb = OperationBinding.Output.Extensions.Find (typeof(SoapBodyBinding)) as SoapBodyBinding;
if (osbb == null) throw new InvalidOperationException ("Soap body binding not found");
outputMembers = ImportMembersMapping (OutputMessage, osbb, style, true);
if (outputMembers == null) throw new InvalidOperationException ("Output message not declared");
}
CodeMemberMethod met = GenerateMethod (memberIds, soapOper, isbb, inputMembers, outputMembers);
if (isbb.Use == SoapBindingUse.Literal)
xmlExporter.ExportMembersMapping (inputMembers);
else
soapExporter.ExportMembersMapping (inputMembers);
if (osbb != null) {
if (osbb.Use == SoapBindingUse.Literal)
xmlExporter.ExportMembersMapping (outputMembers);
else
soapExporter.ExportMembersMapping (outputMembers);
}
foreach (SoapExtensionImporter eximporter in extensionImporters)
{
eximporter.ImportContext = this;
eximporter.ImportMethod (met.CustomAttributes);
}
return met;
}
catch (InvalidOperationException ex)
{
UnsupportedOperationBindingWarning (ex.Message);
return null;
}
}
XmlMembersMapping ImportMembersMapping (Message msg, SoapBodyBinding sbb, SoapBindingStyle style, bool output)
{
string elemName = Operation.Name;
if (output) elemName += "Response";
if (msg.Parts.Count == 1 && msg.Parts[0].Name == "parameters")
{
// Wrapped parameter style
MessagePart part = msg.Parts[0];
if (sbb.Use == SoapBindingUse.Encoded)
{
SoapSchemaMember ssm = new SoapSchemaMember ();
ssm.MemberName = part.Name;
ssm.MemberType = part.Type;
return soapImporter.ImportMembersMapping (elemName, part.Type.Namespace, ssm);
}
else
return xmlImporter.ImportMembersMapping (part.Element);
}
else
{
if (sbb.Use == SoapBindingUse.Encoded)
{
SoapSchemaMember[] mems = new SoapSchemaMember [msg.Parts.Count];
for (int n=0; n<mems.Length; n++)
{
SoapSchemaMember mem = new SoapSchemaMember();
mem.MemberName = msg.Parts[n].Name;
mem.MemberType = msg.Parts[n].Type;
mems[n] = mem;
}
// Rpc messages always have a wrapping element
if (style == SoapBindingStyle.Rpc)
return soapImporter.ImportMembersMapping (elemName, sbb.Namespace, mems, true);
else
return soapImporter.ImportMembersMapping ("", "", mems, false);
}
else
{
if (style == SoapBindingStyle.Rpc)
throw new InvalidOperationException ("The combination of style=rpc with use=literal is not supported");
if (msg.Parts.Count == 1 && msg.Parts[0].Type != XmlQualifiedName.Empty)
return xmlImporter.ImportAnyType (msg.Parts[0].Type, null);
else
{
XmlQualifiedName[] pnames = new XmlQualifiedName [msg.Parts.Count];
for (int n=0; n<pnames.Length; n++)
pnames[n] = msg.Parts[n].Element;
return xmlImporter.ImportMembersMapping (pnames);
}
}
}
}
CodeMemberMethod GenerateMethod (CodeIdentifiers memberIds, SoapOperationBinding soapOper, SoapBodyBinding bodyBinding, XmlMembersMapping inputMembers, XmlMembersMapping outputMembers)
{
CodeIdentifiers pids = new CodeIdentifiers ();
CodeMemberMethod method = new CodeMemberMethod ();
CodeMemberMethod methodBegin = new CodeMemberMethod ();
CodeMemberMethod methodEnd = new CodeMemberMethod ();
method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
methodBegin.Attributes = MemberAttributes.Public | MemberAttributes.Final;
methodEnd.Attributes = MemberAttributes.Public | MemberAttributes.Final;
SoapBindingStyle style = soapOper.Style != SoapBindingStyle.Default ? soapOper.Style : soapBinding.Style;
// Find unique names for temporary variables
for (int n=0; n<inputMembers.Count; n++)
pids.AddUnique (inputMembers[n].MemberName, inputMembers[n]);
if (outputMembers != null)
for (int n=0; n<outputMembers.Count; n++)
pids.AddUnique (outputMembers[n].MemberName, outputMembers[n]);
string varAsyncResult = pids.AddUnique ("asyncResult","asyncResult");
string varResults = pids.AddUnique ("results","results");
string varCallback = pids.AddUnique ("callback","callback");
string varAsyncState = pids.AddUnique ("asyncState","asyncState");
string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name),method);
method.Name = CodeIdentifier.MakeValid(Operation.Name);
if (method.Name == ClassName) method.Name += "1";
methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + method.Name),method);
methodEnd.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + method.Name),method);
method.ReturnType = new CodeTypeReference (typeof(void));
methodEnd.ReturnType = new CodeTypeReference (typeof(void));
methodEnd.Parameters.Add (new CodeParameterDeclarationExpression (typeof (IAsyncResult),varAsyncResult));
CodeExpression[] paramArray = new CodeExpression [inputMembers.Count];
CodeParameterDeclarationExpression[] outParams = new CodeParameterDeclarationExpression [outputMembers != null ? outputMembers.Count : 0];
for (int n=0; n<inputMembers.Count; n++)
{
CodeParameterDeclarationExpression param = GenerateParameter (inputMembers[n], FieldDirection.In);
method.Parameters.Add (param);
GenerateMemberAttributes (inputMembers, inputMembers[n], bodyBinding.Use, param);
methodBegin.Parameters.Add (GenerateParameter (inputMembers[n], FieldDirection.In));
paramArray [n] = new CodeVariableReferenceExpression (param.Name);
}
if (outputMembers != null)
{
bool hasReturn = false;
for (int n=0; n<outputMembers.Count; n++)
{
CodeParameterDeclarationExpression cpd = GenerateParameter (outputMembers[n], FieldDirection.Out);
outParams [n] = cpd;
bool found = false;
foreach (CodeParameterDeclarationExpression ip in method.Parameters)
{
if (ip.Name == cpd.Name && ip.Type.BaseType == cpd.Type.BaseType) {
ip.Direction = FieldDirection.Ref;
methodEnd.Parameters.Add (GenerateParameter (outputMembers[n], FieldDirection.Out));
found = true;
break;
}
}
if (found) continue;
if (!hasReturn)
{
hasReturn = true;
method.ReturnType = cpd.Type;
methodEnd.ReturnType = cpd.Type;
GenerateReturnAttributes (outputMembers, outputMembers[n], bodyBinding.Use, method);
outParams [n] = null;
continue;
}
method.Parameters.Add (cpd);
GenerateMemberAttributes (outputMembers, outputMembers[n], bodyBinding.Use, cpd);
methodEnd.Parameters.Add (GenerateParameter (outputMembers[n], FieldDirection.Out));
}
}
methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (AsyncCallback),varCallback));
methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object),varAsyncState));
methodBegin.ReturnType = new CodeTypeReference (typeof(IAsyncResult));
// Array of input parameters
CodeArrayCreateExpression methodParams;
if (paramArray.Length > 0)
methodParams = new CodeArrayCreateExpression (typeof(object), paramArray);
else
methodParams = new CodeArrayCreateExpression (typeof(object), 0);
// Assignment of output parameters
CodeStatementCollection outAssign = new CodeStatementCollection ();
CodeVariableReferenceExpression arrVar = new CodeVariableReferenceExpression (varResults);
for (int n=0; n<outParams.Length; n++)
{
CodeExpression index = new CodePrimitiveExpression (n);
if (outParams[n] == null)
{
CodeExpression res = new CodeCastExpression (method.ReturnType, new CodeArrayIndexerExpression (arrVar, index));
outAssign.Add (new CodeMethodReturnStatement (res));
}
else
{
CodeExpression res = new CodeCastExpression (outParams[n].Type, new CodeArrayIndexerExpression (arrVar, index));
CodeExpression var = new CodeVariableReferenceExpression (outParams[n].Name);
outAssign.Insert (0, new CodeAssignStatement (var, res));
}
}
if (Style == ServiceDescriptionImportStyle.Client)
{
// Invoke call
CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
CodePrimitiveExpression varMsgName = new CodePrimitiveExpression (messageName);
CodeMethodInvokeExpression inv;
CodeVariableDeclarationStatement dec;
inv = new CodeMethodInvokeExpression (ethis, "Invoke", varMsgName, methodParams);
if (outputMembers != null && outputMembers.Count > 0)
{
dec = new CodeVariableDeclarationStatement (typeof(object[]), varResults, inv);
method.Statements.Add (dec);
method.Statements.AddRange (outAssign);
}
else
method.Statements.Add (inv);
// Begin Invoke Call
CodeExpression expCallb = new CodeVariableReferenceExpression (varCallback);
CodeExpression expAsyncs = new CodeVariableReferenceExpression (varAsyncState);
inv = new CodeMethodInvokeExpression (ethis, "BeginInvoke", varMsgName, methodParams, expCallb, expAsyncs);
methodBegin.Statements.Add (new CodeMethodReturnStatement (inv));
// End Invoke call
CodeExpression varAsyncr = new CodeVariableReferenceExpression (varAsyncResult);
inv = new CodeMethodInvokeExpression (ethis, "EndInvoke", varAsyncr);
if (outputMembers != null && outputMembers.Count > 0)
{
dec = new CodeVariableDeclarationStatement (typeof(object[]), varResults, inv);
methodEnd.Statements.Add (dec);
methodEnd.Statements.AddRange (outAssign);
}
else
methodEnd.Statements.Add (inv);
}
else {
method.Attributes = MemberAttributes.Public | MemberAttributes.Abstract;
}
// Attributes
ImportHeaders (method);
CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Web.Services.WebMethodAttribute");
if (messageName != method.Name) att.Arguments.Add (GetArg ("MessageName",messageName));
AddCustomAttribute (method, att, (Style == ServiceDescriptionImportStyle.Server));
if (style == SoapBindingStyle.Rpc)
{
att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.SoapRpcMethodAttribute");
att.Arguments.Add (GetArg (soapOper.SoapAction));
if (inputMembers.ElementName != method.Name) att.Arguments.Add (GetArg ("RequestElementName", inputMembers.ElementName));
if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response")) att.Arguments.Add (GetArg ("ResponseElementName", outputMembers.ElementName));
att.Arguments.Add (GetArg ("RequestNamespace", inputMembers.Namespace));
if (outputMembers != null) att.Arguments.Add (GetArg ("ResponseNamespace", outputMembers.Namespace));
if (outputMembers == null) att.Arguments.Add (GetArg ("OneWay", true));
}
else
{
if (outputMembers != null && (inputMembers.ElementName == "" && outputMembers.ElementName != "" ||
inputMembers.ElementName != "" && outputMembers.ElementName == ""))
throw new InvalidOperationException ("Parameter style is not the same for the input message and output message");
att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.SoapDocumentMethodAttribute");
att.Arguments.Add (GetArg (soapOper.SoapAction));
if (inputMembers.ElementName != "") {
if (inputMembers.ElementName != method.Name) att.Arguments.Add (GetArg ("RequestElementName", inputMembers.ElementName));
if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response")) att.Arguments.Add (GetArg ("ResponseElementName", outputMembers.ElementName));
att.Arguments.Add (GetArg ("RequestNamespace", inputMembers.Namespace));
if (outputMembers != null) att.Arguments.Add (GetArg ("ResponseNamespace", outputMembers.Namespace));
att.Arguments.Add (GetEnumArg ("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Wrapped"));
}
else
att.Arguments.Add (GetEnumArg ("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Bare"));
if (outputMembers == null) att.Arguments.Add (GetArg ("OneWay", true));
att.Arguments.Add (GetEnumArg ("Use", "System.Web.Services.Description.SoapBindingUse", bodyBinding.Use.ToString()));
}
AddCustomAttribute (method, att, true);
CodeTypeDeclaration.Members.Add (method);
if (Style == ServiceDescriptionImportStyle.Client) {
CodeTypeDeclaration.Members.Add (methodBegin);
CodeTypeDeclaration.Members.Add (methodEnd);
}
return method;
}
CodeParameterDeclarationExpression GenerateParameter (XmlMemberMapping member, FieldDirection dir)
{
CodeParameterDeclarationExpression par = new CodeParameterDeclarationExpression (member.TypeFullName, member.MemberName);
par.Direction = dir;
return par;
}
void GenerateMemberAttributes (XmlMembersMapping members, XmlMemberMapping member, SoapBindingUse use, CodeParameterDeclarationExpression param)
{
if (use == SoapBindingUse.Literal)
xmlExporter.AddMappingMetadata (param.CustomAttributes, member, members.Namespace);
else
soapExporter.AddMappingMetadata (param.CustomAttributes, member);
}
void GenerateReturnAttributes (XmlMembersMapping members, XmlMemberMapping member, SoapBindingUse use, CodeMemberMethod method)
{
if (use == SoapBindingUse.Literal)
xmlExporter.AddMappingMetadata (method.ReturnTypeCustomAttributes, member, members.Namespace, (member.ElementName != method.Name + "Result"));
else
soapExporter.AddMappingMetadata (method.ReturnTypeCustomAttributes, member, (member.ElementName != method.Name + "Result"));
}
void ImportHeaders (CodeMemberMethod method)
{
foreach (object ob in OperationBinding.Input.Extensions)
{
SoapHeaderBinding hb = ob as SoapHeaderBinding;
if (hb == null) continue;
if (HasHeader (OperationBinding.Output, hb))
ImportHeader (method, hb, SoapHeaderDirection.In | SoapHeaderDirection.Out);
else
ImportHeader (method, hb, SoapHeaderDirection.In);
}
if (OperationBinding.Output == null) return;
foreach (object ob in OperationBinding.Output.Extensions)
{
SoapHeaderBinding hb = ob as SoapHeaderBinding;
if (hb == null) continue;
if (!HasHeader (OperationBinding.Input, hb))
ImportHeader (method, hb, SoapHeaderDirection.Out);
}
}
bool HasHeader (MessageBinding msg, SoapHeaderBinding hb)
{
if (msg == null) return false;
foreach (object ob in msg.Extensions)
{
SoapHeaderBinding mhb = ob as SoapHeaderBinding;
if ((mhb != null) && (mhb.Message == hb.Message) && (mhb.Part == hb.Part))
return true;
}
return false;
}
void ImportHeader (CodeMemberMethod method, SoapHeaderBinding hb, SoapHeaderDirection direction)
{
Message msg = ServiceDescriptions.GetMessage (hb.Message);
if (msg == null) throw new InvalidOperationException ("Message " + hb.Message + " not found");
MessagePart part = msg.Parts [hb.Part];
if (part == null) throw new InvalidOperationException ("Message part " + hb.Part + " not found in message " + hb.Message);
XmlTypeMapping map;
if (hb.Use == SoapBindingUse.Literal)
{
map = xmlImporter.ImportDerivedTypeMapping (part.Element, typeof (SoapHeader));
xmlExporter.ExportTypeMapping (map);
}
else
{
map = soapImporter.ImportDerivedTypeMapping (part.Type, typeof (SoapHeader), true);
soapExporter.ExportTypeMapping (map);
}
bool required = false;
string varName = headerVariables [map] as string;
if (varName == null)
{
varName = memberIds.AddUnique(CodeIdentifier.MakeValid (map.TypeName + "Value"),hb);
headerVariables.Add (map, varName);
CodeMemberField codeField = new CodeMemberField (map.TypeFullName, varName);
codeField.Attributes = MemberAttributes.Public;
CodeTypeDeclaration.Members.Add (codeField);
}
CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.SoapHeaderAttribute");
att.Arguments.Add (GetArg (varName));
att.Arguments.Add (GetArg ("Required", required));
if (direction != SoapHeaderDirection.In) att.Arguments.Add (GetEnumArg ("Direction", "System.Web.Services.Protocols.SoapHeaderDirection", direction.ToString ()));
AddCustomAttribute (method, att, true);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SystemPens.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Drawing {
using System.Diagnostics;
using System;
using System.Runtime.Versioning;
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens"]/*' />
/// <devdoc>
/// Pens for select Windows system-wide colors. Whenever possible, try to use
/// SystemPens and SystemBrushes rather than SystemColors.
/// </devdoc>
public sealed class SystemPens {
static readonly object SystemPensKey = new object();
private SystemPens() {
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ActiveBorder"]/*' />
/// <devdoc>
/// Pen is the color of the filled area of an active window border.
/// </devdoc>
public static Pen ActiveBorder {
get {
return FromSystemColor(SystemColors.ActiveBorder);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ActiveCaption"]/*' />
/// <devdoc>
/// Pen is the color of the background of an active title bar caption.
/// </devdoc>
public static Pen ActiveCaption {
get {
return FromSystemColor(SystemColors.ActiveCaption);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ActiveCaptionText"]/*' />
/// <devdoc>
/// Pen is the color of the active window's caption text.
/// </devdoc>
public static Pen ActiveCaptionText {
get {
return FromSystemColor(SystemColors.ActiveCaptionText);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.AppWorkspace"]/*' />
/// <devdoc>
/// Pen is the color of the application workspace. The application workspace
/// is the area in a multiple document view that is not being occupied
/// by documents.
/// </devdoc>
public static Pen AppWorkspace {
get {
return FromSystemColor(SystemColors.AppWorkspace);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ButtonFace"]/*' />
/// <devdoc>
/// Pen for the ButtonFace system color.
/// </devdoc>
public static Pen ButtonFace {
get {
return FromSystemColor(SystemColors.ButtonFace);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ButtonHighlight"]/*' />
/// <devdoc>
/// Pen for the ButtonHighlight system color.
/// </devdoc>
public static Pen ButtonHighlight {
get {
return FromSystemColor(SystemColors.ButtonHighlight);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ButtonShadow"]/*' />
/// <devdoc>
/// Pen for the ButtonShadow system color.
/// </devdoc>
public static Pen ButtonShadow {
get {
return FromSystemColor(SystemColors.ButtonShadow);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.Control"]/*' />
/// <devdoc>
/// Pen is the color of a button or control.
/// </devdoc>
public static Pen Control {
get {
return FromSystemColor(SystemColors.Control);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ControlText"]/*' />
/// <devdoc>
/// Pen is the color of the text on a button or control.
/// </devdoc>
public static Pen ControlText {
get {
return FromSystemColor(SystemColors.ControlText);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ControlDark"]/*' />
/// <devdoc>
/// Pen is the color of the shadow part of a 3D element
/// </devdoc>
public static Pen ControlDark {
get {
return FromSystemColor(SystemColors.ControlDark);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ControlDarkDark"]/*' />
/// <devdoc>
/// Pen is the color of the darkest part of a 3D element
/// </devdoc>
public static Pen ControlDarkDark {
get {
return FromSystemColor(SystemColors.ControlDarkDark);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ControlLight"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static Pen ControlLight {
get {
return FromSystemColor(SystemColors.ControlLight);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ControlLightLight"]/*' />
/// <devdoc>
/// Pen is the color of the lightest part of a 3D element
/// </devdoc>
public static Pen ControlLightLight {
get {
return FromSystemColor(SystemColors.ControlLightLight);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.Desktop"]/*' />
/// <devdoc>
/// Pen is the color of the desktop.
/// </devdoc>
public static Pen Desktop {
get {
return FromSystemColor(SystemColors.Desktop);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.GradientActiveCaption"]/*' />
/// <devdoc>
/// Pen for the GradientActiveCaption system color.
/// </devdoc>
public static Pen GradientActiveCaption {
get {
return FromSystemColor(SystemColors.GradientActiveCaption);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.GradientInactiveCaption"]/*' />
/// <devdoc>
/// Pen for the GradientInactiveCaption system color.
/// </devdoc>
public static Pen GradientInactiveCaption {
get {
return FromSystemColor(SystemColors.GradientInactiveCaption);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.GrayText"]/*' />
/// <devdoc>
/// Pen is the color of disabled text.
/// </devdoc>
public static Pen GrayText {
get {
return FromSystemColor(SystemColors.GrayText);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.Highlight"]/*' />
/// <devdoc>
/// Pen is the color of a highlighted background.
/// </devdoc>
public static Pen Highlight {
get {
return FromSystemColor(SystemColors.Highlight);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.HighlightText"]/*' />
/// <devdoc>
/// Pen is the color of highlighted text.
/// </devdoc>
public static Pen HighlightText {
get {
return FromSystemColor(SystemColors.HighlightText);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.HotTrack"]/*' />
/// <devdoc>
/// Pen is the color used to represent hot tracking.
/// </devdoc>
public static Pen HotTrack {
get {
return FromSystemColor(SystemColors.HotTrack);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.InactiveBorder"]/*' />
/// <devdoc>
/// Pen is the color if an inactive window border.
/// </devdoc>
public static Pen InactiveBorder {
get {
return FromSystemColor(SystemColors.InactiveBorder);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.InactiveCaption"]/*' />
/// <devdoc>
/// Pen is the color of an inactive caption bar.
/// </devdoc>
public static Pen InactiveCaption {
get {
return FromSystemColor(SystemColors.InactiveCaption);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.InactiveCaptionText"]/*' />
/// <devdoc>
/// Pen is the color of an inactive window's caption text.
/// </devdoc>
public static Pen InactiveCaptionText {
get {
return FromSystemColor(SystemColors.InactiveCaptionText);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.Info"]/*' />
/// <devdoc>
/// Pen is the color of the info tooltip's background.
/// </devdoc>
public static Pen Info {
get {
return FromSystemColor(SystemColors.Info);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.InfoText"]/*' />
/// <devdoc>
/// Pen is the color of the info tooltip's text.
/// </devdoc>
public static Pen InfoText {
get {
return FromSystemColor(SystemColors.InfoText);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.Menu"]/*' />
/// <devdoc>
/// Pen is the color of the background of a menu.
/// </devdoc>
public static Pen Menu {
get {
return FromSystemColor(SystemColors.Menu);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.MenuBar"]/*' />
/// <devdoc>
/// Pen is the color of the background of a menu bar.
/// </devdoc>
public static Pen MenuBar {
get {
return FromSystemColor(SystemColors.MenuBar);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.MenuHighlight"]/*' />
/// <devdoc>
/// Pen for the MenuHighlight system color.
/// </devdoc>
public static Pen MenuHighlight {
get {
return FromSystemColor(SystemColors.MenuHighlight);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.MenuText"]/*' />
/// <devdoc>
/// Pen is the color of the menu text.
/// </devdoc>
public static Pen MenuText {
get {
return FromSystemColor(SystemColors.MenuText);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.ScrollBar"]/*' />
/// <devdoc>
/// Pen is the color of the scroll bar area that is not being used by the
/// thumb button.
/// </devdoc>
public static Pen ScrollBar {
get {
return FromSystemColor(SystemColors.ScrollBar);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.Window"]/*' />
/// <devdoc>
/// Pen is the color of the client area of a window.
/// </devdoc>
public static Pen Window {
get {
return FromSystemColor(SystemColors.Window);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.WindowFrame"]/*' />
/// <devdoc>
/// Pen is the color of the window frame.
/// </devdoc>
public static Pen WindowFrame {
get {
return FromSystemColor(SystemColors.WindowFrame);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.WindowText"]/*' />
/// <devdoc>
/// Pen is the color of a window's text.
/// </devdoc>
public static Pen WindowText {
get {
return FromSystemColor(SystemColors.WindowText);
}
}
/// <include file='doc\SystemPens.uex' path='docs/doc[@for="SystemPens.FromSystemColor"]/*' />
/// <devdoc>
/// Retrieves a pen given a system color. An error will be raised
/// if the color provide is not a system color.
/// </devdoc>
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process | ResourceScope.AppDomain, ResourceScope.Process | ResourceScope.AppDomain)]
public static Pen FromSystemColor(Color c) {
if (!c.IsSystemColor) {
throw new ArgumentException(SR.GetString(SR.ColorNotSystemColor, c.ToString()));
}
Pen[] systemPens = (Pen[])SafeNativeMethods.Gdip.ThreadData[SystemPensKey];
if (systemPens == null) {
systemPens = new Pen[(int)KnownColor.WindowText + (int)KnownColor.MenuHighlight - (int)KnownColor.YellowGreen];
SafeNativeMethods.Gdip.ThreadData[SystemPensKey] = systemPens;
}
int idx = (int)c.ToKnownColor();
if (idx > (int)KnownColor.YellowGreen) {
idx -= (int)KnownColor.YellowGreen - (int)KnownColor.WindowText;
}
idx--;
Debug.Assert(idx >= 0 && idx < systemPens.Length, "System colors have been added but our system color array has not been expanded.");
if (systemPens[idx] == null) {
systemPens[idx] = new Pen(c, true);
}
return systemPens[idx];
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using log4net;
using Tailviewer.Api;
namespace Tailviewer.Core
{
/// <summary>
/// Responsible for reading an object graph from a stream which has previously been persisted using
/// a <see cref="Writer"/>.
/// </summary>
public sealed class Reader
: IReader
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly DateTime _created;
private readonly ElementReader _documentReader;
private readonly int _formatVersion;
private readonly DateTime _tailviewerBuildDate;
private readonly Version _tailviewerVersion;
/// <summary>
/// Initializes this reader.
/// </summary>
/// <param name="input"></param>
/// <param name="typeFactory"></param>
public Reader(Stream input, ITypeFactory typeFactory)
{
var document = new XmlDocument();
document.Load(input);
_documentReader = new ElementReader(document.DocumentElement, typeFactory);
_documentReader.TryReadAttribute("FormatVersion", out _formatVersion);
_documentReader.TryReadAttribute("Created", out _created);
_documentReader.TryReadAttribute("TailviewerVersion", out _tailviewerVersion);
_documentReader.TryReadAttribute("TailviewerBuildDate", out _tailviewerBuildDate);
}
/// <summary>
/// The timestamp when the document was created.
/// </summary>
public DateTime Created => _created;
/// <summary>
/// The format version the document was created with.
/// </summary>
public int FormatVersion => _formatVersion;
/// <summary>
/// The version of the application that created the document.
/// </summary>
public Version TailviewerVersion => _tailviewerVersion;
/// <summary>
/// The build date of the application that created the document.
/// </summary>
public DateTime TailviewerBuildDate => _tailviewerBuildDate;
/// <inheritdoc />
public bool TryReadAttribute(string name, out bool value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out string value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out Version value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out DateTime value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out DateTime? value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out Guid value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out int value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out long value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out long? value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out DataSourceId value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out ISerializableType value)
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute<T>(string name, out T value) where T : ISerializableType
{
return _documentReader.TryReadAttribute(name, out value);
}
/// <inheritdoc />
public bool TryReadAttribute<T>(string name, T value) where T : class, ISerializableType
{
return _documentReader.TryReadAttribute(name, value);
}
/// <inheritdoc />
public bool TryReadAttribute(string name, out IEnumerable<ISerializableType> values)
{
return _documentReader.TryReadAttribute(name, out values);
}
/// <inheritdoc />
public bool TryReadAttribute<T>(string name, out IEnumerable<T> values) where T : class, ISerializableType
{
return _documentReader.TryReadAttribute(name, out values);
}
/// <inheritdoc />
public bool TryReadAttribute<T>(string name, List<T> values) where T : class, ISerializableType
{
return _documentReader.TryReadAttribute(name, values);
}
/// <inheritdoc />
public bool TryReadAttributeEnum<T>(string name, out T value) where T : struct
{
return _documentReader.TryReadAttributeEnum(name, out value);
}
private sealed class ElementReader
: IReader
{
private readonly Dictionary<string, XmlElement> _childElements;
private readonly ITypeFactory _typeFactory;
public ElementReader(XmlElement element, ITypeFactory typeFactory)
{
_typeFactory = typeFactory;
var childNodes = element.ChildNodes;
_childElements = new Dictionary<string, XmlElement>(childNodes.Count);
foreach (XmlElement child in childNodes)
if (child != null)
_childElements.Add(child.Name, child);
}
public bool TryReadAttribute(string name, out bool value)
{
if (TryReadAttribute(name, out string stringValue) && bool.TryParse(stringValue, out value))
return true;
value = false;
return false;
}
public bool TryReadAttribute(string name, out string value)
{
XmlElement element;
if (!_childElements.TryGetValue(name, out element))
{
value = null;
return false;
}
value = element.InnerText;
return true;
}
public bool TryReadAttribute(string name, out Version value)
{
string tmp;
if (!TryReadAttribute(name, out tmp))
{
value = null;
return false;
}
if (string.IsNullOrEmpty(tmp)) //< writer.Write(..., null)
{
value = null;
return true;
}
if (!Version.TryParse(tmp, out value))
return false;
return true;
}
public bool TryReadAttribute(string name, out DateTime value)
{
string stringValue;
if (!TryReadAttribute(name, out stringValue))
{
value = default(DateTime);
return false;
}
return TryParseDateTime(stringValue, out value);
}
public bool TryReadAttribute(string name, out DateTime? value)
{
if (!TryReadAttribute(name, out string stringValue))
{
value = null;
return false;
}
if (!TryParseDateTime(stringValue, out var actualValue))
{
value = null;
return false;
}
value = actualValue;
return true;
}
public bool TryReadAttribute(string name, out Guid value)
{
string tmp;
if (!TryReadAttribute(name, out tmp))
{
value = default(Guid);
return false;
}
value = Guid.Parse(tmp);
return true;
}
public bool TryReadAttribute(string name, out int value)
{
string tmp;
if (!TryReadAttribute(name, out tmp))
{
value = default(int);
return false;
}
if (!int.TryParse(tmp, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
return false;
return true;
}
public bool TryReadAttribute(string name, out long value)
{
string tmp;
if (!TryReadAttribute(name, out tmp))
{
value = default(int);
return false;
}
return TryParseLong(tmp, out value);
}
public bool TryReadAttribute(string name, out long? value)
{
string tmp;
if (!TryReadAttribute(name, out tmp))
{
value = null;
return false;
}
if (!TryParseLong(tmp, out var actualValue))
{
value = null;
return false;
}
value = actualValue;
return true;
}
public bool TryReadAttribute(string name, out DataSourceId value)
{
Guid tmp;
if (!TryReadAttribute(name, out tmp))
{
value = default(DataSourceId);
return false;
}
value = new DataSourceId(tmp);
return true;
}
public bool TryReadAttribute(string name, out ISerializableType value)
{
return TryReadAttribute<ISerializableType>(name, out value);
}
public bool TryReadAttribute<T>(string name, out T value) where T : ISerializableType
{
XmlElement element;
if (!_childElements.TryGetValue(name, out element))
{
value = default(T);
return false;
}
return TryReadChild(element, out value);
}
public bool TryReadAttribute<T>(string name, T value) where T : class, ISerializableType
{
if (value == null)
throw new ArgumentNullException(nameof(value), "You must construct the object beforehand if you use this overload. If you cannot do that, then you need to use the overload with value as an out parameter!");
XmlElement element;
if (!_childElements.TryGetValue(name, out element))
return false;
var child = element.ChildNodes.OfType<XmlElement>().FirstOrDefault(x => x.Name == "Value");
if (child == null)
return false;
var reader = new ElementReader(child, _typeFactory);
try
{
value.Deserialize(reader);
return true;
}
catch (Exception e)
{
Log.ErrorFormat("Caught unexpected exception while deserializing '{0}': {1}",
name, e);
return false;
}
}
public bool TryReadAttribute(string name, out IEnumerable<ISerializableType> values)
{
return TryReadAttribute<ISerializableType>(name, out values);
}
public bool TryReadAttribute<T>(string name, out IEnumerable<T> values) where T : class, ISerializableType
{
var tmp = new List<T>();
if (!TryReadAttribute(name, tmp))
{
values = null;
return false;
}
values = tmp;
return true;
}
public bool TryReadAttribute<T>(string name, List<T> values) where T : class, ISerializableType
{
XmlElement element;
if (!_childElements.TryGetValue(name, out element))
return false;
var node = element.ChildNodes.OfType<XmlElement>().FirstOrDefault(x => x.Name == "Count");
if (node == null)
return false;
int count;
if (!int.TryParse(node.InnerText, NumberStyles.Integer, CultureInfo.InvariantCulture, out count))
return false;
values.Clear();
TryReadChildren(element, values);
return true;
}
public bool TryReadAttributeEnum<T>(string name, out T value) where T : struct
{
if (TryReadAttribute(name, out string stringValue) && Enum.TryParse(stringValue, out T tmp))
{
value = tmp;
return true;
}
value = default(T);
return false;
}
private static bool TryParseDateTime(string stringValue, out DateTime value)
{
if (!DateTime.TryParseExact(stringValue, "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out value))
return false;
return true;
}
private static bool TryParseLong(string stringValue, out long value)
{
if (!long.TryParse(stringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
return false;
return true;
}
private bool TryReadChild<T>(XmlElement element, out T value) where T : ISerializableType
{
var type = element.GetElementsByTagName("Type").OfType<XmlElement>().FirstOrDefault();
if (type == null) //< This is the case when a null value was persisted
{
value = default(T);
return true;
}
var typeName = type.InnerText;
var tmp = _typeFactory.TryCreateNew(typeName);
if (!(tmp is T)) //< Type doesn't exist or couldn't be created
{
value = default(T);
return false;
}
var child = element.GetElementsByTagName("Value").OfType<XmlElement>().FirstOrDefault();
if (child == null)
{
value = default(T);
return false;
}
var reader = new ElementReader(child, _typeFactory);
try
{
value = (T) tmp;
value.Deserialize(reader);
return true;
}
catch (Exception e)
{
Log.ErrorFormat("Caught unexpected exception while deserializing '{0}': {1}",
typeName, e);
value = default(T);
return false;
}
}
private void TryReadChildren<T>(XmlElement element, List<T> values) where T : class, ISerializableType
{
foreach (XmlElement child in element.ChildNodes)
if (child != null && child.Name == "Element")
{
T value;
if (TryReadChild(child, out value))
values.Add(value);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.ObjectModel;
using System.Management.Automation.Subsystem;
using System.Management.Automation.Subsystem.DSC;
using System.Management.Automation.Subsystem.Prediction;
using System.Threading;
using Xunit;
namespace PSTests.Sequential
{
public static class SubsystemTests
{
private static readonly MyPredictor predictor1, predictor2;
static SubsystemTests()
{
predictor1 = MyPredictor.FastPredictor;
predictor2 = MyPredictor.SlowPredictor;
}
private static void VerifyCommandPredictorMetadata(SubsystemInfo ssInfo)
{
Assert.Equal(SubsystemKind.CommandPredictor, ssInfo.Kind);
Assert.Equal(typeof(ICommandPredictor), ssInfo.SubsystemType);
Assert.True(ssInfo.AllowUnregistration);
Assert.True(ssInfo.AllowMultipleRegistration);
Assert.Empty(ssInfo.RequiredCmdlets);
Assert.Empty(ssInfo.RequiredFunctions);
}
private static void VerifyCrossPlatformDscMetadata(SubsystemInfo ssInfo)
{
Assert.Equal(SubsystemKind.CrossPlatformDsc, ssInfo.Kind);
Assert.Equal(typeof(ICrossPlatformDsc), ssInfo.SubsystemType);
Assert.True(ssInfo.AllowUnregistration);
Assert.False(ssInfo.AllowMultipleRegistration);
Assert.Empty(ssInfo.RequiredCmdlets);
Assert.Empty(ssInfo.RequiredFunctions);
}
[Fact]
public static void GetSubsystemInfo()
{
SubsystemInfo predictorInfo = SubsystemManager.GetSubsystemInfo(typeof(ICommandPredictor));
VerifyCommandPredictorMetadata(predictorInfo);
Assert.False(predictorInfo.IsRegistered);
Assert.Empty(predictorInfo.Implementations);
SubsystemInfo predictorInfo2 = SubsystemManager.GetSubsystemInfo(SubsystemKind.CommandPredictor);
Assert.Same(predictorInfo2, predictorInfo);
SubsystemInfo crossPlatformDscInfo = SubsystemManager.GetSubsystemInfo(typeof(ICrossPlatformDsc));
VerifyCrossPlatformDscMetadata(crossPlatformDscInfo);
Assert.False(crossPlatformDscInfo.IsRegistered);
Assert.Empty(crossPlatformDscInfo.Implementations);
SubsystemInfo crossPlatformDscInfo2 = SubsystemManager.GetSubsystemInfo(SubsystemKind.CrossPlatformDsc);
Assert.Same(crossPlatformDscInfo2, crossPlatformDscInfo);
ReadOnlyCollection<SubsystemInfo> ssInfos = SubsystemManager.GetAllSubsystemInfo();
Assert.Equal(2, ssInfos.Count);
Assert.Same(ssInfos[0], predictorInfo);
Assert.Same(ssInfos[1], crossPlatformDscInfo);
ICommandPredictor predictorImpl = SubsystemManager.GetSubsystem<ICommandPredictor>();
Assert.Null(predictorImpl);
ReadOnlyCollection<ICommandPredictor> predictorImpls = SubsystemManager.GetSubsystems<ICommandPredictor>();
Assert.Empty(predictorImpls);
ICrossPlatformDsc crossPlatformDscImpl = SubsystemManager.GetSubsystem<ICrossPlatformDsc>();
Assert.Null(crossPlatformDscImpl);
ReadOnlyCollection<ICrossPlatformDsc> crossPlatformDscImpls = SubsystemManager.GetSubsystems<ICrossPlatformDsc>();
Assert.Empty(crossPlatformDscImpls);
}
[Fact]
public static void RegisterSubsystem()
{
try
{
Assert.Throws<ArgumentNullException>(
paramName: "proxy",
() => SubsystemManager.RegisterSubsystem<ICommandPredictor, MyPredictor>(null));
Assert.Throws<ArgumentNullException>(
paramName: "proxy",
() => SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, null));
Assert.Throws<ArgumentException>(
paramName: "proxy",
() => SubsystemManager.RegisterSubsystem((SubsystemKind)0, predictor1));
// Register 'predictor1'
SubsystemManager.RegisterSubsystem<ICommandPredictor, MyPredictor>(predictor1);
// Now validate the SubsystemInfo of the 'ICommandPredictor' subsystem
SubsystemInfo ssInfo = SubsystemManager.GetSubsystemInfo(typeof(ICommandPredictor));
SubsystemInfo crossPlatformDscInfo = SubsystemManager.GetSubsystemInfo(typeof(ICrossPlatformDsc));
VerifyCommandPredictorMetadata(ssInfo);
Assert.True(ssInfo.IsRegistered);
Assert.Single(ssInfo.Implementations);
// Now validate the 'ImplementationInfo'
var implInfo = ssInfo.Implementations[0];
Assert.Equal(predictor1.Id, implInfo.Id);
Assert.Equal(predictor1.Name, implInfo.Name);
Assert.Equal(predictor1.Description, implInfo.Description);
Assert.Equal(SubsystemKind.CommandPredictor, implInfo.Kind);
Assert.Same(typeof(MyPredictor), implInfo.ImplementationType);
// Now validate the subsystem implementation itself.
ICommandPredictor impl = SubsystemManager.GetSubsystem<ICommandPredictor>();
Assert.Same(impl, predictor1);
Assert.Null(impl.FunctionsToDefine);
Assert.Equal(SubsystemKind.CommandPredictor, impl.Kind);
const string Client = "SubsystemTest";
const string Input = "Hello world";
var predClient = new PredictionClient(Client, PredictionClientKind.Terminal);
var predCxt = PredictionContext.Create(Input);
var results = impl.GetSuggestion(predClient, predCxt, CancellationToken.None);
Assert.Equal($"'{Input}' from '{Client}' - TEST-1 from {impl.Name}", results.SuggestionEntries[0].SuggestionText);
Assert.Equal($"'{Input}' from '{Client}' - TeSt-2 from {impl.Name}", results.SuggestionEntries[1].SuggestionText);
// Now validate the all-subsystem-implementation collection.
ReadOnlyCollection<ICommandPredictor> impls = SubsystemManager.GetSubsystems<ICommandPredictor>();
Assert.Single(impls);
Assert.Same(predictor1, impls[0]);
// Register 'predictor2'
SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, predictor2);
// Now validate the SubsystemInfo of the 'ICommandPredictor' subsystem
VerifyCommandPredictorMetadata(ssInfo);
Assert.True(ssInfo.IsRegistered);
Assert.Equal(2, ssInfo.Implementations.Count);
// Now validate the new 'ImplementationInfo'
implInfo = ssInfo.Implementations[1];
Assert.Equal(predictor2.Id, implInfo.Id);
Assert.Equal(predictor2.Name, implInfo.Name);
Assert.Equal(predictor2.Description, implInfo.Description);
Assert.Equal(SubsystemKind.CommandPredictor, implInfo.Kind);
Assert.Same(typeof(MyPredictor), implInfo.ImplementationType);
// Now validate the new subsystem implementation.
impl = SubsystemManager.GetSubsystem<ICommandPredictor>();
Assert.Same(impl, predictor2);
// Now validate the all-subsystem-implementation collection.
impls = SubsystemManager.GetSubsystems<ICommandPredictor>();
Assert.Equal(2, impls.Count);
Assert.Same(predictor1, impls[0]);
Assert.Same(predictor2, impls[1]);
}
finally
{
SubsystemManager.UnregisterSubsystem<ICommandPredictor>(predictor1.Id);
SubsystemManager.UnregisterSubsystem(SubsystemKind.CommandPredictor, predictor2.Id);
}
}
[Fact]
public static void UnregisterSubsystem()
{
// Exception expected when no implementation is registered
Assert.Throws<InvalidOperationException>(() => SubsystemManager.UnregisterSubsystem<ICommandPredictor>(predictor1.Id));
SubsystemManager.RegisterSubsystem<ICommandPredictor, MyPredictor>(predictor1);
SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, predictor2);
// Exception is expected when specified id cannot be found
Assert.Throws<InvalidOperationException>(() => SubsystemManager.UnregisterSubsystem<ICommandPredictor>(Guid.NewGuid()));
// Unregister 'predictor1'
SubsystemManager.UnregisterSubsystem<ICommandPredictor>(predictor1.Id);
SubsystemInfo ssInfo = SubsystemManager.GetSubsystemInfo(SubsystemKind.CommandPredictor);
VerifyCommandPredictorMetadata(ssInfo);
Assert.True(ssInfo.IsRegistered);
Assert.Single(ssInfo.Implementations);
var implInfo = ssInfo.Implementations[0];
Assert.Equal(predictor2.Id, implInfo.Id);
Assert.Equal(predictor2.Name, implInfo.Name);
Assert.Equal(predictor2.Description, implInfo.Description);
Assert.Equal(SubsystemKind.CommandPredictor, implInfo.Kind);
Assert.Same(typeof(MyPredictor), implInfo.ImplementationType);
ICommandPredictor impl = SubsystemManager.GetSubsystem<ICommandPredictor>();
Assert.Same(impl, predictor2);
ReadOnlyCollection<ICommandPredictor> impls = SubsystemManager.GetSubsystems<ICommandPredictor>();
Assert.Single(impls);
Assert.Same(predictor2, impls[0]);
// Unregister 'predictor2'
SubsystemManager.UnregisterSubsystem(SubsystemKind.CommandPredictor, predictor2.Id);
VerifyCommandPredictorMetadata(ssInfo);
Assert.False(ssInfo.IsRegistered);
Assert.Empty(ssInfo.Implementations);
impl = SubsystemManager.GetSubsystem<ICommandPredictor>();
Assert.Null(impl);
impls = SubsystemManager.GetSubsystems<ICommandPredictor>();
Assert.Empty(impls);
}
}
}
| |
using ACBr.Net.Core.Extensions;
using Xunit;
namespace ACBr.Net.Core.Tests
{
public class ValidadarIETest
{
[Fact]
public void ValidoAC()
{
Assert.True("01.004.823/001-12".IsIE("AC"));
Assert.True("013456784".IsIE("AC"));
}
[Fact]
public void FormatarAC()
{
Assert.Equal("01.004.823/001-12", "0100482300112".FormatarIE("AC"));
}
[Fact]
public void InvalidoAC()
{
Assert.False("".IsIE("AC"));
Assert.False("99999".IsIE("AC"));
Assert.False("01.004.823/001-99".IsIE("AC"));
}
[Fact]
public void ValidoAL()
{
Assert.True("240123450".IsIE("AL"));
}
[Fact]
public void InvalidoAL()
{
Assert.False("".IsIE("AL"));
Assert.False("240123456".IsIE("AL"));
}
[Fact]
public void FormatarAL()
{
Assert.Equal("240123450", "240123450".FormatarIE("AL"));
}
[Fact]
public void ValidoAP()
{
Assert.True("030123459".IsIE("AP"));
Assert.True("030170011".IsIE("AP"));
Assert.True("030190225".IsIE("AP"));
Assert.True("030190231".IsIE("AP"));
}
[Fact]
public void InvalidoAP()
{
Assert.False("".IsIE("AP"));
Assert.False("123456789".IsIE("AP"));
}
[Fact]
public void FormatarAP()
{
Assert.Equal("030123459", "030123459".FormatarIE("AP"));
}
[Fact]
public void ValidoAM()
{
Assert.True("123123127".IsIE("AM"));
}
[Fact]
public void InvalidoAM()
{
Assert.False("".IsIE("AM"));
Assert.False("123123123".IsIE("AM"));
}
[Fact]
public void FormatarAM()
{
Assert.Equal("12.312.312-7", "123123127".FormatarIE("AM"));
}
[Fact]
public void ValidoBA()
{
Assert.True("123456-63".IsIE("BA"));
Assert.True("173456-13".IsIE("BA"));
}
[Fact]
public void InvalidoBA()
{
Assert.False("".IsIE("BA"));
Assert.False("123456-78".IsIE("BA"));
}
[Fact]
public void FormatarBA()
{
Assert.Equal("0123456-63", "12345663".FormatarIE("BA"));
}
[Fact]
public void ValidoCE()
{
Assert.True("023456787".IsIE("CE"));
}
[Fact]
public void InvalidoCE()
{
Assert.False("".IsIE("CE"));
Assert.False("123456789".IsIE("CE"));
}
[Fact]
public void FormatarCE()
{
Assert.Equal("02345678-7", "023456787".FormatarIE("CE"));
}
[Fact]
public void ValidoDF()
{
Assert.True("0734567890103".IsIE("DF"));
}
[Fact]
public void InvalidoDF()
{
Assert.False("".IsIE("DF"));
Assert.False("12345678901".IsIE("DF"));
Assert.False("1234567890123".IsIE("DF"));
}
[Fact]
public void FormatarDF()
{
Assert.Equal("07345678901-03", "0734567890103".FormatarIE("DF"));
}
[Fact]
public void ValidoES()
{
Assert.True("123123127".IsIE("ES"));
}
[Fact]
public void InvalidoES()
{
Assert.False("".IsIE("ES"));
Assert.False("123123123".IsIE("ES"));
}
[Fact]
public void FormatarES()
{
Assert.Equal("123123127", "123123127".FormatarIE("ES"));
}
[Fact]
public void ValidoGO()
{
Assert.True("10.987.654-7".IsIE("GO"));
Assert.True("104299274".IsIE("GO"));
}
[Fact]
public void InvalidoGO()
{
Assert.False("".IsIE("GO"));
Assert.False("12.312.312-3".IsIE("GO"));
}
[Fact]
public void FormatarGO()
{
Assert.Equal("10.987.654-7", "109876547".FormatarIE("GO"));
}
[Fact]
public void ValidoMA()
{
Assert.True("120000385".IsIE("MA"));
}
[Fact]
public void InvalidoMA()
{
Assert.False("".IsIE("MA"));
Assert.False("123123123".IsIE("MA"));
}
[Fact]
public void FormatarMA()
{
Assert.Equal("120000385", "120000385".FormatarIE("MA"));
}
[Fact]
public void ValidoMT()
{
Assert.True("0013000001-9".IsIE("MT"));
}
[Fact]
public void InvalidoMT()
{
Assert.False("".IsIE("MT"));
Assert.False("1234567890-1".IsIE("MT"));
}
[Fact]
public void FormatarMT()
{
Assert.Equal("0013000001-9", "130000019".FormatarIE("MT"));
}
[Fact]
public void ValidoMS()
{
Assert.True("28.312.312-5".IsIE("MS"));
}
[Fact]
public void InvalidoMS()
{
Assert.False("".IsIE("MS"));
Assert.False("123123123".IsIE("MS"));
}
[Fact]
public void FormatarMS()
{
Assert.Equal("28.312.312-5", "283123125".FormatarIE("MS"));
}
[Fact]
public void ValidoMG()
{
Assert.True("062.307.904/0081".IsIE("MG"));
}
[Fact]
public void InvalidoMG()
{
Assert.False("".IsIE("MG"));
Assert.False("123.123.123/9999".IsIE("MG"));
}
[Fact]
public void FormatarMG()
{
Assert.Equal("062.307.904/0081", "0623079040081".FormatarIE("MG"));
}
[Fact]
public void ValidoPA()
{
Assert.True("15999999-5".IsIE("PA"));
}
[Fact]
public void InvalidoPA()
{
Assert.False("".IsIE("PA"));
Assert.False("15999999-9".IsIE("PA"));
}
[Fact]
public void FormatarPA()
{
Assert.Equal("15-999999-5", "159999995".FormatarIE("PA"));
}
[Fact]
public void ValidoPB()
{
Assert.True("16000001-7".IsIE("PB"));
}
[Fact]
public void InvalidoPB()
{
Assert.False("".IsIE("PB"));
Assert.False("06000001-9".IsIE("PB"));
}
[Fact]
public void FormatarPB()
{
Assert.Equal("16000001-7", "160000017".FormatarIE("PB"));
}
[Fact]
public void ValidoPR()
{
Assert.True("123.45678-50".IsIE("PR"));
}
[Fact]
public void InvalidoPR()
{
Assert.False("".IsIE("PR"));
Assert.False("123.45678-99".IsIE("PR"));
}
[Fact]
public void FormatarPR()
{
Assert.Equal("123.45678-50", "1234567850".FormatarIE("PR"));
}
[Fact]
public void ValidoPE()
{
Assert.True("0321418-40".IsIE("PE"));
Assert.True("18.1.001.0000004-9".IsIE("PE"));
Assert.True("9999999-40".IsIE("PE"));
}
[Fact]
public void InvalidoPE()
{
Assert.False("".IsIE("PE"));
Assert.False("0321418-99".IsIE("PE"));
Assert.False("18.1.001.0000004-0".IsIE("PE"));
}
[Fact]
public void FormatarPE()
{
Assert.Equal("0321418-99", "032141899".FormatarIE("PE"));
Assert.Equal("18.1.001.0000004-0", "18100100000040".FormatarIE("PE"));
}
[Fact]
public void ValidoPI()
{
Assert.True("192345672".IsIE("PI"));
}
[Fact]
public void InvalidoPI()
{
Assert.False("".IsIE("PI"));
Assert.False("012345678".IsIE("PI"));
}
[Fact]
public void FormatarPI()
{
Assert.Equal("192345672", "192345672".FormatarIE("PI"));
}
[Fact]
public void ValidoRJ()
{
Assert.True("12.123.12-4".IsIE("RJ"));
}
[Fact]
public void InvalidoRJ()
{
Assert.False("".IsIE("RJ"));
Assert.False("12.123.12-9".IsIE("RJ"));
}
[Fact]
public void FormatarRJ()
{
Assert.Equal("12.123.12-4", "12123124".FormatarIE("RJ"));
}
[Fact]
public void ValidoRN()
{
Assert.True("20.040.040-1".IsIE("RN"));
Assert.True("20.0.040.040-0".IsIE("RN"));
}
[Fact]
public void InvalidoRN()
{
Assert.False("".IsIE("RN"));
Assert.False("20.040.040-9".IsIE("RN"));
Assert.False("20.0.040.040-9".IsIE("RN"));
}
[Fact]
public void FormatarRN()
{
Assert.Equal("20.040.040-1", "200400401".FormatarIE("RN"));
Assert.Equal("20.0.040.040-0", "2000400400".FormatarIE("RN"));
}
[Fact]
public void ValidoRS()
{
Assert.True("224/3658792".IsIE("RS"));
}
[Fact]
public void InvalidoRS()
{
Assert.False("".IsIE("RS"));
Assert.False("224/1234567".IsIE("RS"));
}
[Fact]
public void FormatarRS()
{
Assert.Equal("224/3658792", "2243658792".FormatarIE("RS"));
}
[Fact]
public void ValidoRO()
{
Assert.True("101.62521-3".IsIE("RO"));
Assert.True("0000000062521-3".IsIE("RO"));
}
[Fact]
public void InvalidoRO()
{
Assert.False("".IsIE("RO"));
Assert.False("101.12345-6".IsIE("RO"));
Assert.False("1234567890521-3".IsIE("RO"));
}
[Fact]
public void FormatarRO()
{
Assert.Equal("101.62521-3", "101625213".FormatarIE("RO"));
Assert.Equal("0000000062521-3", "00000000625213".FormatarIE("RO"));
}
[Fact]
public void ValidoRR()
{
Assert.True("24008266-8".IsIE("RR"));
}
[Fact]
public void InvalidoRR()
{
Assert.False("".IsIE("RR"));
Assert.False("12345678-8".IsIE("RR"));
}
[Fact]
public void FormatarRR()
{
Assert.Equal("24008266-8", "240082668".FormatarIE("RR"));
}
[Fact]
public void ValidoSC()
{
Assert.True("251.040.852".IsIE("SC"));
}
[Fact]
public void InvalidoSC()
{
Assert.False("".IsIE("SC"));
Assert.False("123.123.123".IsIE("SC"));
}
[Fact]
public void FormatarSC()
{
Assert.Equal("251.040.852", "251040852".FormatarIE("SC"));
}
[Fact]
public void ValidoSP()
{
Assert.True("110.042.490.114".IsIE("SP"));
Assert.True("P-01100424.3/002".IsIE("SP"));
}
[Fact]
public void InvalidoSP()
{
Assert.False("".IsIE("SP"));
Assert.False("123.123.123.123".IsIE("SP"));
Assert.False("P-12345678.9/002".IsIE("SP"));
}
[Fact]
public void FormatarSP()
{
Assert.Equal("110.042.490.114", "110042490114".FormatarIE("SP"));
Assert.Equal("P-01100424.3/123", "P011004243123".FormatarIE("SP"));
}
[Fact]
public void ValidoSE()
{
Assert.True("27123456-3".IsIE("SE"));
}
[Fact]
public void InvalidoSE()
{
Assert.False("".IsIE("SE"));
Assert.False("12312312-3".IsIE("SE"));
}
[Fact]
public void FormatarSE()
{
Assert.Equal("27.123.456-3", "271234563".FormatarIE("SE"));
}
[Fact]
public void ValidoTO()
{
Assert.True("01.022.783-0".IsIE("TO"));
Assert.True("29.01.022783-6".IsIE("TO"));
}
[Fact]
public void InvalidoTO()
{
Assert.False("".IsIE("TO"));
Assert.False("12.123.123-9".IsIE("TO"));
Assert.False("12.34.567890-6".IsIE("TO"));
}
[Fact]
public void FormatarTO()
{
Assert.Equal("01.022.783-0", "010227830".FormatarIE("TO"));
Assert.Equal("29.01.022783-6", "29010227836".FormatarIE("TO"));
}
}
}
| |
/* ====================================================================
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;
namespace NStorage.Storage
{
/**
* Wraps a <c>byte</c> array and provides simple data input access.
* Internally, this class maintains a buffer read index, so that for the most part, primitive
* data can be read in a data-input-stream-like manner.<p/>
*
* Note - the calling class should call the {@link #available()} method to detect end-of-buffer
* and Move to the next data block when the current is exhausted.
* For optimisation reasons, no error handling is performed in this class. Thus, mistakes in
* calling code ran may raise ugly exceptions here, like {@link ArrayIndexOutOfBoundsException},
* etc .<p/>
*
* The multi-byte primitive input methods ({@link #readUshortLE()}, {@link #readIntLE()} and
* {@link #readLongLE()}) have corresponding 'spanning Read' methods which (when required) perform
* a read across the block boundary. These spanning read methods take the previous
* {@link DataInputBlock} as a parameter.
* Reads of larger amounts of data (into <c>byte</c> array buffers) must be managed by the caller
* since these could conceivably involve more than two blocks.
*
* @author Josh Micich
*/
public class DataInputBlock
{
/**
* Possibly any size (usually 512K or 64K). Assumed to be at least 8 bytes for all blocks
* before the end of the stream. The last block in the stream can be any size except zero.
*/
private byte[] _buf;
private int _readIndex;
private int _maxIndex;
internal DataInputBlock(byte[] data, int startOffset)
{
_buf = data;
_readIndex = startOffset;
_maxIndex = _buf.Length;
}
public int Available()
{
return _maxIndex - _readIndex;
}
public int ReadUByte()
{
return _buf[_readIndex++] & 0xFF;
}
/**
* Reads a <c>short</c> which was encoded in <em>little endian</em> format.
*/
public int ReadUshortLE()
{
int i = _readIndex;
int b0 = _buf[i++] & 0xFF;
int b1 = _buf[i++] & 0xFF;
_readIndex = i;
return (b1 << 8) + (b0 << 0);
}
/**
* Reads a <c>short</c> which spans the end of <c>prevBlock</c> and the start of this block.
*/
public int ReadUshortLE(DataInputBlock prevBlock)
{
// simple case - will always be one byte in each block
int i = prevBlock._buf.Length - 1;
int b0 = prevBlock._buf[i++] & 0xFF;
int b1 = _buf[_readIndex++] & 0xFF;
return (b1 << 8) + (b0 << 0);
}
/**
* Reads an <c>int</c> which was encoded in <em>little endian</em> format.
*/
public int ReadIntLE()
{
int i = _readIndex;
int b0 = _buf[i++] & 0xFF;
int b1 = _buf[i++] & 0xFF;
int b2 = _buf[i++] & 0xFF;
int b3 = _buf[i++] & 0xFF;
_readIndex = i;
return (b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0);
}
/**
* Reads an <c>int</c> which spans the end of <c>prevBlock</c> and the start of this block.
*/
public int ReadIntLE(DataInputBlock prevBlock, int prevBlockAvailable)
{
byte[] buf = new byte[4];
ReadSpanning(prevBlock, prevBlockAvailable, buf);
int b0 = buf[0] & 0xFF;
int b1 = buf[1] & 0xFF;
int b2 = buf[2] & 0xFF;
int b3 = buf[3] & 0xFF;
return (b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0);
}
/**
* Reads a <c>long</c> which was encoded in <em>little endian</em> format.
*/
public long ReadLongLE()
{
int i = _readIndex;
int b0 = _buf[i++] & 0xFF;
int b1 = _buf[i++] & 0xFF;
int b2 = _buf[i++] & 0xFF;
int b3 = _buf[i++] & 0xFF;
int b4 = _buf[i++] & 0xFF;
int b5 = _buf[i++] & 0xFF;
int b6 = _buf[i++] & 0xFF;
int b7 = _buf[i++] & 0xFF;
_readIndex = i;
return (((long)b7 << 56) +
((long)b6 << 48) +
((long)b5 << 40) +
((long)b4 << 32) +
((long)b3 << 24) +
(b2 << 16) +
(b1 << 8) +
(b0 << 0));
}
/**
* Reads a <c>long</c> which spans the end of <c>prevBlock</c> and the start of this block.
*/
public long ReadLongLE(DataInputBlock prevBlock, int prevBlockAvailable)
{
byte[] buf = new byte[8];
ReadSpanning(prevBlock, prevBlockAvailable, buf);
int b0 = buf[0] & 0xFF;
int b1 = buf[1] & 0xFF;
int b2 = buf[2] & 0xFF;
int b3 = buf[3] & 0xFF;
int b4 = buf[4] & 0xFF;
int b5 = buf[5] & 0xFF;
int b6 = buf[6] & 0xFF;
int b7 = buf[7] & 0xFF;
return (((long)b7 << 56) +
((long)b6 << 48) +
((long)b5 << 40) +
((long)b4 << 32) +
((long)b3 << 24) +
(b2 << 16) +
(b1 << 8) +
(b0 << 0));
}
/**
* Reads a small amount of data from across the boundary between two blocks.
* The {@link #_readIndex} of this (the second) block is updated accordingly.
* Note- this method (and other code) assumes that the second {@link DataInputBlock}
* always is big enough to complete the read without being exhausted.
*/
private void ReadSpanning(DataInputBlock prevBlock, int prevBlockAvailable, byte[] buf)
{
Array.Copy(prevBlock._buf, prevBlock._readIndex, buf, 0, prevBlockAvailable);
int secondReadLen = buf.Length - prevBlockAvailable;
Array.Copy(_buf, 0, buf, prevBlockAvailable, secondReadLen);
_readIndex = secondReadLen;
}
/**
* Reads <c>len</c> bytes from this block into the supplied buffer.
*/
public void ReadFully(byte[] buf, int off, int len)
{
Array.Copy(_buf, _readIndex, buf, off, len);
_readIndex += len;
}
}
}
| |
/*
* PortAudioSharp - PortAudio bindings for .NET
* Copyright 2006-2011 Riccardo Gerosa and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Runtime.InteropServices;
namespace PortAudioSharp {
/**
<summary>
A simplified high-level audio class
</summary>
*/
public class Audio : IDisposable {
private int inputChannels, outputChannels, frequency;
private uint framesPerBuffer;
private PortAudio.PaStreamCallbackDelegate paStreamCallback;
private int hostApi;
PortAudio.PaHostApiInfo apiInfo;
PortAudio.PaDeviceInfo inputDeviceInfo, outputDeviceInfo;
private IntPtr stream;
private static bool loggingEnabled = false;
private bool disposed = false;
public static bool LoggingEnabled {
get { return loggingEnabled; }
set { loggingEnabled = value; }
}
public Audio(int inputChannels, int outputChannels, int frequency, uint framesPerBuffer,
PortAudio.PaStreamCallbackDelegate paStreamCallback) {
log("Initializing...");
this.inputChannels = inputChannels;
this.outputChannels = outputChannels;
this.frequency = frequency;
this.framesPerBuffer = framesPerBuffer;
this.paStreamCallback = paStreamCallback;
if (errorCheck("Initialize",PortAudio.Pa_Initialize())) {
this.disposed = true;
// if Pa_Initialize() returns an error code,
// Pa_Terminate() should NOT be called.
throw new Exception("Can't initialize audio");
}
int apiCount = PortAudio.Pa_GetHostApiCount();
for (int i = 0; i < apiCount; i++) {
PortAudio.PaHostApiInfo availableApiInfo = PortAudio.Pa_GetHostApiInfo(i);
log("available API index: " + i + "\n" + availableApiInfo.ToString());
}
this.hostApi = apiSelect();
log("selected Host API: " + this.hostApi);
this.apiInfo = PortAudio.Pa_GetHostApiInfo(this.hostApi);
this.inputDeviceInfo = PortAudio.Pa_GetDeviceInfo(apiInfo.defaultInputDevice);
this.outputDeviceInfo = PortAudio.Pa_GetDeviceInfo(apiInfo.defaultOutputDevice);
log("input device:\n" + inputDeviceInfo.ToString());
log("output device:\n" + outputDeviceInfo.ToString());
}
public void Start() {
log("Starting...");
this.stream = streamOpen(this.apiInfo.defaultInputDevice, this.inputChannels,
this.apiInfo.defaultOutputDevice,this.outputChannels,
this.frequency,this.framesPerBuffer);
log("Stream pointer: " + stream.ToInt32());
streamStart(stream);
}
public void Stop() {
log("Stopping...");
streamStop(this.stream);
streamClose(this.stream);
this.stream = new IntPtr(0);
}
private void log(String logString) {
if (loggingEnabled)
System.Console.WriteLine("PortAudio: " + logString);
System.Console.WriteLine();
}
private bool errorCheck(String action, PortAudio.PaError errorCode) {
if (errorCode != PortAudio.PaError.paNoError) {
log(action + " error: " + PortAudio.Pa_GetErrorText(errorCode));
if (errorCode == PortAudio.PaError.paUnanticipatedHostError) {
PortAudio.PaHostErrorInfo errorInfo = PortAudio.Pa_GetLastHostErrorInfo();
log("- Host error API type: " + errorInfo.hostApiType);
log("- Host error code: " + errorInfo.errorCode);
log("- Host error text: " + errorInfo.errorText);
}
return true;
} else {
log(action + " OK");
return false;
}
}
private int apiSelect() {
int selectedHostApi = PortAudio.Pa_GetDefaultHostApi();
int apiCount = PortAudio.Pa_GetHostApiCount();
for (int i = 0; i<apiCount; i++) {
PortAudio.PaHostApiInfo apiInfo = PortAudio.Pa_GetHostApiInfo(i);
if ((apiInfo.type == PortAudio.PaHostApiTypeId.paDirectSound)
|| (apiInfo.type == PortAudio.PaHostApiTypeId.paALSA))
selectedHostApi = i;
}
return selectedHostApi;
}
private IntPtr streamOpen(int inputDevice,int inputChannels,
int outputDevice,int outputChannels,
int sampleRate, uint framesPerBuffer) {
IntPtr stream = new IntPtr();
IntPtr data = new IntPtr(0);
PortAudio.PaStreamParameters? inputParams;
if (inputDevice == -1 || inputChannels <= 0) {
inputParams = null;
} else {
PortAudio.PaStreamParameters inputParamsTemp = new PortAudio.PaStreamParameters();
inputParamsTemp.channelCount = inputChannels;
inputParamsTemp.device = inputDevice;
inputParamsTemp.sampleFormat = PortAudio.PaSampleFormat.paFloat32;
inputParamsTemp.suggestedLatency = this.inputDeviceInfo.defaultLowInputLatency;
inputParams = inputParamsTemp;
}
PortAudio.PaStreamParameters? outputParams;
if (outputDevice == -1 || outputChannels <= 0) {
outputParams = null;
} else {
PortAudio.PaStreamParameters outputParamsTemp = new PortAudio.PaStreamParameters();
outputParamsTemp.channelCount = outputChannels;
outputParamsTemp.device = outputDevice;
outputParamsTemp.sampleFormat = PortAudio.PaSampleFormat.paFloat32;
outputParamsTemp.suggestedLatency = this.outputDeviceInfo.defaultLowOutputLatency;
outputParams = outputParamsTemp;
}
errorCheck("OpenDefaultStream",PortAudio.Pa_OpenStream(
out stream,
ref inputParams,
ref outputParams,
sampleRate,
framesPerBuffer,
PortAudio.PaStreamFlags.paNoFlag,
this.paStreamCallback,
data));
return stream;
}
/*
private IntPtr streamOpen(int inputChannels,int outputChannels,
int sampleRate, uint framesPerBuffer) {
IntPtr stream = new IntPtr();
IntPtr data = new IntPtr(0);
errorCheck("OpenDefaultStream",PortAudio.Pa_OpenDefaultStream(
out stream,
inputChannels,
outputChannels,
(uint) PortAudio.PaSampleFormat.paFloat32,
sampleRate,
framesPerBuffer,
this.paStreamCallback,
data));
return stream;
}
*/
private void streamClose(IntPtr stream) {
errorCheck("CloseStream",PortAudio.Pa_CloseStream(stream));
}
private void streamStart(IntPtr stream) {
errorCheck("StartStream",PortAudio.Pa_StartStream(stream));
}
private void streamStop(IntPtr stream) {
errorCheck("StopStream",PortAudio.Pa_StopStream(stream));
}
/*
private void streamWrite(IntPtr stream, float[] buffer) {
errorCheck("WriteStream",PortAudio.Pa_WriteStream(
stream,buffer,(uint)(buffer.Length/2)));
}
*/
private void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
// Dispose here any managed resources
}
// Dispose here any unmanaged resources
log("Terminating...");
errorCheck("Terminate",PortAudio.Pa_Terminate());
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Audio() {
Dispose(false);
}
}
}
| |
#region License
//
// Splitter.cs July 2008
//
// Copyright (C) 2008, Niall Gallagher <niallg@users.sf.net>
//
// 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
#region Using directives
using System.Text;
using System;
#endregion
namespace SimpleFramework.Xml.Stream {
/// <summary>
/// The <c>Splitter</c> object is used split up a string in to
/// tokens that can be used to create a camel case or hyphenated text
/// representation of the string. This will preserve acronyms and
/// numbers and splits tokens by case and character type. Examples
/// of how a string would be splitted are as follows.
/// </code>
/// CamelCaseString = "Camel" "Case" "String"
/// hyphenated-text = "hyphenated" "text"
/// URLAcronym = "URL" "acronym"
/// RFC2616.txt = "RFC" "2616" "txt"
/// </code>
/// By splitting strings in to individual words this allows the
/// splitter to be used to assemble the words in a way that adheres
/// to a specific style. Each style can then be applied to an XML
/// document to give it a consistent format.
/// </summary>
/// <seealso>
/// SimpleFramework.Xml.Stream.Style
/// </seealso>
internal abstract class Splitter {
/// <summary>
/// This is the string builder used to build the processed text.
/// </summary>
protected StringBuilder builder;
/// <summary>
/// This is the original text that is to be split in to words.
/// </summary>
protected char[] text;
/// <summary>
/// This is the number of characters to be considered for use.
/// </summary>
protected int count;
/// <summary>
/// This is the current read offset of the text string.
/// </summary>
protected int off;
/// <summary>
/// Constructor of the <c>Splitter</c> object. This is used
/// to split the provided string in to individual words so that
/// they can be assembled as a styled token, which can represent
/// an XML attribute or element.
/// </summary>
/// <param name="source">
/// this is the source that is to be split
/// </param>
public Splitter(String source) {
this.builder = new StringBuilder();
this.text = source.ToCharArray();
this.count = text.Length;
}
/// <summary>
/// This is used to process the internal string and convert it in
/// to a styled string. The styled string can then be used as an
/// XML attribute or element providing a consistent format to the
/// document that is being generated.
/// </summary>
/// <returns>
/// the string that has been converted to a styled string
/// </returns>
public String Process() {
while(off < count) {
while(off < count) {
char ch = text[off];
if(!IsSpecial(ch)) {
break;
}
off++;
}
if(!Acronym()) {
Token();
Number();
}
}
return builder.ToString();
}
/// <summary>
/// This is used to extract a token from the source string. Once a
/// token has been extracted the <c>Commit</c> method is
/// called to add it to the string being build. Each time this is
/// called a token, if extracted, will be committed to the string.
/// Before being committed the string is parsed for styling.
/// </summary>
public void Token() {
int mark = off;
while(mark < count) {
char ch = text[mark];
if(!IsLetter(ch)) {
break;
}
if(mark > off) {
if(IsUpper(ch)) {
break;
}
}
mark++;
}
if(mark > off) {
Parse(text, off, mark - off);
Commit(text, off, mark - off);
}
off = mark;
}
/// <summary>
/// This is used to extract a acronym from the source string. Once
/// a token has been extracted the <c>Commit</c> method is
/// called to add it to the string being build. Each time this is
/// called a token, if extracted, will be committed to the string.
/// </summary>
/// <returns>
/// true if an acronym was extracted from the source
/// </returns>
public bool Acronym() {
int mark = off;
int size = 0;
while(mark < count) {
char ch = text[mark];
if(IsUpper(ch)) {
size++;
} else {
break;
}
mark++;
}
if(size > 1) {
if(mark < count) {
char ch = text[mark-1];
if(IsUpper(ch)) {
mark--;
}
}
Commit(text, off, mark - off);
off = mark;
}
return size > 1;
}
/// <summary>
/// This is used to extract a number from the source string. Once
/// a token has been extracted the <c>Commit</c> method is
/// called to add it to the string being build. Each time this is
/// called a token, if extracted, will be committed to the string.
/// </summary>
/// <returns>
/// true if an number was extracted from the source
/// </returns>
public bool Number() {
int mark = off;
int size = 0;
while(mark < count) {
char ch = text[mark];
if(IsDigit(ch)) {
size++;
} else {
break;
}
mark++;
}
if(size > 0) {
Commit(text, off, mark - off);
}
off = mark;
return size > 0;
}
/// <summary>
/// This is used to determine if the provided string evaluates to
/// a letter character. This delegates to <c>System.Char</c>
/// so that the full range of unicode characters are considered.
/// </summary>
/// <param name="ch">
/// this is the character that is to be evaluated
/// </param>
/// <returns>
/// this returns true if the character is a letter
/// </returns>
public bool IsLetter(char ch) {
return Char.IsLetter(ch);
}
/// <summary>
/// This is used to determine if the provided string evaluates to
/// a symbol character. This delegates to <c>System.Char</c>
/// so that the full range of unicode characters are considered.
/// </summary>
/// <param name="ch">
/// this is the character that is to be evaluated
/// </param>
/// <returns>
/// this returns true if the character is a symbol
/// </returns>
public bool IsSpecial(char ch) {
return !Char.IsLetter(ch) && !Char.IsDigit(ch);
}
/// <summary>
/// This is used to determine if the provided string evaluates to
/// a digit character. This delegates to <c>Character</c>
/// so that the full range of unicode characters are considered.
/// </summary>
/// <param name="ch">
/// this is the character that is to be evaluated
/// </param>
/// <returns>
/// this returns true if the character is a digit
/// </returns>
public bool IsDigit(char ch) {
return Char.IsDigit(ch);
}
/// <summary>
/// This is used to determine if the provided string evaluates to
/// an upper case letter. This delegates to <c>System.Char</c>
/// so that the full range of unicode characters are considered.
/// </summary>
/// <param name="ch">
/// this is the character that is to be evaluated
/// </param>
/// <returns>
/// this returns true if the character is upper case
/// </returns>
public bool IsUpper(char ch) {
return Char.IsUpper(ch);
}
/// <summary>
/// This is used to convert the provided character to an upper
/// case character. This delegates to <c>System.Char</c> to
/// perform the conversion so unicode characters are considered.
/// </summary>
/// <param name="ch">
/// this is the character that is to be converted
/// </param>
/// <returns>
/// the character converted to upper case
/// </returns>
public char ToUpper(char ch) {
return Char.ToUpper(ch);
}
/// <summary>
/// This is used to convert the provided character to a lower
/// case character. This delegates to <c>System.Char</c> to
/// perform the conversion so unicode characters are considered.
/// </summary>
/// <param name="ch">
/// this is the character that is to be converted
/// </param>
/// <returns>
/// the character converted to lower case
/// </returns>
public char ToLower(char ch) {
return Char.ToLower(ch);
}
/// <summary>
/// This is used to parse the provided text in to the style that
/// is required. Manipulation of the text before committing it
/// ensures that the text adheres to the required style.
/// </summary>
/// <param name="text">
/// this is the text buffer to acquire the token from
/// </param>
/// <param name="off">
/// this is the offset in the buffer token starts at
/// </param>
/// <param name="len">
/// this is the length of the token to be parsed
/// </param>
public abstract void Parse(char[] text, int off, int len);
/// <summary>
/// This is used to commit the provided text in to the style that
/// is required. Committing the text to the buffer assembles the
/// tokens resulting in a complete token.
/// </summary>
/// <param name="text">
/// this is the text buffer to acquire the token from
/// </param>
/// <param name="off">
/// this is the offset in the buffer token starts at
/// </param>
/// <param name="len">
/// this is the length of the token to be committed
/// </param>
public abstract void Commit(char[] text, int off, int len);
}
}
| |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* 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
namespace RedBadger.Xpf.Data
{
using System;
using System.Globalization;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reflection;
internal class OneWayBinding<T> : IObservable<T>, IBinding, IDisposable
{
private readonly PropertyInfo deferredProperty;
private readonly T initialValue;
private readonly BindingResolutionMode resolutionMode;
private readonly bool shouldPushInitialValueOnSubscribe;
private INotifyPropertyChanged deferredSource;
private bool isDisposed;
private IObserver<T> observer;
private IObservable<T> sourceObservable;
private IDisposable subscription;
/// <summary>
/// A one-way binding to the data context
/// </summary>
public OneWayBinding()
: this(BindingResolutionMode.Deferred)
{
}
/// <summary>
/// A one-way binding to a property on the data context
/// </summary>
/// <param name = "propertyInfo"></param>
public OneWayBinding(PropertyInfo propertyInfo)
: this(BindingResolutionMode.Deferred)
{
if (propertyInfo == null)
{
throw new ArgumentNullException("propertyInfo");
}
this.deferredProperty = propertyInfo;
this.sourceObservable = Observable.Defer(this.GetDeferredObservable);
}
/// <summary>
/// A one-way binding to a specified source
/// </summary>
/// <param name = "source"></param>
public OneWayBinding(T source)
: this(BindingResolutionMode.Immediate)
{
this.sourceObservable = new BehaviorSubject<T>(source);
}
/// <summary>
/// A one-way binding to a property on a specified source
/// </summary>
/// <param name = "source"></param>
/// <param name = "propertyInfo"></param>
public OneWayBinding(object source, PropertyInfo propertyInfo)
: this(BindingResolutionMode.Immediate)
{
if (propertyInfo == null)
{
throw new ArgumentNullException("propertyInfo");
}
this.initialValue = GetValue(source, propertyInfo);
var notifyPropertyChanged = source as INotifyPropertyChanged;
if (notifyPropertyChanged != null)
{
this.sourceObservable = GetObservable(notifyPropertyChanged, propertyInfo);
this.shouldPushInitialValueOnSubscribe = true;
}
else
{
this.sourceObservable = new BehaviorSubject<T>(this.initialValue);
}
}
protected OneWayBinding(BindingResolutionMode resolutionMode)
{
this.resolutionMode = resolutionMode;
}
~OneWayBinding()
{
this.Dispose(false);
}
public BindingResolutionMode ResolutionMode
{
get
{
return this.resolutionMode;
}
}
protected IObserver<T> Observer
{
get
{
return this.observer;
}
}
protected IObservable<T> SourceObservable
{
get
{
return this.sourceObservable;
}
set
{
this.sourceObservable = value;
}
}
protected IDisposable Subscription
{
set
{
this.subscription = value;
}
}
public void Dispose(bool isDisposing)
{
if (!this.isDisposed)
{
if (isDisposing)
{
if (this.subscription != null)
{
this.subscription.Dispose();
}
}
}
this.isDisposed = true;
}
public virtual void Resolve(object dataContext)
{
if (this.sourceObservable == null)
{
this.observer.OnNext(Convert(dataContext));
}
else
{
this.observer.OnNext(GetValue(dataContext, this.deferredProperty));
if (dataContext is INotifyPropertyChanged)
{
this.deferredSource = (INotifyPropertyChanged)dataContext;
this.subscription = this.sourceObservable.Subscribe(this.observer);
}
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
public IDisposable Subscribe(IObserver<T> observer)
{
this.observer = observer;
if (this.resolutionMode == BindingResolutionMode.Immediate)
{
if (this.shouldPushInitialValueOnSubscribe)
{
this.observer.OnNext(this.initialValue);
}
this.subscription = this.sourceObservable.Subscribe(this.observer);
}
return this;
}
internal static T Convert(object value)
{
if (value != null)
{
Type sourceType = value.GetType();
Type targetType = typeof(T);
if (sourceType != targetType && !targetType.IsAssignableFrom(sourceType))
{
value = System.Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture);
}
}
return (T)value;
}
private static IObservable<T> GetObservable(INotifyPropertyChanged source, PropertyInfo propertyInfo)
{
return
Observable.FromEventPattern<PropertyChangedEventArgs>(
handler => source.PropertyChanged += handler, handler => source.PropertyChanged -= handler).Where(
data => data.EventArgs.PropertyName == propertyInfo.Name).Select(
e => GetValue(source, propertyInfo));
}
private static T GetValue(object source, PropertyInfo propertyInfo)
{
return Convert(propertyInfo.GetValue(source, null));
}
private IObservable<T> GetDeferredObservable()
{
return GetObservable(this.deferredSource, this.deferredProperty);
}
}
}
| |
// Copyright 2018 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
//
// 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 Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.Util.Reports;
using Google.Api.Ads.AdWords.Util.Reports.v201809;
using Google.Api.Ads.AdWords.v201809;
using Google.Api.Ads.Common.Util.Reports;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
/// <summary>
/// This code example runs a report for every advertiser account under a
/// given manager account, using multiple parallel threads. This code example
/// needs to be run against an AdWords manager account.
/// </summary>
public class ParallelReportDownload : ExampleBase
{
/// <summary>
/// The maximum number of reports to download in parallel. This number should
/// be less than or equal to <see cref="MAX_NUMBER_OF_THREADS"/>.
/// </summary>
private const int MAX_REPORT_DOWNLOADS_IN_PARALLEL = 3;
/// <summary>
/// The maximum number of threads to initialize for report downloads.
/// Normally, you would set this to <see cref="MAX_REPORT_DOWNLOADS_IN_PARALLEL"/>.
/// However, a more dynamic strategy involves changing
/// MAX_REPORT_DOWNLOADS_IN_PARALLEL at runtime depending on the AdWords
/// API server loads.
/// </summary>
private const int MAX_NUMBER_OF_THREADS = 10;
/// <summary>
/// Represents a report that was successfully downloaded.
/// </summary>
public class SuccessfulReportDownload
{
/// <summary>
/// Gets or sets the customer ID for the report.
/// </summary>
public long CustomerId { get; set; }
/// <summary>
/// Gets or sets the path to which report was downloaded.
/// </summary>
public string Path { get; set; }
}
/// <summary>
/// Represents a report download that failed.
/// </summary>
public class FailedReportDownload
{
/// <summary>
/// Gets or sets the customer ID for the report.
/// </summary>
public long CustomerId { get; set; }
/// <summary>
/// Gets or sets the exception that was thrown..
/// </summary>
public AdWordsReportsException Exception { get; set; }
}
/// <summary>
/// A data structure to hold data specific for a particular report download
/// thread.
/// </summary>
public class ReportDownloadData
{
/// <summary>
/// Gets or sets the application configuration.
/// </summary>
public AdWordsAppConfig Config { get; set; }
/// <summary>
/// Gets or sets the index of the thread that identifies it.
/// </summary>
public int ThreadIndex { get; set; }
/// <summary>
/// Gets or sets the folder to which reports are downloaded.
/// </summary>
public string DownloadFolder { get; set; }
/// <summary>
/// Gets or sets the event that signals the main thread that this thread
/// is finished with its job.
/// </summary>
public ManualResetEvent SignalEvent { get; set; }
/// <summary>
/// Gets or sets the queue that holds the list of all customerIDs to be
/// processed.
/// </summary>
public IProducerConsumerCollection<long> CustomerIdQueue { get; set; }
/// <summary>
/// Gets or sets the queue that holds the list of successful report
/// downloads.
/// </summary>
public IProducerConsumerCollection<SuccessfulReportDownload> SuccessfulReports
{
get;
set;
}
/// <summary>
/// Gets or sets the queue that holds the list of failed report downloads.
/// </summary>
public IProducerConsumerCollection<FailedReportDownload> FailedReports { get; set; }
/// <summary>
/// Gets or sets the lock that ensures only a fixed number of report
/// downloads happen simultaneously.
/// </summary>
public Semaphore QuotaLock { get; set; }
/// <summary>
/// The callback method for the report download thread.
/// </summary>
public void ThreadCallback(object arg)
{
string query = (string) arg;
AdWordsUser user = new AdWordsUser(this.Config);
while (true)
{
// Wait to acquire a lock on the quota lock.
QuotaLock.WaitOne();
// Try to get a customer ID from the queue.
long customerId = 0;
bool hasMoreCustomers = CustomerIdQueue.TryTake(out customerId);
if (!hasMoreCustomers)
{
// Nothing more to do, break the loop.
QuotaLock.Release();
break;
}
try
{
ProcessCustomer(user, customerId, query);
}
finally
{
// Release the quota lock once we have downloaded the report for the
// customer ID.
QuotaLock.Release();
}
}
// Mark the download as finished.
this.SignalEvent.Set();
}
/// <summary>
/// Processes the customer.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="customerId">The customer ID.</param>
/// <param name="query">The report query.</param>
private void ProcessCustomer(AdWordsUser user, long customerId, string query)
{
// Set the customer ID to the current customer.
this.Config.ClientCustomerId = customerId.ToString();
string downloadFile = string.Format("{0}{1}adgroup_{2:D10}.gz", this.DownloadFolder,
Path.DirectorySeparatorChar, customerId);
// Download the report.
Console.WriteLine("[Thread #{0}]: Downloading report for customer: {1} into {2}...",
this.ThreadIndex, customerId, downloadFile);
try
{
ReportUtilities utilities = new ReportUtilities(user, "v201809", query,
DownloadFormat.GZIPPED_CSV.ToString());
using (ReportResponse response = utilities.GetResponse())
{
response.Save(downloadFile);
}
// Mark this report download as success.
SuccessfulReportDownload success = new SuccessfulReportDownload
{
CustomerId = customerId,
Path = downloadFile
};
SuccessfulReports.TryAdd(success);
Console.WriteLine("Report was downloaded to '{0}'.", downloadFile);
}
catch (AdWordsReportsException e)
{
// Mark this report download as failure.
FailedReportDownload failure = new FailedReportDownload
{
CustomerId = customerId,
Exception = e
};
FailedReports.TryAdd(failure);
Console.WriteLine(
"Failed to download report for customer: {0}. Exception says {1}",
customerId, e.Message);
}
}
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
ParallelReportDownload codeExample = new ParallelReportDownload();
Console.WriteLine(codeExample.Description);
try
{
string fileName = "INSERT_FOLDER_NAME_HERE";
codeExample.Run(new AdWordsUser(), fileName);
}
catch (Exception e)
{
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e));
}
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get
{
return "This code example runs a report for every advertiser account under a " +
"given manager account, using multiple parallel threads. This code example " +
"needs to be run against an AdWords manager account.";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="downloadFolder">The file to which the report is downloaded.
/// </param>
public void Run(AdWordsUser user, string downloadFolder)
{
// Increase the number of HTTP connections we can do in parallel.
System.Net.ServicePointManager.DefaultConnectionLimit = 100;
try
{
// Start the rate limiter with an initial value of zero, so that all
// threads block immediately.
Semaphore rateLimiter = new Semaphore(0, MAX_REPORT_DOWNLOADS_IN_PARALLEL);
// Get all the advertiser accounts under this manager account.
List<long> allCustomerIds = GetDescendantAdvertiserAccounts(user);
// Create a concurrent queue of customers so that all threads can work
// on the collection in parallel.
ConcurrentQueue<long> customerQueue = new ConcurrentQueue<long>(allCustomerIds);
// Create queues to keep track of successful and failed report downloads.
ConcurrentQueue<SuccessfulReportDownload> reportsSucceeeded =
new ConcurrentQueue<SuccessfulReportDownload>();
ConcurrentQueue<FailedReportDownload> reportsFailed =
new ConcurrentQueue<FailedReportDownload>();
// Keep an array of events. This is used by the main thread to wait for
// all worker threads to join.
ManualResetEvent[] doneEvents = new ManualResetEvent[MAX_NUMBER_OF_THREADS];
// The list of threads to download reports.
Thread[] threads = new Thread[MAX_NUMBER_OF_THREADS];
// The data for each thread.
ReportDownloadData[] threadData = new ReportDownloadData[MAX_NUMBER_OF_THREADS];
// The query to be run on each account.
ReportQuery query = new ReportQueryBuilder()
.Select("CampaignId", "AdGroupId", "Impressions", "Clicks", "Cost")
.From(ReportDefinitionReportType.ADGROUP_PERFORMANCE_REPORT)
.Where("AdGroupStatus").In("ENABLED", "PAUSED")
.During(ReportDefinitionDateRangeType.LAST_7_DAYS).Build();
// Initialize the threads and their data.
for (int i = 0; i < MAX_NUMBER_OF_THREADS; i++)
{
doneEvents[i] = new ManualResetEvent(false);
threadData[i] = new ReportDownloadData()
{
Config = (AdWordsAppConfig) (user.Config.Clone()),
DownloadFolder = downloadFolder,
SignalEvent = doneEvents[i],
ThreadIndex = i,
QuotaLock = rateLimiter,
CustomerIdQueue = customerQueue,
SuccessfulReports = reportsSucceeeded,
FailedReports = reportsFailed
};
threads[i] = new Thread(threadData[i].ThreadCallback);
}
// Start the threads. Since the initial value of rate limiter is zero,
// all threads will block immediately.
for (int i = 0; i < threads.Length; i++)
{
threads[i].Start(query);
}
// Now reset the rate limiter so all threads can start downloading reports.
rateLimiter.Release(MAX_REPORT_DOWNLOADS_IN_PARALLEL);
// Wait for all threads in pool to complete.
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("Download completed, results:");
Console.WriteLine("Successful reports:");
while (!reportsSucceeeded.IsEmpty)
{
SuccessfulReportDownload success = null;
if (reportsSucceeeded.TryDequeue(out success))
{
Console.WriteLine("Client ID: {0}, Path: {1}", success.CustomerId,
success.Path);
}
}
Console.WriteLine("Failed reports:");
while (!reportsFailed.IsEmpty)
{
FailedReportDownload failure = null;
if (reportsFailed.TryDequeue(out failure))
{
Console.WriteLine("Client ID: {0}, Cause: {1}", failure.CustomerId,
failure.Exception.Message);
}
}
Console.WriteLine("All reports are downloaded.");
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to download reports.", e);
}
}
/// <summary>
/// Gets the list of all descendant advertiser accounts under the manager
/// account.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <returns>A list of customer IDs for descendant advertiser accounts.</returns>
public static List<long> GetDescendantAdvertiserAccounts(AdWordsUser user)
{
List<long> retval = new List<long>();
// Get the ManagedCustomerService.
ManagedCustomerService managedCustomerService =
(ManagedCustomerService) user.GetService(AdWordsService.v201809
.ManagedCustomerService);
// Create selector.
Selector selector = new Selector()
{
fields = new string[]
{
ManagedCustomer.Fields.CustomerId
},
predicates = new Predicate[]
{
// Select only advertiser accounts.
Predicate.Equals(ManagedCustomer.Fields.CanManageClients, false.ToString())
},
paging = Paging.Default
};
ManagedCustomerPage page = null;
try
{
do
{
page = managedCustomerService.get(selector);
if (page.entries != null)
{
foreach (ManagedCustomer customer in page.entries)
{
retval.Add(customer.customerId);
}
}
selector.paging.IncreaseOffset();
} while (selector.paging.startIndex < page.totalNumEntries);
}
catch (Exception)
{
Console.WriteLine(
"Failed to retrieve advertiser accounts under the manager account.");
throw;
}
return retval;
}
}
}
| |
/*
* 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 NumericUtils = Lucene.Net.Util.NumericUtils;
using NumericRangeQuery = Lucene.Net.Search.NumericRangeQuery;
namespace Lucene.Net.Documents
{
/// <summary> Provides support for converting dates to strings and vice-versa.
/// The strings are structured so that lexicographic sorting orders
/// them by date, which makes them suitable for use as field values
/// and search terms.
///
/// <p/>This class also helps you to limit the resolution of your dates. Do not
/// save dates with a finer resolution than you really need, as then
/// RangeQuery and PrefixQuery will require more memory and become slower.
///
/// <p/>Compared to {@link DateField} the strings generated by the methods
/// in this class take slightly more space, unless your selected resolution
/// is set to <code>Resolution.DAY</code> or lower.
///
/// <p/>
/// Another approach is {@link NumericUtils}, which provides
/// a sortable binary representation (prefix encoded) of numeric values, which
/// date/time are.
/// For indexing a {@link Date} or {@link Calendar}, just get the unix timestamp as
/// <code>long</code> using {@link Date#getTime} or {@link Calendar#getTimeInMillis} and
/// index this as a numeric value with {@link NumericField}
/// and use {@link NumericRangeQuery} to query it.
/// </summary>
public class DateTools
{
private static readonly System.String YEAR_FORMAT = "yyyy";
private static readonly System.String MONTH_FORMAT = "yyyyMM";
private static readonly System.String DAY_FORMAT = "yyyyMMdd";
private static readonly System.String HOUR_FORMAT = "yyyyMMddHH";
private static readonly System.String MINUTE_FORMAT = "yyyyMMddHHmm";
private static readonly System.String SECOND_FORMAT = "yyyyMMddHHmmss";
private static readonly System.String MILLISECOND_FORMAT = "yyyyMMddHHmmssfff";
private static readonly System.Globalization.Calendar calInstance = new System.Globalization.GregorianCalendar();
// cannot create, the class has static methods only
private DateTools()
{
}
/// <summary> Converts a Date to a string suitable for indexing.
///
/// </summary>
/// <param name="date">the date to be converted
/// </param>
/// <param name="resolution">the desired resolution, see
/// {@link #Round(Date, DateTools.Resolution)}
/// </param>
/// <returns> a string in format <code>yyyyMMddHHmmssSSS</code> or shorter,
/// depending on <code>resolution</code>; using GMT as timezone
/// </returns>
public static System.String DateToString(System.DateTime date, Resolution resolution)
{
return TimeToString(date.Ticks / TimeSpan.TicksPerMillisecond, resolution);
}
/// <summary> Converts a millisecond time to a string suitable for indexing.
///
/// </summary>
/// <param name="time">the date expressed as milliseconds since January 1, 1970, 00:00:00 GMT
/// </param>
/// <param name="resolution">the desired resolution, see
/// {@link #Round(long, DateTools.Resolution)}
/// </param>
/// <returns> a string in format <code>yyyyMMddHHmmssSSS</code> or shorter,
/// depending on <code>resolution</code>; using GMT as timezone
/// </returns>
public static System.String TimeToString(long time, Resolution resolution)
{
System.DateTime date = new System.DateTime(Round(time, resolution));
if (resolution == Resolution.YEAR)
{
return date.ToString(YEAR_FORMAT);
}
else if (resolution == Resolution.MONTH)
{
return date.ToString(MONTH_FORMAT);
}
else if (resolution == Resolution.DAY)
{
return date.ToString(DAY_FORMAT);
}
else if (resolution == Resolution.HOUR)
{
return date.ToString(HOUR_FORMAT);
}
else if (resolution == Resolution.MINUTE)
{
return date.ToString(MINUTE_FORMAT);
}
else if (resolution == Resolution.SECOND)
{
return date.ToString(SECOND_FORMAT);
}
else if (resolution == Resolution.MILLISECOND)
{
return date.ToString(MILLISECOND_FORMAT);
}
throw new System.ArgumentException("unknown resolution " + resolution);
}
/// <summary> Converts a string produced by <code>timeToString</code> or
/// <code>DateToString</code> back to a time, represented as the
/// number of milliseconds since January 1, 1970, 00:00:00 GMT.
///
/// </summary>
/// <param name="dateString">the date string to be converted
/// </param>
/// <returns> the number of milliseconds since January 1, 1970, 00:00:00 GMT
/// </returns>
/// <throws> ParseException if <code>dateString</code> is not in the </throws>
/// <summary> expected format
/// </summary>
public static long StringToTime(System.String dateString)
{
return StringToDate(dateString).Ticks;
}
/// <summary> Converts a string produced by <code>timeToString</code> or
/// <code>DateToString</code> back to a time, represented as a
/// Date object.
///
/// </summary>
/// <param name="dateString">the date string to be converted
/// </param>
/// <returns> the parsed time as a Date object
/// </returns>
/// <throws> ParseException if <code>dateString</code> is not in the </throws>
/// <summary> expected format
/// </summary>
public static System.DateTime StringToDate(System.String dateString)
{
System.DateTime date;
if (dateString.Length == 4)
{
date = new System.DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
1, 1, 0, 0, 0, 0);
}
else if (dateString.Length == 6)
{
date = new System.DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
1, 0, 0, 0, 0);
}
else if (dateString.Length == 8)
{
date = new System.DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
Convert.ToInt16(dateString.Substring(6, 2)),
0, 0, 0, 0);
}
else if (dateString.Length == 10)
{
date = new System.DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
Convert.ToInt16(dateString.Substring(6, 2)),
Convert.ToInt16(dateString.Substring(8, 2)),
0, 0, 0);
}
else if (dateString.Length == 12)
{
date = new System.DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
Convert.ToInt16(dateString.Substring(6, 2)),
Convert.ToInt16(dateString.Substring(8, 2)),
Convert.ToInt16(dateString.Substring(10, 2)),
0, 0);
}
else if (dateString.Length == 14)
{
date = new System.DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
Convert.ToInt16(dateString.Substring(6, 2)),
Convert.ToInt16(dateString.Substring(8, 2)),
Convert.ToInt16(dateString.Substring(10, 2)),
Convert.ToInt16(dateString.Substring(12, 2)),
0);
}
else if (dateString.Length == 17)
{
date = new System.DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
Convert.ToInt16(dateString.Substring(6, 2)),
Convert.ToInt16(dateString.Substring(8, 2)),
Convert.ToInt16(dateString.Substring(10, 2)),
Convert.ToInt16(dateString.Substring(12, 2)),
Convert.ToInt16(dateString.Substring(14, 3)));
}
else
{
throw new System.FormatException("Input is not valid date string: " + dateString);
}
return date;
}
/// <summary> Limit a date's resolution. For example, the date <code>2004-09-21 13:50:11</code>
/// will be changed to <code>2004-09-01 00:00:00</code> when using
/// <code>Resolution.MONTH</code>.
///
/// </summary>
/// <param name="resolution">The desired resolution of the date to be returned
/// </param>
/// <returns> the date with all values more precise than <code>resolution</code>
/// set to 0 or 1
/// </returns>
public static System.DateTime Round(System.DateTime date, Resolution resolution)
{
return new System.DateTime(Round(date.Ticks / TimeSpan.TicksPerMillisecond, resolution));
}
/// <summary> Limit a date's resolution. For example, the date <code>1095767411000</code>
/// (which represents 2004-09-21 13:50:11) will be changed to
/// <code>1093989600000</code> (2004-09-01 00:00:00) when using
/// <code>Resolution.MONTH</code>.
///
/// </summary>
/// <param name="time">The time in milliseconds (not ticks).</param>
/// <param name="resolution">The desired resolution of the date to be returned
/// </param>
/// <returns> the date with all values more precise than <code>resolution</code>
/// set to 0 or 1, expressed as milliseconds since January 1, 1970, 00:00:00 GMT
/// </returns>
public static long Round(long time, Resolution resolution)
{
System.DateTime dt = new System.DateTime(time * TimeSpan.TicksPerMillisecond);
if (resolution == Resolution.YEAR)
{
dt = dt.AddMonths(1 - dt.Month);
dt = dt.AddDays(1 - dt.Day);
dt = dt.AddHours(0 - dt.Hour);
dt = dt.AddMinutes(0 - dt.Minute);
dt = dt.AddSeconds(0 - dt.Second);
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.MONTH)
{
dt = dt.AddDays(1 - dt.Day);
dt = dt.AddHours(0 - dt.Hour);
dt = dt.AddMinutes(0 - dt.Minute);
dt = dt.AddSeconds(0 - dt.Second);
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.DAY)
{
dt = dt.AddHours(0 - dt.Hour);
dt = dt.AddMinutes(0 - dt.Minute);
dt = dt.AddSeconds(0 - dt.Second);
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.HOUR)
{
dt = dt.AddMinutes(0 - dt.Minute);
dt = dt.AddSeconds(0 - dt.Second);
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.MINUTE)
{
dt = dt.AddSeconds(0 - dt.Second);
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.SECOND)
{
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.MILLISECOND)
{
// don't cut off anything
}
else
{
throw new System.ArgumentException("unknown resolution " + resolution);
}
return dt.Ticks;
}
/// <summary>Specifies the time granularity. </summary>
public class Resolution
{
public static readonly Resolution YEAR = new Resolution("year");
public static readonly Resolution MONTH = new Resolution("month");
public static readonly Resolution DAY = new Resolution("day");
public static readonly Resolution HOUR = new Resolution("hour");
public static readonly Resolution MINUTE = new Resolution("minute");
public static readonly Resolution SECOND = new Resolution("second");
public static readonly Resolution MILLISECOND = new Resolution("millisecond");
private System.String resolution;
internal Resolution()
{
}
internal Resolution(System.String resolution)
{
this.resolution = resolution;
}
public override System.String ToString()
{
return resolution;
}
}
static DateTools()
{
{
// times need to be normalized so the value doesn't depend on the
// location the index is created/used:
// {{Aroush-2.1}}
/*
YEAR_FORMAT.setTimeZone(GMT);
MONTH_FORMAT.setTimeZone(GMT);
DAY_FORMAT.setTimeZone(GMT);
HOUR_FORMAT.setTimeZone(GMT);
MINUTE_FORMAT.setTimeZone(GMT);
SECOND_FORMAT.setTimeZone(GMT);
MILLISECOND_FORMAT.setTimeZone(GMT);
*/
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace System.Linq.Expressions
{
internal abstract class ExpressionVisitor
{
public virtual Expression Visit (Expression expression)
{
if (expression == null)
throw new ArgumentNullException ("expression");
switch (expression.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
case ExpressionType.UnaryPlus:
return VisitUnary ((UnaryExpression)expression);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.Power:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
return VisitBinary ((BinaryExpression)expression);
case ExpressionType.TypeIs:
return VisitTypeIs ((TypeBinaryExpression)expression);
case ExpressionType.Conditional:
return VisitConditional ((ConditionalExpression)expression);
case ExpressionType.Constant:
return VisitConstant ((ConstantExpression)expression);
case ExpressionType.Parameter:
return VisitParameter ((ParameterExpression)expression);
case ExpressionType.MemberAccess:
return VisitMember ((MemberExpression)expression);
case ExpressionType.Call:
return VisitMethodCall ((MethodCallExpression)expression);
case ExpressionType.Lambda:
return VisitLambda ((LambdaExpression) expression);
case ExpressionType.New:
return VisitNew ((NewExpression) expression);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return VisitNewArray ((NewArrayExpression)expression);
case ExpressionType.Invoke:
return VisitInvocation ((InvocationExpression)expression);
default:
throw new ArgumentException (string.Format ("Unhandled expression type: '{0}'", expression.NodeType));
}
}
protected virtual MemberBinding VisitBinding (MemberBinding binding)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
return VisitMemberAssignment ((MemberAssignment)binding);
default:
throw new ArgumentException (string.Format ("Unhandled binding type '{0}'", binding.BindingType));
}
}
protected virtual ElementInit VisitElementInitializer (ElementInit initializer)
{
Expression[] args;
if (VisitExpressionList (initializer.Arguments, out args))
return Expression.ElementInit (initializer.AddMethod, args);
return initializer;
}
protected virtual Expression VisitUnary (UnaryExpression unary)
{
Expression e = Visit (unary.Operand);
if (e != unary.Operand)
return Expression.MakeUnary (unary.NodeType, e, unary.Type, unary.Method);
return unary;
}
protected virtual Expression VisitBinary (BinaryExpression binary)
{
Expression left = Visit (binary.Left);
Expression right = Visit (binary.Right);
LambdaExpression conv = null;
if (binary.Conversion != null)
conv = (LambdaExpression)Visit (binary.Conversion);
if (left != binary.Left || right != binary.Right || conv != binary.Conversion)
return Expression.MakeBinary (binary.NodeType, left, right, binary.IsLiftedToNull, binary.Method, conv);
return binary;
}
protected virtual Expression VisitTypeIs (TypeBinaryExpression type)
{
Expression e = Visit (type.Expression);
if (e != type.Expression)
return Expression.TypeIs (e, type.TypeOperand);
return type;
}
protected virtual Expression VisitConstant (ConstantExpression constant)
{
return constant;
}
protected virtual Expression VisitConditional (ConditionalExpression conditional)
{
Expression test = Visit (conditional.Test);
Expression ifTrue = Visit (conditional.IfTrue);
Expression ifFalse = Visit (conditional.IfFalse);
if (test != conditional.Test || ifTrue != conditional.IfTrue || ifFalse != conditional.IfFalse)
return Expression.Condition (test, ifTrue, ifFalse);
return conditional;
}
protected virtual Expression VisitParameter (ParameterExpression parameter)
{
return parameter;
}
protected virtual Expression VisitMember (MemberExpression member)
{
Expression e = Visit (member.Expression);
if (e != member.Expression)
return Expression.MakeMemberAccess (e, member.Member);
return member;
}
protected bool VisitExpressionList (IEnumerable<Expression> expressions, out Expression[] newExpressions)
{
Expression[] args = expressions.ToArray();
newExpressions = new Expression[args.Length];
bool changed = false;
for (int i = 0; i < args.Length; ++i)
{
Expression original = args[i];
Expression current = Visit (original);
newExpressions[i] = current;
if (original != current)
changed = true;
}
return changed;
}
protected virtual Expression VisitMethodCall (MethodCallExpression methodCall)
{
bool changed = false;
Expression obj = null;
if (methodCall.Object != null)
{
obj = Visit (methodCall.Object);
changed = (obj != methodCall.Object);
}
Expression[] args;
changed = VisitExpressionList (methodCall.Arguments, out args) || changed;
if (changed)
return Expression.Call (obj, methodCall.Method, args);
return methodCall;
}
protected virtual MemberAssignment VisitMemberAssignment (MemberAssignment assignment)
{
Expression e = Visit (assignment.Expression);
if (e != assignment.Expression)
return Expression.Bind (assignment.Member, e);
return assignment;
}
protected virtual Expression VisitLambda (LambdaExpression lambda)
{
Expression body = Visit (lambda.Body);
bool changed = (body != lambda.Body);
Expression[] parameters;
changed = VisitExpressionList (lambda.Parameters.Cast<Expression>(), out parameters) || changed;
if (changed)
return Expression.Lambda (body, parameters.Cast<ParameterExpression>().ToArray());
return lambda;
}
protected virtual Expression VisitNew (NewExpression nex)
{
Expression[] args;
if (VisitExpressionList (nex.Arguments, out args))
return Expression.New (nex.Constructor, args, nex.Members);
return nex;
}
protected virtual Expression VisitNewArray (NewArrayExpression newArray)
{
Expression[] args;
if (VisitExpressionList (newArray.Expressions, out args))
return Expression.NewArrayInit (newArray.Type, args);
return newArray;
}
protected virtual Expression VisitInvocation (InvocationExpression invocation)
{
Expression[] args;
bool changed = VisitExpressionList (invocation.Arguments, out args);
Expression e = Visit (invocation.Expression);
changed = (e != invocation.Expression) || changed;
if (changed)
return Expression.Invoke (e, args);
return invocation;
}
}
}
| |
namespace AngleSharp.Dom
{
using AngleSharp.Css.Parser;
using AngleSharp.Dom.Events;
using AngleSharp.Text;
using System;
using System.Linq;
/// <summary>
/// Represents an element node.
/// </summary>
public abstract class Element : Node, IElement
{
#region Fields
private readonly NamedNodeMap _attributes;
private readonly String _namespace;
private readonly String? _prefix;
private readonly String _localName;
private HtmlCollection<IElement>? _elements;
private TokenList? _classList;
private IShadowRoot? _shadowRoot;
#endregion
#region ctor
/// <inheritdoc />
public Element(Document owner, String localName, String? prefix, String? namespaceUri, NodeFlags flags = NodeFlags.None)
: this(owner, prefix != null ? String.Concat(prefix, ":", localName) : localName, localName, prefix, namespaceUri!, flags)
{
}
/// <inheritdoc />
public Element(Document owner, String name, String localName, String? prefix, String namespaceUri, NodeFlags flags = NodeFlags.None)
: base(owner, name, NodeType.Element, flags)
{
_localName = localName;
_prefix = prefix;
_namespace = namespaceUri;
_attributes = new NamedNodeMap(this);
}
#endregion
#region Internal Properties
internal IBrowsingContext Context => Owner?.Context!;
internal NamedNodeMap Attributes => _attributes;
#endregion
#region Properties
/// <inheritdoc />
public IElement? AssignedSlot => ParentElement?.ShadowRoot?.GetAssignedSlot(Slot);
/// <inheritdoc />
public String? Slot
{
get => this.GetOwnAttribute(AttributeNames.Slot);
set => this.SetOwnAttribute(AttributeNames.Slot, value);
}
/// <inheritdoc />
public IShadowRoot? ShadowRoot => _shadowRoot;
/// <inheritdoc />
public String? Prefix => _prefix;
/// <inheritdoc />
public String LocalName => _localName;
/// <inheritdoc />
public String? NamespaceUri => _namespace ?? this.GetNamespaceUri();
/// <inheritdoc />
public override String TextContent
{
get
{
var sb = StringBuilderPool.Obtain();
foreach (var child in this.GetDescendants().OfType<IText>())
{
sb.Append(child.Data);
}
return sb.ToPool();
}
set
{
var node = !String.IsNullOrEmpty(value) ? new TextNode(Owner, value) : null;
ReplaceAll(node, false);
}
}
/// <inheritdoc />
public ITokenList ClassList
{
get
{
if (_classList is null)
{
_classList = new TokenList(this.GetOwnAttribute(AttributeNames.Class));
_classList.Changed += value => UpdateAttribute(AttributeNames.Class, value);
}
return _classList;
}
}
/// <inheritdoc />
public String? ClassName
{
get => this.GetOwnAttribute(AttributeNames.Class);
set => this.SetOwnAttribute(AttributeNames.Class, value);
}
/// <inheritdoc />
public String? Id
{
get => this.GetOwnAttribute(AttributeNames.Id);
set => this.SetOwnAttribute(AttributeNames.Id, value);
}
/// <inheritdoc />
public String TagName => NodeName;
/// <inheritdoc />
public ISourceReference? SourceReference { get; set; }
/// <inheritdoc />
public IElement? PreviousElementSibling
{
get
{
var parent = Parent;
if (parent != null)
{
var found = false;
for (var i = parent.ChildNodes.Length - 1; i >= 0; i--)
{
if (Object.ReferenceEquals(parent.ChildNodes[i], this))
{
found = true;
}
else if (found && parent.ChildNodes[i] is IElement previousElementSibling)
{
return previousElementSibling;
}
}
}
return null;
}
}
/// <inheritdoc />
public IElement? NextElementSibling
{
get
{
var parent = Parent;
if (parent != null)
{
var n = parent.ChildNodes.Length;
var found = false;
for (var i = 0; i < n; i++)
{
if (Object.ReferenceEquals(parent.ChildNodes[i], this))
{
found = true;
}
else if (found && parent.ChildNodes[i] is IElement childEl)
{
return childEl;
}
}
}
return null;
}
}
/// <inheritdoc />
public Int32 ChildElementCount
{
get
{
var children = ChildNodes;
var n = children.Length;
var count = 0;
for (var i = 0; i < n; i++)
{
if (children[i].NodeType == NodeType.Element)
{
count++;
}
}
return count;
}
}
/// <inheritdoc />
public IHtmlCollection<IElement> Children => _elements ??= new HtmlCollection<IElement>(this, deep: false);
/// <inheritdoc />
public IElement? FirstElementChild
{
get
{
var children = ChildNodes;
var n = children.Length;
for (var i = 0; i < n; i++)
{
if (children[i] is IElement child)
{
return child;
}
}
return null;
}
}
/// <inheritdoc />
public IElement? LastElementChild
{
get
{
var children = ChildNodes;
for (var i = children.Length - 1; i >= 0; i--)
{
if (children[i] is IElement child)
{
return child;
}
}
return null;
}
}
/// <inheritdoc />
public String InnerHtml
{
get => ChildNodes.ToHtml();
set => ReplaceAll(new DocumentFragment(this, value), false);
}
/// <inheritdoc />
public String OuterHtml
{
get => this.ToHtml();
set
{
var parentNode = Parent;
if (parentNode != null)
{
switch (parentNode.NodeType)
{
case NodeType.Document:
throw new DomException(DomError.NoModificationAllowed);
case NodeType.DocumentFragment:
parentNode = new Html.Dom.HtmlBodyElement(Owner);
break;
}
}
var parent = parentNode as Element ?? throw new DomException(DomError.NotSupported);
parent.InsertChild(parent.IndexOf(this), new DocumentFragment(parent, value));
parent.RemoveChild(this);
}
}
INamedNodeMap IElement.Attributes => _attributes;
/// <inheritdoc />
public Boolean IsFocused
{
get => Object.ReferenceEquals(Owner?.FocusElement, this);
protected set
{
var document = Owner;
document?.QueueTask(() =>
{
if (value)
{
document.SetFocus(this);
this.Fire<FocusEvent>(m => m.Init(EventNames.Focus, false, false));
}
else
{
document.SetFocus(null);
this.Fire<FocusEvent>(m => m.Init(EventNames.Blur, false, false));
}
});
}
}
#endregion
#region Methods
/// <summary>
/// Takes a given string source and parses it into a subtree
/// using the current element as context.
/// Follows the fragment parsing strategy for the given namespace.
/// </summary>
/// <param name="source">The source to parse into a subtree.</param>
/// <returns>The documentElement of the new subtree.</returns>
public abstract IElement ParseSubtree(String source);
/// <inheritdoc />
public IShadowRoot AttachShadow(ShadowRootMode mode = ShadowRootMode.Open)
{
if (TagNames.AllNoShadowRoot.Contains(_localName))
{
throw new DomException(DomError.NotSupported);
}
if (ShadowRoot != null)
{
throw new DomException(DomError.InvalidState);
}
_shadowRoot = new ShadowRoot(this, mode);
return _shadowRoot;
}
/// <inheritdoc />
public IElement? QuerySelector(String selectors) => ChildNodes.QuerySelector(selectors, this);
/// <inheritdoc />
public IHtmlCollection<IElement> QuerySelectorAll(String selectors) => ChildNodes.QuerySelectorAll(selectors, this);
/// <inheritdoc />
public IHtmlCollection<IElement> GetElementsByClassName(String classNames) => ChildNodes.GetElementsByClassName(classNames);
/// <inheritdoc />
public IHtmlCollection<IElement> GetElementsByTagName(String tagName) => ChildNodes.GetElementsByTagName(tagName);
/// <inheritdoc />
public IHtmlCollection<IElement> GetElementsByTagNameNS(String? namespaceURI, String tagName) => ChildNodes.GetElementsByTagName(namespaceURI, tagName);
/// <inheritdoc />
public Boolean Matches(String selectorText)
{
var parser = Context.GetService<ICssSelectorParser>()!;
var sg = parser.ParseSelector(selectorText) ?? throw new DomException(DomError.Syntax);
return sg.Match(this, this);
}
/// <inheritdoc />
public IElement? Closest(String selectorText)
{
var parser = Context.GetService<ICssSelectorParser>()!;
var sg = parser.ParseSelector(selectorText) ?? throw new DomException(DomError.Syntax);
var node = (IElement)this;
while (node != null)
{
if (sg.Match(node, node))
{
return node;
}
else
{
node = node.ParentElement;
}
}
return null;
}
/// <inheritdoc />
public Boolean HasAttribute(String name)
{
if (_namespace.Is(NamespaceNames.HtmlUri))
{
name = name.HtmlLower();
}
return _attributes.GetNamedItem(name) != null;
}
/// <inheritdoc />
public Boolean HasAttribute(String? namespaceUri, String localName)
{
if (String.IsNullOrEmpty(namespaceUri))
{
namespaceUri = null;
}
return _attributes.GetNamedItem(namespaceUri, localName) != null;
}
/// <inheritdoc />
public String? GetAttribute(String name)
{
if (_namespace.Is(NamespaceNames.HtmlUri))
{
name = name.HtmlLower();
}
return _attributes.GetNamedItem(name)?.Value;
}
/// <inheritdoc />
public String? GetAttribute(String? namespaceUri, String localName)
{
if (String.IsNullOrEmpty(namespaceUri))
{
namespaceUri = null;
}
return _attributes.GetNamedItem(namespaceUri, localName)?.Value;
}
/// <inheritdoc />
public void SetAttribute(String name, String value)
{
if (value != null)
{
if (!name.IsXmlName())
{
throw new DomException(DomError.InvalidCharacter);
}
if (_namespace.Is(NamespaceNames.HtmlUri))
{
name = name.HtmlLower();
}
this.SetOwnAttribute(name, value);
}
else
{
RemoveAttribute(name);
}
}
/// <inheritdoc />
public void SetAttribute(String? namespaceUri, String name, String value)
{
if (value != null)
{
GetPrefixAndLocalName(name, ref namespaceUri, out var prefix, out var localName);
_attributes.SetNamedItem(new Attr(prefix, localName, value, namespaceUri));
}
else
{
RemoveAttribute(namespaceUri, name);
}
}
/// <summary>
/// Adds an attribute.
/// </summary>
/// <param name="attr">The attribute to add.</param>
public void AddAttribute(Attr attr)
{
attr.Container = _attributes;
_attributes.FastAddItem(attr);
}
/// <inheritdoc />
public Boolean RemoveAttribute(String name)
{
if (_namespace.Is(NamespaceNames.HtmlUri))
{
name = name.HtmlLower();
}
return _attributes.RemoveNamedItemOrDefault(name) != null;
}
/// <inheritdoc />
public Boolean RemoveAttribute(String? namespaceUri, String localName)
{
if (String.IsNullOrEmpty(namespaceUri))
{
namespaceUri = null;
}
return _attributes.RemoveNamedItemOrDefault(namespaceUri, localName) != null;
}
/// <inheritdoc />
public void Prepend(params INode[] nodes)
{
this.PrependNodes(nodes);
}
/// <inheritdoc />
public void Append(params INode[] nodes)
{
this.AppendNodes(nodes);
}
/// <inheritdoc />
public override Boolean Equals(INode? otherNode)
{
if (otherNode is IElement otherElement)
{
return NamespaceUri.Is(otherElement.NamespaceUri) &&
_attributes.SameAs(otherElement.Attributes) &&
base.Equals(otherNode);
}
return false;
}
/// <inheritdoc />
public void Before(params INode[] nodes) => this.InsertBefore(nodes);
/// <inheritdoc />
public void After(params INode[] nodes) => this.InsertAfter(nodes);
/// <inheritdoc />
public void Replace(params INode[] nodes) => this.ReplaceWith(nodes);
/// <inheritdoc />
public void Remove() => this.RemoveFromParent();
/// <inheritdoc />
public void Insert(AdjacentPosition position, String html)
{
var useThis = position == AdjacentPosition.AfterBegin || position == AdjacentPosition.BeforeEnd;
var context = useThis ? this : Parent as Element ?? throw new DomException("The element has no parent.");
var nodes = new DocumentFragment(context, html);
switch (position)
{
case AdjacentPosition.BeforeBegin:
Parent!.InsertBefore(nodes, this);
break;
case AdjacentPosition.AfterEnd:
Parent!.InsertChild(Parent.IndexOf(this) + 1, nodes);
break;
case AdjacentPosition.AfterBegin:
InsertChild(0, nodes);
break;
case AdjacentPosition.BeforeEnd:
AppendChild(nodes);
break;
}
}
/// <inheritdoc />
public override Node Clone(Document owner, Boolean deep)
{
var node = new AnyElement(owner, LocalName, _prefix, _namespace, Flags);
CloneElement(node, owner, deep);
return node;
}
#endregion
#region Internal Methods
internal virtual void SetupElement()
{
var attrs = _attributes;
if (attrs.Length > 0)
{
var observers = Context.GetServices<IAttributeObserver>();
foreach (var attr in attrs)
{
var name = attr.LocalName;
var value = attr.Value;
foreach (var observer in observers)
{
observer.NotifyChange(this, name, value);
}
}
}
}
internal void AttributeChanged(String localName, String? namespaceUri, String? oldValue, String? newValue)
{
if (namespaceUri is null)
{
var observers = Context.GetServices<IAttributeObserver>();
foreach (var observer in observers)
{
observer.NotifyChange(this, localName, newValue);
}
}
Owner.QueueMutation(MutationRecord.Attributes(
target: this,
attributeName: localName,
attributeNamespace: namespaceUri,
previousValue: oldValue));
}
internal void UpdateClassList(String value) => _classList?.Update(value);
#endregion
#region Helpers
/// <inheritdoc />
protected void UpdateAttribute(String name, String value) => this.SetOwnAttribute(name, value, suppressCallbacks: true);
/// <inheritdoc />
protected sealed override String? LocateNamespace(String prefix) => this.LocateNamespaceFor(prefix);
/// <inheritdoc />
protected sealed override String? LocatePrefix(String namespaceUri) => this.LocatePrefixFor(namespaceUri);
/// <inheritdoc />
protected void CloneElement(Element element, Document owner, Boolean deep)
{
CloneNode(element, owner, deep);
foreach (var attribute in _attributes)
{
var attr = new Attr(attribute.Prefix, attribute.LocalName, attribute.Value, attribute.NamespaceUri);
attr.Container = element._attributes;
element._attributes.FastAddItem(attr);
}
element.SetupElement();
}
#endregion
}
}
| |
namespace AngleSharp.Css.Declarations
{
using AngleSharp.Css.Converters;
using AngleSharp.Css.Dom;
using AngleSharp.Css.Parser;
using AngleSharp.Css.Values;
using AngleSharp.Dom;
using AngleSharp.Text;
using System;
using System.Collections.Generic;
static class ContentDeclaration
{
public static String Name = PropertyNames.Content;
public static IValueConverter Converter = new ContentValueConverter();
public static ICssValue InitialValue = InitialValues.ContentDecl;
public static PropertyFlags Flags = PropertyFlags.None;
sealed class ContentValueConverter : IValueConverter
{
private static readonly Dictionary<String, IContentMode> ContentModes = new Dictionary<String, IContentMode>(StringComparer.OrdinalIgnoreCase)
{
{ CssKeywords.OpenQuote, new OpenQuoteContentMode() },
{ CssKeywords.NoOpenQuote, new NoOpenQuoteContentMode() },
{ CssKeywords.CloseQuote, new CloseQuoteContentMode() },
{ CssKeywords.NoCloseQuote, new NoCloseQuoteContentMode() },
};
public ICssValue Convert(StringSource source)
{
var modes = default(ICssValue[]);
if (source.IsIdentifier(CssKeywords.Normal))
{
modes = new ICssValue[] { new NormalContentMode() };
}
else if (source.IsIdentifier(CssKeywords.None))
{
modes = new ICssValue[] { };
}
else
{
var ms = new List<ICssValue>();
while (!source.IsDone)
{
var t = source.ParseString();
if (t != null)
{
ms.Add(new TextContentMode(t));
source.SkipSpacesAndComments();
continue;
}
var u = source.ParseUri();
if (u != null)
{
ms.Add(new UrlContentMode(u));
source.SkipSpacesAndComments();
continue;
}
var c = source.ParseCounter();
if (c.HasValue)
{
ms.Add(new CounterContentMode(c.Value));
source.SkipSpacesAndComments();
continue;
}
var a = source.ParseAttr();
if (a != null)
{
ms.Add(new AttributeContentMode(a.Attribute));
source.SkipSpacesAndComments();
continue;
}
var m = source.ParseStatic(ContentModes);
if (m.HasValue)
{
ms.Add(m.Value);
source.SkipSpacesAndComments();
continue;
}
return null;
}
modes = ms.ToArray();
}
if (modes != null)
{
return new ContentValue(modes);
}
return null;
}
private sealed class ContentValue : ICssValue
{
private ICssValue[] _modes;
public ContentValue(ICssValue[] modes)
{
_modes = modes;
}
public String CssText => _modes.Length == 0 ? CssKeywords.None : _modes.Join(" ");
}
private interface IContentMode : ICssValue
{
String Stringify(IElement element);
}
/// <summary>
/// Computes to none for the :before and :after pseudo-elements.
/// </summary>
private sealed class NormalContentMode : IContentMode
{
public String CssText => CssKeywords.Normal;
public String Stringify(IElement element)
{
return String.Empty;
}
}
/// <summary>
/// The value is replaced by the open quote string from the quotes
/// property.
/// </summary>
private sealed class OpenQuoteContentMode : IContentMode
{
public String CssText => CssKeywords.OpenQuote;
public String Stringify(IElement element)
{
return String.Empty;
}
}
/// <summary>
/// The value is replaced by the close string from the quotes
/// property.
/// </summary>
private sealed class CloseQuoteContentMode : IContentMode
{
public String CssText => CssKeywords.CloseQuote;
public String Stringify(IElement element)
{
return String.Empty;
}
}
/// <summary>
/// Introduces no content, but increments the level of nesting for
/// quotes.
/// </summary>
private sealed class NoOpenQuoteContentMode : IContentMode
{
public String CssText => CssKeywords.NoOpenQuote;
public String Stringify(IElement element)
{
return String.Empty;
}
}
/// <summary>
/// Introduces no content, but decrements the level of nesting for
/// quotes.
/// </summary>
private sealed class NoCloseQuoteContentMode : IContentMode
{
public String CssText => CssKeywords.NoCloseQuote;
public String Stringify(IElement element)
{
return String.Empty;
}
}
/// <summary>
/// Text content.
/// </summary>
private sealed class TextContentMode : IContentMode
{
private readonly String _text;
public TextContentMode(String text)
{
_text = text;
}
public String CssText => _text.CssString();
public String Stringify(IElement element)
{
return _text;
}
}
/// <summary>
/// The generated text is the value of all counters with the given name
/// in scope at this pseudo-element, from outermost to innermost
/// separated by the specified string.
/// </summary>
private sealed class CounterContentMode : IContentMode
{
private readonly CounterDefinition _counter;
public CounterContentMode(CounterDefinition counter)
{
_counter = counter;
}
public String CssText => _counter.CssText;
public String Stringify(IElement element)
{
return String.Empty;
}
}
/// <summary>
/// Returns the value of the element's attribute X as a string. If
/// there is no attribute X, an empty string is returned.
/// </summary>
private sealed class AttributeContentMode : IContentMode
{
private readonly String _attribute;
public AttributeContentMode(String attribute)
{
_attribute = attribute;
}
public String CssText => FunctionNames.Attr.CssFunction(_attribute);
public String Stringify(IElement element)
{
return element.GetAttribute(_attribute) ?? String.Empty;
}
}
/// <summary>
/// The value is a URI that designates an external resource (such as an
/// image). If the resource or image can't be displayed, it is either
/// ignored or some placeholder shows up.
/// </summary>
private sealed class UrlContentMode : IContentMode
{
private readonly CssUrlValue _url;
public UrlContentMode(CssUrlValue url)
{
_url = url;
}
public String CssText => _url.CssText;
public String Stringify(IElement element)
{
return String.Empty;
}
}
}
}
}
| |
using NUnit.Framework;
using Revolver.Core;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Globalization;
using Sitecore.SecurityModel;
using Cmd = Revolver.Core.Commands;
namespace Revolver.Test
{
[TestFixture]
[Category("ChangeItem")]
public class ChangeItem : BaseCommandTest
{
Item _testTreeRoot = null;
Item _germanLanguageDef = null;
bool _revertLanguage = false;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
_revertLanguage = !TestUtil.IsGermanRegistered(_context);
if (_revertLanguage)
_germanLanguageDef = TestUtil.RegisterGermanLanaguage(_context);
using(new SecurityDisabler())
{
InitContent();
_testTreeRoot = TestUtil.CreateContentFromFile("TestResources\\narrow tree with duplicate names.xml", _testRoot);
}
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
if (_testRoot != null)
{
using (new SecurityDisabler())
{
_testRoot.Delete();
}
}
if (_revertLanguage)
{
using (new SecurityDisabler())
{
_germanLanguageDef.Delete();
}
}
}
protected void ProcessTest(Item context, string path, CommandStatus expectedStatus, ID expectedContext, Language language = null, Sitecore.Data.Version version = null)
{
var cmd = new Cmd.ChangeItem();
InitCommand(cmd);
cmd.PathOrID = path;
_context.CurrentItem = context;
var prevPath = "/" + context.Database.Name + context.Paths.FullPath;
var result = cmd.Run();
Assert.AreEqual(expectedStatus, result.Status);
Assert.AreEqual(expectedContext, _context.CurrentItem.ID);
if (expectedStatus == CommandStatus.Success)
Assert.AreEqual(prevPath, _context.EnvironmentVariables["prevpath"]);
if (language != null)
Assert.AreEqual(language, _context.CurrentItem.Language);
if (version != null)
Assert.AreEqual(version, _context.CurrentItem.Version);
}
[Test]
public void NoPath()
{
ProcessTest(_testTreeRoot, string.Empty, CommandStatus.Failure, _testTreeRoot.ID);
}
[Test]
public void RelativeValidChild()
{
ProcessTest(_testTreeRoot, "Sycorax", CommandStatus.Success, _testTreeRoot.Axes.GetChild("Sycorax").ID);
}
[Test]
public void RelativeInvalidChild()
{
ProcessTest(_testTreeRoot, "i hope this name doesnt exist", CommandStatus.Failure, _testTreeRoot.ID);
}
[Test]
public void RelativeValidGrandChild()
{
ProcessTest(_testTreeRoot, "Umbriel/Ymir", CommandStatus.Success, _testTreeRoot.Axes.SelectSingleItem("Umbriel/Ymir").ID);
}
[Test]
public void RelativeInvalidGrandChild()
{
ProcessTest(_testTreeRoot, "Umbriel/i hope this name doesnt exist", CommandStatus.Failure, _testTreeRoot.ID);
}
[Test]
public void RelativeValidAncestor()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Umbriel/Ymir");
ProcessTest(item, "../..", CommandStatus.Success, _testTreeRoot.ID);
}
[Test]
public void RelativeValid()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Umbriel/Ymir");
ProcessTest(item, "../../Juliet", CommandStatus.Success, _testTreeRoot.Axes.SelectSingleItem("Juliet").ID);
}
[Test]
public void RelativeInvalid()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Umbriel/Ymir");
ProcessTest(item, "../../boo", CommandStatus.Failure, item.ID);
}
[Test]
public void ValidId()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Umbriel/Ymir");
ProcessTest(_context.CurrentDatabase.GetRootItem(), item.ID.ToString(), CommandStatus.Success, item.ID);
}
[Test]
public void InvalidId()
{
var item = _context.CurrentDatabase.GetRootItem();
ProcessTest(item, ID.NewID.ToString(), CommandStatus.Failure, item.ID);
}
[Test]
public void MalformedId()
{
ProcessTest(_testTreeRoot, "{bbb-eee-444-aaa}", CommandStatus.Failure, _testTreeRoot.ID);
}
[Test]
public void SameNameValidIndex()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Umbriel");
var expectedItem = _testTreeRoot.Axes.SelectSingleItem("Umbriel/*[@title='Skoll 1']");
ProcessTest(item, "skoll[1]", CommandStatus.Success, expectedItem.ID);
}
[Test]
public void SameNameInvalidIndex()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Umbriel");
ProcessTest(item, "skoll[5]", CommandStatus.Failure, item.ID);
}
[Test]
public void NotSameNameWithValidIndex()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Umbriel");
var expectedItem = _testTreeRoot.Axes.SelectSingleItem("Umbriel/Ymir");
ProcessTest(item, "Ymir[0]", CommandStatus.Success, expectedItem.ID);
}
[Test]
public void NotSameNameWithInvalidIndex()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Umbriel");
ProcessTest(item, "Ymir[1]", CommandStatus.Failure, item.ID);
}
[Test]
public void RelativeByValidChildIndex()
{
var expectedItem = _testTreeRoot.Axes.SelectSingleItem("Sycorax");
ProcessTest(_testTreeRoot, "[1]", CommandStatus.Success, expectedItem.ID);
}
[Test]
public void RelativeByInvalidChildIndex()
{
var expectedItem = _testTreeRoot.Axes.SelectSingleItem("Sycorax");
ProcessTest(_testTreeRoot, "[7]", CommandStatus.Failure, _testTreeRoot.ID);
}
[Test]
public void AbsoluteValid()
{
var expectedItem = _testTreeRoot.Axes.SelectSingleItem("Sycorax");
ProcessTest(_testTreeRoot, expectedItem.Paths.FullPath, CommandStatus.Success, expectedItem.ID);
}
[Test]
public void AbsoluteInvalid()
{
ProcessTest(_testTreeRoot, "/sitecore/content/nothing/doesnt/exist", CommandStatus.Failure, _testTreeRoot.ID);
}
[Test]
public void RelativeShorthandChildExists()
{
ProcessTest(_testTreeRoot, "s", CommandStatus.Success, _testTreeRoot.Axes.GetChild("Sycorax").ID);
}
[Test]
public void RelativeShorthandChildDoesntExist()
{
ProcessTest(_testTreeRoot, "z", CommandStatus.Failure, _testTreeRoot.ID);
}
[Test]
public void ToRoot()
{
ProcessTest(_testTreeRoot, "/", CommandStatus.Success, _context.CurrentDatabase.GetRootItem().ID);
}
[Test]
public void ToCoreDB()
{
using (new SecurityDisabler())
{
var db = Factory.GetDatabase("core");
var coreContent = db.GetItem("/sitecore/content");
ProcessTest(_testTreeRoot, "/core/sitecore/content", CommandStatus.Success, coreContent.ID);
}
}
[Test]
public void ToWebDB()
{
var db = Factory.GetDatabase("web");
var webMediaLibrary = db.GetItem("/sitecore/media library");
ProcessTest(_testTreeRoot, "/web/sitecore/media library", CommandStatus.Success, webMediaLibrary.ID);
}
[Test]
public void ToMasterDB()
{
var db = Factory.GetDatabase("master");
var masterSystem = db.GetItem("/sitecore/system");
ProcessTest(_testTreeRoot, "/master/sitecore/system", CommandStatus.Success, masterSystem.ID);
}
[Test]
public void ChangeContextLanguage()
{
var language = Language.Parse("de");
var germanVersion = _context.CurrentDatabase.GetItem(_testTreeRoot.ID, language);
ProcessTest(_testTreeRoot, ":de", CommandStatus.Success, germanVersion.ID, language);
}
[Test]
public void ChangeLanguageRelative()
{
var language = Language.Parse("de");
var currentLanguageItem = _testTreeRoot.Axes.SelectSingleItem("Umbriel/Ymir");
var germanVersion = _context.CurrentDatabase.GetItem(currentLanguageItem.ID, language);
ProcessTest(_testTreeRoot, "umbriel/ymir:de", CommandStatus.Success, germanVersion.ID, language);
}
[Test]
public void ChangeLanguageAbsolute()
{
var language = Language.Parse("de");
var currentLanguageItem = _testTreeRoot.Axes.SelectSingleItem("Umbriel/Ymir");
var germanVersion = _context.CurrentDatabase.GetItem(currentLanguageItem.ID, language);
ProcessTest(_testTreeRoot, currentLanguageItem.Paths.FullPath + ":de", CommandStatus.Success, germanVersion.ID, language);
}
[Test]
public void ChangeLanguageInvalid()
{
ProcessTest(_testTreeRoot, ":foo", CommandStatus.Failure, _testTreeRoot.ID, _testTreeRoot.Language, _testTreeRoot.Version);
}
[Test]
public void ChangeContextVersion()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Juliet");
ProcessTest(item, "::1", CommandStatus.Success, item.ID, null, Sitecore.Data.Version.First);
}
[Test]
public void ChangeContextVersionFromLatest()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Juliet");
ProcessTest(item, "::-1", CommandStatus.Success, item.ID, null, Sitecore.Data.Version.Parse(2));
}
[Test]
public void ChangeVersionRelative()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Juliet");
ProcessTest(_testTreeRoot, "Juliet::2", CommandStatus.Success, item.ID, null, Sitecore.Data.Version.Parse(2));
}
[Test]
public void ChangeVersionAbsolute()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Juliet");
ProcessTest(_testTreeRoot, item.Paths.FullPath + "::2", CommandStatus.Success, item.ID, null, Sitecore.Data.Version.Parse(2));
}
[Test]
public void ChangeVersionInvalidFromEnd()
{
ProcessTest(_testTreeRoot, "::-300", CommandStatus.Failure, _testTreeRoot.ID, _testTreeRoot.Language, _testTreeRoot.Version);
}
[Test]
public void ChangeVersionAndLanguageRelative()
{
var item = _testTreeRoot.Axes.SelectSingleItem("Juliet");
ProcessTest(_testTreeRoot, "Juliet:de:1", CommandStatus.Success, item.ID, Language.Parse("de"), Sitecore.Data.Version.Parse(1));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Concurrent;
using System.Reflection;
using System.Diagnostics;
namespace Signum.Utilities
{
public static class PolymorphicMerger
{
public static T? Inheritance<T>(KeyValuePair<Type, T?> currentValue, KeyValuePair<Type, T?> baseValue, List<KeyValuePair<Type, T?>> newInterfacesValues) where T : class
{
return currentValue.Value ?? baseValue.Value;
}
public static T? InheritanceAndInterfaces<T>(KeyValuePair<Type, T?> currentValue, KeyValuePair<Type, T?> baseValue, List<KeyValuePair<Type, T?>> newInterfacesValues) where T : class
{
var result = currentValue.Value ?? baseValue.Value;
if (result != null)
return result;
var conflicts = newInterfacesValues.Where(a => a.Value != null);
if (conflicts.Count() > 1)
throw new InvalidOperationException("Ambiguity for type {0} between interfaces {1}".FormatWith(currentValue.Key.Name, newInterfacesValues.CommaAnd(t => t.Key.Name)));
return conflicts.Select(a => a.Value).SingleOrDefaultEx();
}
public static Dictionary<K, V>? InheritDictionary<K, V>(KeyValuePair<Type, Dictionary<K, V>?> currentValue, KeyValuePair<Type, Dictionary<K, V>?> baseValue, List<KeyValuePair<Type, Dictionary<K, V>?>> newInterfacesValues)
where K : notnull
{
if (currentValue.Value == null && baseValue.Value == null)
return null;
Dictionary<K, V> newDictionary = new Dictionary<K, V>();
if (baseValue.Value != null)
newDictionary.AddRange(baseValue.Value!);
if (currentValue.Value != null)
newDictionary.SetRange(currentValue.Value!);
return newDictionary;
}
public static Dictionary<K, V>? InheritDictionaryInterfaces<K, V>(KeyValuePair<Type, Dictionary<K, V>?> currentValue, KeyValuePair<Type, Dictionary<K, V>?> baseValue, List<KeyValuePair<Type, Dictionary<K, V>?>> newInterfacesValues)
where K : notnull
{
if (currentValue.Value == null && baseValue.Value == null && newInterfacesValues.All(a => a.Value == null))
return null;
Dictionary<K, V> newDictionary = new Dictionary<K, V>();
if (baseValue.Value != null)
newDictionary.AddRange(baseValue.Value!);
if (currentValue.Value != null)
newDictionary.SetRange(currentValue.Value!);
var interfaces = newInterfacesValues.Where(a => a.Value != null) as IEnumerable<KeyValuePair<Type, Dictionary<K, V>>>;
var keys = interfaces.SelectMany(inter => inter.Value.Keys).Distinct().Except(newDictionary.Keys);
foreach (var item in keys)
{
var types = interfaces.Where(a => a.Value!.ContainsKey(item)).Select(a => new { a.Key, Value = a.Value![item] }).ToList();
var groups = types.GroupBy(t => t.Value);
if (groups.Count() > 1)
throw new InvalidOperationException("Ambiguity for key {0} in type {0} between interfaces {1}".FormatWith(item, currentValue.Key.Name, types.CommaAnd(t => t.Key!.Name)));
newDictionary[item] = groups.Single().Key;
}
return newDictionary;
}
}
public delegate T? PolymorphicMerger<T>(KeyValuePair<Type, T?> currentValue, KeyValuePair<Type, T?> baseValue, List<KeyValuePair<Type, T?>> newInterfacesValues) where T : class;
public class Polymorphic<T> where T : class
{
Dictionary<Type, T> definitions = new Dictionary<Type, T>();
ConcurrentDictionary<Type, T?> cached = new ConcurrentDictionary<Type, T?>();
PolymorphicMerger<T> merger;
Type? minimumType;
public bool ContainsKey(Type type)
{
return definitions.ContainsKey(type);
}
bool IsAllowed(Type type)
{
return minimumType == null || minimumType.IsAssignableFrom(type);
}
void AssertAllowed(Type type)
{
if (!IsAllowed(type))
throw new InvalidOperationException("{0} is not a {1}".FormatWith(type.Name, minimumType!.Name));
}
public Polymorphic(PolymorphicMerger<T>? merger = null, Type? minimumType = null)
{
this.merger = merger ?? PolymorphicMerger.Inheritance<T>;
this.minimumType = minimumType ?? GetDefaultType(typeof(T));
}
private static Type? GetDefaultType(Type type)
{
if (!typeof(Delegate).IsAssignableFrom(type))
return null;
MethodInfo mi = type.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance)!;
var param = mi.GetParameters().FirstOrDefault();
if (param == null)
return null;
return param.ParameterType;
}
public T GetValue(Type type)
{
var result = TryGetValue(type);
if (result == null)
throw new InvalidOperationException("No value defined for type {0}".FormatWith(type));
return result;
}
public T? TryGetValue(Type type)
{
AssertAllowed(type);
return cached.GetOrAdd(type, TryGetValueInternal);
}
public T? GetDefinition(Type type)
{
AssertAllowed(type);
return definitions.TryGetC(type);
}
T? TryGetValueInternal(Type type)
{
if (cached.TryGetValue(type, out T? result))
return result;
var baseValue = type.BaseType == null || !IsAllowed(type.BaseType) ? null : TryGetValue(type.BaseType);
var currentValue = definitions.TryGetC(type);
if (minimumType != null && !minimumType.IsInterface)
return merger(KeyValuePair.Create(type, currentValue), KeyValuePair.Create(type.BaseType!, baseValue), new List<KeyValuePair<Type, T?>>());
IEnumerable<Type> interfaces = type.GetInterfaces().Where(IsAllowed);
if (type.BaseType != null)
interfaces = interfaces.Except(type.BaseType.GetInterfaces());
return merger(KeyValuePair.Create(type, currentValue), KeyValuePair.Create(type.BaseType!, baseValue), interfaces.Select(inter => KeyValuePair.Create(inter, TryGetValue(inter))).ToList());
}
public void SetDefinition(Type type, T value)
{
AssertAllowed(type);
definitions[type] = value;
ClearCache();
}
public void ClearCache()
{
cached.Clear();
}
public IEnumerable<Type> OverridenTypes
{
get { return definitions.Keys; }
}
public IEnumerable<T> OverridenValues
{
get { return definitions.Values; }
}
public Dictionary<Type, T> ExportDefinitions()
{
return this.definitions;
}
public void ImportDefinitions(Dictionary<Type, T> dic)
{
this.definitions = dic;
this.ClearCache();
}
}
[DebuggerStepThrough]
public static class PolymorphicExtensions
{
public static T GetOrAddDefinition<T>(this Polymorphic<T> polymorphic, Type type) where T : class, new()
{
T? value = polymorphic.GetDefinition(type);
if (value != null)
return value;
value = new T();
polymorphic.SetDefinition(type, value);
return value;
}
public static void Register<T, S>(this Polymorphic<Action<T>> polymorphic, Action<S> action) where S : T
where T : class
{
polymorphic.SetDefinition(typeof(S), t => action((S)t));
}
public static void Register<T, S, P0>(this Polymorphic<Action<T, P0>> polymorphic, Action<S, P0> action) where S : T
where T : class
{
polymorphic.SetDefinition(typeof(S), (t, p0) => action((S)t, p0));
}
public static void Register<T, S, P0, P1>(this Polymorphic<Action<T, P0, P1>> polymorphic, Action<S, P0, P1> action) where S : T
where T : class
{
polymorphic.SetDefinition(typeof(S), (t, p0, p1) => action((S)t, p0, p1));
}
public static void Register<T, S, P0, P1, P2>(this Polymorphic<Action<T, P0, P1, P2>> polymorphic, Action<S, P0, P1, P2> action) where S : T
where T : class
{
polymorphic.SetDefinition(typeof(S), (t, p0, p1, p2) => action((S)t, p0, p1, p2));
}
public static void Register<T, S, P0, P1, P2, P3>(this Polymorphic<Action<T, P0, P1, P2, P3>> polymorphic, Action<S, P0, P1, P2, P3> action) where S : T
where T : class
{
polymorphic.SetDefinition(typeof(S), (t, p0, p1, p2, p3) => action((S)t, p0, p1, p2, p3));
}
public static void Register<T, S, R>(this Polymorphic<Func<T, R>> polymorphic, Func<S, R> func) where S : T
where T : class
{
polymorphic.SetDefinition(typeof(S), t => func((S)t));
}
public static void Register<T, S, P0, R>(this Polymorphic<Func<T, P0, R>> polymorphic, Func<S, P0, R> func) where S : T
where T : class
{
polymorphic.SetDefinition(typeof(S), (t, p0) => func((S)t, p0));
}
public static void Register<T, S, P0, P1, R>(this Polymorphic<Func<T, P0, P1, R>> polymorphic, Func<S, P0, P1, R> func) where S : T
where T : class
{
polymorphic.SetDefinition(typeof(S), (t, p0, p1) => func((S)t, p0, p1));
}
public static void Register<T, S, P0, P1, P2, R>(this Polymorphic<Func<T, P0, P1, P2, R>> polymorphic, Func<S, P0, P1, P2, R> func) where S : T
where T : class
{
polymorphic.SetDefinition(typeof(S), (t, p0, p1, p2) => func((S)t, p0, p1, p2));
}
public static void Register<T, S, P0, P1, P2, P3, R>(this Polymorphic<Func<T, P0, P1, P2, P3, R>> polymorphic, Func<S, P0, P1, P2, P3, R> func) where S : T
where T : class
{
polymorphic.SetDefinition(typeof(S), (t, p0, p1, p2, p3) => func((S)t, p0, p1, p2, p3));
}
public static void Invoke<T>(this Polymorphic<Action<T>> polymorphic, T instance) where T : notnull
{
var action = polymorphic.GetValue(instance.GetType());
action(instance);
}
public static void Invoke<T, P0>(this Polymorphic<Action<T, P0>> polymorphic, T instance, P0 p0) where T : notnull
{
var action = polymorphic.GetValue(instance.GetType());
action(instance, p0);
}
public static void Invoke<T, P0, P1>(this Polymorphic<Action<T, P0, P1>> polymorphic, T instance, P0 p0, P1 p1) where T : notnull
{
var action = polymorphic.GetValue(instance.GetType());
action(instance, p0, p1);
}
public static void Invoke<T, P0, P1, P2>(this Polymorphic<Action<T, P0, P1, P2>> polymorphic, T instance, P0 p0, P1 p1, P2 p2) where T : notnull
{
var action = polymorphic.GetValue(instance.GetType());
action(instance, p0, p1, p2);
}
public static void Invoke<T, P0, P1, P2, P3>(this Polymorphic<Action<T, P0, P1, P2, P3>> polymorphic, T instance, P0 p0, P1 p1, P2 p2, P3 p3) where T : notnull
{
var action = polymorphic.GetValue(instance.GetType());
action(instance, p0, p1, p2, p3);
}
public static R Invoke<T, R>(this Polymorphic<Func<T, R>> polymorphic, T instance) where T : notnull
{
var func = polymorphic.GetValue(instance.GetType());
return func(instance);
}
public static R Invoke<T, P0, R>(this Polymorphic<Func<T, P0, R>> polymorphic, T instance, P0 p0) where T : notnull
{
var func = polymorphic.GetValue(instance.GetType());
return func(instance, p0);
}
public static R Invoke<T, P0, P1, R>(this Polymorphic<Func<T, P0, P1, R>> polymorphic, T instance, P0 p0, P1 p1) where T : notnull
{
var func = polymorphic.GetValue(instance.GetType());
return func(instance, p0, p1);
}
public static R Invoke<T, P0, P1, P2, R>(this Polymorphic<Func<T, P0, P1, P2, R>> polymorphic, T instance, P0 p0, P1 p1, P2 p2) where T : notnull
{
var func = polymorphic.GetValue(instance.GetType());
return func(instance, p0, p1, p2);
}
public static R Invoke<T, P0, P1, P2, P3, R>(this Polymorphic<Func<T, P0, P1, P2, P3, R>> polymorphic, T instance, P0 p0, P1 p1, P2 p2, P3 p3) where T : notnull
{
var func = polymorphic.GetValue(instance.GetType());
return func(instance, p0, p1, p2, p3);
}
}
}
| |
//! \file ImageDCF.cs
//! \date Fri Jul 29 14:07:15 2016
//! \brief AliceSoft incremental image format.
//
// Copyright (C) 2016-2018 by morkt
//
// 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.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Windows.Media;
using GameRes.Compression;
using GameRes.Utility;
namespace GameRes.Formats.AliceSoft
{
internal class DcfMetaData : ImageMetaData
{
public string BaseName;
public long DataOffset;
}
[Export(typeof(ImageFormat))]
public class DcfFormat : ImageFormat
{
public override string Tag { get { return "DCF"; } }
public override string Description { get { return "AliceSoft System incremental image"; } }
public override uint Signature { get { return 0x20666364; } } // 'dcf '
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
stream.Seek (4, SeekOrigin.Current);
uint header_size = stream.ReadUInt32();
long data_pos = stream.Position + header_size;
if (stream.ReadInt32() != 1)
return null;
uint width = stream.ReadUInt32();
uint height = stream.ReadUInt32();
int bpp = stream.ReadInt32();
int name_length = stream.ReadInt32();
if (name_length <= 0)
return null;
int shift = (name_length % 7) + 1;
var name_bits = stream.ReadBytes (name_length);
for (int i = 0; i < name_length; ++i)
{
name_bits[i] = Binary.RotByteL (name_bits[i], shift);
}
return new DcfMetaData
{
Width = width,
Height = height,
BPP = bpp,
BaseName = Encodings.cp932.GetString (name_bits),
DataOffset = data_pos,
};
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
using (var reader = new DcfReader (stream, (DcfMetaData)info))
{
reader.Unpack();
return ImageData.Create (info, reader.Format, null, reader.Data, reader.Stride);
}
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("DcfFormat.Write not implemented");
}
}
internal sealed class DcfReader : IDisposable
{
IBinaryStream m_input;
DcfMetaData m_info;
byte[] m_output;
byte[] m_mask = null;
byte[] m_base = null;
int m_overlay_bpp;
int m_base_bpp;
static readonly Lazy<ImageFormat> s_QntFormat = new Lazy<ImageFormat> (() => ImageFormat.FindByTag ("QNT"));
internal ImageFormat Qnt { get { return s_QntFormat.Value; } }
public byte[] Data { get { return m_output; } }
public PixelFormat Format { get; private set; }
public int Stride { get; private set; }
public DcfReader (IBinaryStream input, DcfMetaData info)
{
m_input = input;
m_info = info;
}
public void Unpack ()
{
long next_pos = m_info.DataOffset;
for (;;)
{
m_input.Position = next_pos;
uint id = m_input.ReadUInt32();
next_pos += 8 + m_input.ReadUInt32();
if (0x6C646664 == id) // 'dfdl'
{
int unpacked_size = m_input.ReadInt32();
if (unpacked_size <= 0)
continue;
m_mask = new byte[unpacked_size];
using (var input = new ZLibStream (m_input.AsStream, CompressionMode.Decompress, true))
input.Read (m_mask, 0, unpacked_size);
}
else if (0x64676364 == id) // 'dcgd'
break;
}
long qnt_pos = m_input.Position;
if (m_input.ReadUInt32() != Qnt.Signature)
throw new InvalidFormatException();
using (var reg = new StreamRegion (m_input.AsStream, qnt_pos, true))
using (var qnt = new BinaryStream (reg, m_input.Name))
{
var qnt_info = Qnt.ReadMetaData (qnt) as QntMetaData;
if (null == qnt_info)
throw new InvalidFormatException();
var overlay = new QntFormat.Reader (reg, qnt_info);
overlay.Unpack();
m_overlay_bpp = overlay.BPP;
if (m_mask != null)
ReadBaseImage();
if (m_base != null)
{
m_output = ApplyOverlay (overlay.Data);
SetFormat ((int)m_info.Width, m_overlay_bpp);
}
else
{
m_output = overlay.Data;
SetFormat ((int)qnt_info.Width, m_overlay_bpp);
}
}
}
void SetFormat (int width, int bpp)
{
Format = 24 == bpp ? PixelFormats.Bgr24 : PixelFormats.Bgra32;
Stride = width * (bpp / 8);
}
byte[] ApplyOverlay (byte[] overlay)
{
int blocks_x = (int)m_info.Width / 0x10;
int blocks_y = (int)m_info.Height / 0x10;
int base_step = m_base_bpp / 8;
int overlay_step = m_overlay_bpp / 8;
int base_stride = (int)m_info.Width * base_step;
int overlay_stride = (int)m_info.Width * overlay_step;
int mask_pos = 4;
for (int y = 0; y < blocks_y; ++y)
{
int base_pos = y * 0x10 * base_stride;
int dst_pos = y * 0x10 * overlay_stride;
for (int x = 0; x < blocks_x; ++x)
{
if (0 == m_mask[mask_pos++])
continue;
for (int by = 0; by < 0x10; ++by)
{
int src = base_pos + by * base_stride + x * 0x10 * base_step;
int dst = dst_pos + by * overlay_stride + x * 0x10 * overlay_step;
for (int bx = 0; bx < 0x10; ++bx)
{
overlay[dst ] = m_base[src ];
overlay[dst+1] = m_base[src+1];
overlay[dst+2] = m_base[src+2];
if (4 == overlay_step)
{
overlay[dst+3] = 4 == base_step ? m_base[src+3] : (byte)0xFF;
}
src += base_step;
dst += overlay_step;
}
}
}
}
return overlay;
}
void ReadBaseImage ()
{
try
{
string dir_name = VFS.GetDirectoryName (m_info.FileName);
string base_name = Path.ChangeExtension (m_info.BaseName, "qnt");
base_name = VFS.CombinePath (dir_name, base_name);
using (var base_file = VFS.OpenBinaryStream (base_name))
{
var base_info = Qnt.ReadMetaData (base_file) as QntMetaData;
if (null != base_info && m_info.Width == base_info.Width && m_info.Height == base_info.Height)
{
base_info.FileName = base_name;
var reader = new QntFormat.Reader (base_file.AsStream, base_info);
reader.Unpack();
m_base_bpp = reader.BPP;
m_base = reader.Data;
}
}
}
catch (Exception X)
{
Trace.WriteLine (X.Message, "[DCF]");
}
}
#region IDisposable Members
public void Dispose ()
{
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Keywords.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System.Xml;
namespace System.Xml.Xsl.Xslt {
internal class KeywordsTable {
public XmlNameTable NameTable;
public string AnalyzeString;
public string ApplyImports;
public string ApplyTemplates;
public string Assembly;
public string Attribute;
public string AttributeSet;
public string CallTemplate;
public string CaseOrder;
public string CDataSectionElements;
public string Character;
public string CharacterMap;
public string Choose;
public string Comment;
public string Copy;
public string CopyOf;
public string Count;
public string DataType;
public string DecimalFormat;
public string DecimalSeparator;
public string DefaultCollation;
public string DefaultValidation;
public string Digit;
public string DisableOutputEscaping;
public string DocTypePublic;
public string DocTypeSystem;
public string Document;
public string Element;
public string Elements;
public string Encoding;
public string ExcludeResultPrefixes;
public string ExtensionElementPrefixes;
public string Fallback;
public string ForEach;
public string ForEachGroup;
public string Format;
public string From;
public string Function;
public string GroupingSeparator;
public string GroupingSize;
public string Href;
public string Id;
public string If;
public string ImplementsPrefix;
public string Import;
public string ImportSchema;
public string Include;
public string Indent;
public string Infinity;
public string Key;
public string Lang;
public string Language;
public string LetterValue;
public string Level;
public string Match;
public string MatchingSubstring;
public string MediaType;
public string Message;
public string Method;
public string MinusSign;
public string Mode;
public string Name;
public string Namespace;
public string NamespaceAlias;
public string NaN;
public string NextMatch;
public string NonMatchingSubstring;
public string Number;
public string OmitXmlDeclaration;
public string Order;
public string Otherwise;
public string Output;
public string OutputCharacter;
public string OutputVersion;
public string Param;
public string PatternSeparator;
public string Percent;
public string PerformSort;
public string PerMille;
public string PreserveSpace;
public string Priority;
public string ProcessingInstruction;
public string Required;
public string ResultDocument;
public string ResultPrefix;
public string Script;
public string Select;
public string Separator;
public string Sequence;
public string Sort;
public string Space;
public string Standalone;
public string StripSpace;
public string Stylesheet;
public string StylesheetPrefix;
public string Template;
public string Terminate;
public string Test;
public string Text;
public string Transform;
public string UrnMsxsl;
public string UriXml;
public string UriXsl;
public string UriWdXsl;
public string Use;
public string UseAttributeSets;
public string UseWhen;
public string Using;
public string Value;
public string ValueOf;
public string Variable;
public string Version;
public string When;
public string WithParam;
public string Xml;
public string Xmlns;
public string XPathDefaultNamespace;
public string ZeroDigit;
public KeywordsTable(XmlNameTable nt) {
this.NameTable = nt;
AnalyzeString = nt.Add("analyze-string");
ApplyImports = nt.Add("apply-imports");
ApplyTemplates = nt.Add("apply-templates");
Assembly = nt.Add("assembly");
Attribute = nt.Add("attribute");
AttributeSet = nt.Add("attribute-set");
CallTemplate = nt.Add("call-template");
CaseOrder = nt.Add("case-order");
CDataSectionElements = nt.Add("cdata-section-elements");
Character = nt.Add("character");
CharacterMap = nt.Add("character-map");
Choose = nt.Add("choose");
Comment = nt.Add("comment");
Copy = nt.Add("copy");
CopyOf = nt.Add("copy-of");
Count = nt.Add("count");
DataType = nt.Add("data-type");
DecimalFormat = nt.Add("decimal-format");
DecimalSeparator = nt.Add("decimal-separator");
DefaultCollation = nt.Add("default-collation");
DefaultValidation = nt.Add("default-validation");
Digit = nt.Add("digit");
DisableOutputEscaping = nt.Add("disable-output-escaping");
DocTypePublic = nt.Add("doctype-public");
DocTypeSystem = nt.Add("doctype-system");
Document = nt.Add("document");
Element = nt.Add("element");
Elements = nt.Add("elements");
Encoding = nt.Add("encoding");
ExcludeResultPrefixes = nt.Add("exclude-result-prefixes");
ExtensionElementPrefixes = nt.Add("extension-element-prefixes");
Fallback = nt.Add("fallback");
ForEach = nt.Add("for-each");
ForEachGroup = nt.Add("for-each-group");
Format = nt.Add("format");
From = nt.Add("from");
Function = nt.Add("function");
GroupingSeparator = nt.Add("grouping-separator");
GroupingSize = nt.Add("grouping-size");
Href = nt.Add("href");
Id = nt.Add("id");
If = nt.Add("if");
ImplementsPrefix = nt.Add("implements-prefix");
Import = nt.Add("import");
ImportSchema = nt.Add("import-schema");
Include = nt.Add("include");
Indent = nt.Add("indent");
Infinity = nt.Add("infinity");
Key = nt.Add("key");
Lang = nt.Add("lang");
Language = nt.Add("language");
LetterValue = nt.Add("letter-value");
Level = nt.Add("level");
Match = nt.Add("match");
MatchingSubstring = nt.Add("matching-substring");
MediaType = nt.Add("media-type");
Message = nt.Add("message");
Method = nt.Add("method");
MinusSign = nt.Add("minus-sign");
Mode = nt.Add("mode");
Name = nt.Add("name");
Namespace = nt.Add("namespace");
NamespaceAlias = nt.Add("namespace-alias");
NaN = nt.Add("NaN");
NextMatch = nt.Add("next-match");
NonMatchingSubstring = nt.Add("non-matching-substring");
Number = nt.Add("number");
OmitXmlDeclaration = nt.Add("omit-xml-declaration");
Otherwise = nt.Add("otherwise");
Order = nt.Add("order");
Output = nt.Add("output");
OutputCharacter = nt.Add("output-character");
OutputVersion = nt.Add("output-version");
Param = nt.Add("param");
PatternSeparator = nt.Add("pattern-separator");
Percent = nt.Add("percent");
PerformSort = nt.Add("perform-sort");
PerMille = nt.Add("per-mille");
PreserveSpace = nt.Add("preserve-space");
Priority = nt.Add("priority");
ProcessingInstruction = nt.Add("processing-instruction");
Required = nt.Add("required");
ResultDocument = nt.Add("result-document");
ResultPrefix = nt.Add("result-prefix");
Script = nt.Add("script");
Select = nt.Add("select");
Separator = nt.Add("separator");
Sequence = nt.Add("sequence");
Sort = nt.Add("sort");
Space = nt.Add("space");
Standalone = nt.Add("standalone");
StripSpace = nt.Add("strip-space");
Stylesheet = nt.Add("stylesheet");
StylesheetPrefix = nt.Add("stylesheet-prefix");
Template = nt.Add("template");
Terminate = nt.Add("terminate");
Test = nt.Add("test");
Text = nt.Add("text");
Transform = nt.Add("transform");
UrnMsxsl = nt.Add(XmlReservedNs.NsMsxsl);
UriXml = nt.Add(XmlReservedNs.NsXml);
UriXsl = nt.Add(XmlReservedNs.NsXslt);
UriWdXsl = nt.Add(XmlReservedNs.NsWdXsl);
Use = nt.Add("use");
UseAttributeSets = nt.Add("use-attribute-sets");
UseWhen = nt.Add("use-when");
Using = nt.Add("using");
Value = nt.Add("value");
ValueOf = nt.Add("value-of");
Variable = nt.Add("variable");
Version = nt.Add("version");
When = nt.Add("when");
WithParam = nt.Add("with-param");
Xml = nt.Add("xml");
Xmlns = nt.Add("xmlns");
XPathDefaultNamespace = nt.Add("xpath-default-namespace");
ZeroDigit = nt.Add("zero-digit");
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: Directory
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Exposes routines for enumerating through a
** directory.
**
** April 11,2000
**
===========================================================*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Text;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Threading;
#if FEATURE_MACL
using System.Security.AccessControl;
#endif
namespace System.IO {
[ComVisible(true)]
public static class Directory {
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DirectoryInfo GetParent(String path)
{
if (path==null)
throw new ArgumentNullException("path");
if (path.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"), "path");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
String s = Path.GetDirectoryName(fullPath);
if (s==null)
return null;
return new DirectoryInfo(s);
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DirectoryInfo CreateDirectory(String path) {
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
Contract.EndContractBlock();
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
return InternalCreateDirectoryHelper(path, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static DirectoryInfo UnsafeCreateDirectory(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
Contract.EndContractBlock();
return InternalCreateDirectoryHelper(path, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static DirectoryInfo InternalCreateDirectoryHelper(String path, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(path.Length != 0);
String fullPath = Path.GetFullPathInternal(path);
// You need read access to the directory to be returned back and write access to all the directories
// that you need to create. If we fail any security checks we will not create any directories at all.
// We attempt to create directories only after all the security checks have passed. This is avoid doing
// a demand at every level.
String demandDir = GetDemandDir(fullPath, true);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandDir);
state.EnsureState(); // do the check on the AppDomainManager to make sure this is allowed
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false);
#endif
InternalCreateDirectory(fullPath, path, null, checkHost);
return new DirectoryInfo(fullPath, false);
}
#if FEATURE_MACL
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DirectoryInfo CreateDirectory(String path, DirectorySecurity directorySecurity) {
if (path==null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
// You need read access to the directory to be returned back and write access to all the directories
// that you need to create. If we fail any security checks we will not create any directories at all.
// We attempt to create directories only after all the security checks have passed. This is avoid doing
// a demand at every level.
String demandDir = GetDemandDir(fullPath, true);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false );
InternalCreateDirectory(fullPath, path, directorySecurity);
return new DirectoryInfo(fullPath, false);
}
#endif // FEATURE_MACL
// Input to this method should already be fullpath. This method will ensure that we append
// the trailing slash only when appropriate and when thisDirOnly is specified append a "."
// at the end of the path to indicate that the demand is only for the fullpath and not
// everything underneath it.
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.None, ResourceScope.None)]
internal static String GetDemandDir(string fullPath, bool thisDirOnly)
{
String demandPath;
if (thisDirOnly) {
if (fullPath.EndsWith( Path.DirectorySeparatorChar )
|| fullPath.EndsWith( Path.AltDirectorySeparatorChar ) )
demandPath = fullPath + ".";
else
demandPath = fullPath + Path.DirectorySeparatorCharAsString + ".";
}
else {
if (!(fullPath.EndsWith( Path.DirectorySeparatorChar )
|| fullPath.EndsWith( Path.AltDirectorySeparatorChar )) )
demandPath = fullPath + Path.DirectorySeparatorCharAsString;
else
demandPath = fullPath;
}
return demandPath;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj)
{
InternalCreateDirectory(fullPath, path, dirSecurityObj, false);
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal unsafe static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, bool checkHost)
{
#if FEATURE_MACL
DirectorySecurity dirSecurity = (DirectorySecurity)dirSecurityObj;
#endif // FEATURE_MACL
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && Path.IsDirectorySeparator(fullPath[length - 1]))
length--;
int lengthRoot = Path.GetRootLength(fullPath);
// For UNC paths that are only // or ///
if (length == 2 && Path.IsDirectorySeparator(fullPath[1]))
throw new IOException(Environment.GetResourceString("IO.IO_CannotCreateDirectory", path));
// We can save a bunch of work if the directory we want to create already exists. This also
// saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the
// final path is accessable and the directory already exists. For example, consider trying
// to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo
// and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar
// and fail to due so, causing an exception to be thrown. This is not what we want.
if (InternalExists(fullPath)) {
return;
}
List<string> stackDir = new List<string>();
// Attempt to figure out which directories don't exist, and only
// create the ones we need. Note that InternalExists may fail due
// to Win32 ACL's preventing us from seeing a directory, and this
// isn't threadsafe.
bool somepathexists = false;
if (length > lengthRoot) { // Special case root (fullpath = X:\\)
int i = length-1;
while (i >= lengthRoot && !somepathexists) {
String dir = fullPath.Substring(0, i+1);
if (!InternalExists(dir)) // Create only the ones missing
stackDir.Add(dir);
else
somepathexists = true;
while (i > lengthRoot && fullPath[i] != Path.DirectorySeparatorChar && fullPath[i] != Path.AltDirectorySeparatorChar) i--;
i--;
}
}
int count = stackDir.Count;
if (stackDir.Count != 0)
{
String [] securityList = new String[stackDir.Count];
stackDir.CopyTo(securityList, 0);
for (int j = 0 ; j < securityList.Length; j++)
securityList[j] += "\\."; // leaf will never have a slash at the end
// Security check for all directories not present only.
#if !FEATURE_PAL && FEATURE_MACL
AccessControlActions control = (dirSecurity == null) ? AccessControlActions.None : AccessControlActions.Change;
new FileIOPermission(FileIOPermissionAccess.Write, control, securityList, false, false ).Demand();
#else
#if FEATURE_CORECLR
if (checkHost)
{
foreach (String demandPath in securityList)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, String.Empty, demandPath);
state.EnsureState();
}
}
#else
new FileIOPermission(FileIOPermissionAccess.Write, securityList, false, false ).Demand();
#endif
#endif //!FEATURE_PAL && FEATURE_MACL
}
// If we were passed a DirectorySecurity, convert it to a security
// descriptor and set it in he call to CreateDirectory.
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
#if FEATURE_MACL
if (dirSecurity != null) {
secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
// For ACL's, get the security descriptor from the FileSecurity.
byte[] sd = dirSecurity.GetSecurityDescriptorBinaryForm();
byte * bytesOnStack = stackalloc byte[sd.Length];
Buffer.Memcpy(bytesOnStack, 0, sd, 0, sd.Length);
secAttrs.pSecurityDescriptor = bytesOnStack;
}
#endif
bool r = true;
int firstError = 0;
String errorString = path;
// If all the security checks succeeded create all the directories
while (stackDir.Count > 0) {
String name = stackDir[stackDir.Count - 1];
stackDir.RemoveAt(stackDir.Count - 1);
if (name.Length >= Path.MAX_DIRECTORY_PATH)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
r = Win32Native.CreateDirectory(name, secAttrs);
if (!r && (firstError == 0)) {
int currentError = Marshal.GetLastWin32Error();
// While we tried to avoid creating directories that don't
// exist above, there are at least two cases that will
// cause us to see ERROR_ALREADY_EXISTS here. InternalExists
// can fail because we didn't have permission to the
// directory. Secondly, another thread or process could
// create the directory between the time we check and the
// time we try using the directory. Thirdly, it could
// fail because the target does exist, but is a file.
if (currentError != Win32Native.ERROR_ALREADY_EXISTS)
firstError = currentError;
else {
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
if (File.InternalExists(name) || (!InternalExists(name, out currentError) && currentError == Win32Native.ERROR_ACCESS_DENIED)) {
firstError = currentError;
// Give the user a nice error message, but don't leak path information.
try {
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, GetDemandDir(name, true));
state.EnsureState();
}
#else
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, GetDemandDir(name, true)).Demand();
#endif // FEATURE_CORECLR
errorString = name;
}
catch(SecurityException) {}
}
}
}
}
// We need this check to mask OS differences
// Handle CreateDirectory("X:\\foo") when X: doesn't exist. Similarly for n/w paths.
if ((count == 0) && !somepathexists) {
String root = InternalGetDirectoryRoot(fullPath);
if (!InternalExists(root)) {
// Extract the root from the passed in path again for security.
__Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, InternalGetDirectoryRoot(path));
}
return;
}
// Only throw an exception if creating the exact directory we
// wanted failed to work correctly.
if (!r && (firstError != 0)) {
__Error.WinIOError(firstError, errorString);
}
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static bool Exists(String path)
{
return InternalExistsHelper(path, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static bool UnsafeExists(String path)
{
return InternalExistsHelper(path, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static bool InternalExistsHelper(String path, bool checkHost) {
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
// Get fully qualified file name ending in \* for security check
String fullPath = Path.GetFullPathInternal(path);
String demandPath = GetDemandDir(fullPath, true);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandPath);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandPath, false, false);
#endif
return InternalExists(fullPath);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException)
{
#if !FEATURE_PAL
Contract.Assert(false, "Ignore this assert and send a repro to [....]. This assert was tracking purposes only.");
#endif //!FEATURE_PAL
}
return false;
}
// Determine whether path describes an existing directory
// on disk, avoiding security checks.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static bool InternalExists(String path) {
int lastError = Win32Native.ERROR_SUCCESS;
return InternalExists(path, out lastError);
}
// Determine whether path describes an existing directory
// on disk, avoiding security checks.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static bool InternalExists(String path, out int lastError) {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
lastError = File.FillAttributeInfo(path, ref data, false, true);
return (lastError == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetCreationTime(String path,DateTime creationTime)
{
SetCreationTimeUtc(path, creationTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public unsafe static void SetCreationTimeUtc(String path,DateTime creationTimeUtc)
{
using (SafeFileHandle handle = Directory.OpenHandle(path)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, &fileTime, null, null);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetCreationTime(String path)
{
return File.GetCreationTime(path);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetCreationTimeUtc(String path)
{
return File.GetCreationTimeUtc(path);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetLastWriteTime(String path,DateTime lastWriteTime)
{
SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public unsafe static void SetLastWriteTimeUtc(String path,DateTime lastWriteTimeUtc)
{
using (SafeFileHandle handle = Directory.OpenHandle(path)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, null, null, &fileTime);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastWriteTime(String path)
{
return File.GetLastWriteTime(path);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastWriteTimeUtc(String path)
{
return File.GetLastWriteTimeUtc(path);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetLastAccessTime(String path,DateTime lastAccessTime)
{
SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public unsafe static void SetLastAccessTimeUtc(String path,DateTime lastAccessTimeUtc)
{
using (SafeFileHandle handle = Directory.OpenHandle(path)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, null, &fileTime, null);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastAccessTime(String path)
{
return File.GetLastAccessTime(path);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastAccessTimeUtc(String path)
{
return File.GetLastAccessTimeUtc(path);
}
#if FEATURE_MACL
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DirectorySecurity GetAccessControl(String path)
{
return new DirectorySecurity(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DirectorySecurity GetAccessControl(String path, AccessControlSections includeSections)
{
return new DirectorySecurity(path, includeSections);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetAccessControl(String path, DirectorySecurity directorySecurity)
{
if (directorySecurity == null)
throw new ArgumentNullException("directorySecurity");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
directorySecurity.Persist(fullPath);
}
#endif
// Returns an array of filenames in the DirectoryInfo specified by path
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] GetFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt").
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] GetFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static String[] InternalGetFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static String[] UnsafeGetFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption, false);
}
// Returns an array of Directories in the current directory.
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] GetDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] GetDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static String[] InternalGetDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<String[]>() != null);
return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static String[] UnsafeGetDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<String[]>() != null);
return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption, false);
}
// Returns an array of strongly typed FileSystemInfo entries in the path
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] GetFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] GetFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, searchOption);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static String[] InternalGetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption, true);
}
// Private class that holds search data that is passed around
// in the heap based stack recursion
internal sealed class SearchData
{
public SearchData(String fullPath, String userPath, SearchOption searchOption)
{
Contract.Requires(fullPath != null && fullPath.Length > 0);
Contract.Requires(userPath != null && userPath.Length > 0);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
this.fullPath = fullPath;
this.userPath = userPath;
this.searchOption = searchOption;
}
public readonly string fullPath; // Fully qualified search path excluding the search criteria in the end (ex, c:\temp\bar\foo)
public readonly string userPath; // User specified path (ex, bar\foo)
public readonly SearchOption searchOption;
}
// Returns fully qualified user path of dirs/files that matches the search parameters.
// For recursive search this method will search through all the sub dirs and execute
// the given search criteria against every dir.
// For all the dirs/files returned, it will then demand path discovery permission for
// their parent folders (it will avoid duplicate permission checks)
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static String[] InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(userPathOriginal != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<String> enble = FileSystemEnumerableFactory.CreateFileNameIterator(
path, userPathOriginal, searchPattern,
includeFiles, includeDirs, searchOption, checkHost);
List<String> fileList = new List<String>(enble);
return fileList.ToArray();
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> EnumerateDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, searchOption);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static IEnumerable<String> InternalEnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return EnumerateFileSystemNames(path, searchPattern, searchOption, false, true);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> EnumerateFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, "*", SearchOption.TopDirectoryOnly);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, searchOption);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static IEnumerable<String> InternalEnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> EnumerateFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, searchOption);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static IEnumerable<String> InternalEnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, true);
}
private static IEnumerable<String> EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption,
bool includeFiles, bool includeDirs)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return FileSystemEnumerableFactory.CreateFileNameIterator(path, path, searchPattern,
includeFiles, includeDirs, searchOption, true);
}
// Retrieves the names of the logical drives on this machine in the
// form "C:\".
//
// Your application must have System Info permission.
//
[System.Security.SecuritySafeCritical] // auto-generated
public static String[] GetLogicalDrives()
{
Contract.Ensures(Contract.Result<String[]>() != null);
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
int drives = Win32Native.GetLogicalDrives();
if (drives==0)
__Error.WinIOError();
uint d = (uint)drives;
int count = 0;
while (d != 0) {
if (((int)d & 1) != 0) count++;
d >>= 1;
}
String[] result = new String[count];
char[] root = new char[] {'A', ':', '\\'};
d = (uint)drives;
count = 0;
while (d != 0) {
if (((int)d & 1) != 0) {
result[count++] = new String(root);
}
d >>= 1;
root[0]++;
}
return result;
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String GetDirectoryRoot(String path) {
if (path==null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
String root = fullPath.Substring(0, Path.GetRootLength(fullPath));
String demandPath = GetDemandDir(root, true);
#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, path, demandPath);
state.EnsureState();
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, demandPath, false, false);
#endif
return root;
}
internal static String InternalGetDirectoryRoot(String path) {
if (path == null) return null;
return path.Substring(0, Path.GetRootLength(path));
}
/*===============================CurrentDirectory===============================
**Action: Provides a getter and setter for the current directory. The original
** current DirectoryInfo is the one from which the process was started.
**Returns: The current DirectoryInfo (from the getter). Void from the setter.
**Arguments: The current DirectoryInfo to which to switch to the setter.
**Exceptions:
==============================================================================*/
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String GetCurrentDirectory()
{
return InternalGetCurrentDirectory(true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static String UnsafeGetCurrentDirectory()
{
return InternalGetCurrentDirectory(false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static String InternalGetCurrentDirectory(bool checkHost)
{
StringBuilder sb = StringBuilderCache.Acquire(Path.MAX_PATH + 1);
if (Win32Native.GetCurrentDirectory(sb.Capacity, sb) == 0)
__Error.WinIOError();
String currentDirectory = sb.ToString();
// Note that if we have somehow put our command prompt into short
// file name mode (ie, by running edlin or a DOS grep, etc), then
// this will return a short file name.
if (currentDirectory.IndexOf('~') >= 0) {
int r = Win32Native.GetLongPathName(currentDirectory, sb, sb.Capacity);
if (r == 0 || r >= Path.MAX_PATH) {
int errorCode = Marshal.GetLastWin32Error();
if (r >= Path.MAX_PATH)
errorCode = Win32Native.ERROR_FILENAME_EXCED_RANGE;
if (errorCode != Win32Native.ERROR_FILE_NOT_FOUND &&
errorCode != Win32Native.ERROR_PATH_NOT_FOUND &&
errorCode != Win32Native.ERROR_INVALID_FUNCTION && // by design - enough said.
errorCode != Win32Native.ERROR_ACCESS_DENIED)
__Error.WinIOError(errorCode, String.Empty);
}
currentDirectory = sb.ToString();
}
StringBuilderCache.Release(sb);
String demandPath = GetDemandDir(currentDirectory, true);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPath);
state.EnsureState();
}
#else
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, new String[] { demandPath }, false, false ).Demand();
#endif
return currentDirectory;
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetCurrentDirectory(String path)
{
if (path==null)
throw new ArgumentNullException("value");
if (path.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
Contract.EndContractBlock();
if (path.Length >= Path.MAX_PATH)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
// This will have some large effects on the rest of the runtime
// and other appdomains in this process. Demand unmanaged code.
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
String fulldestDirName = Path.GetFullPathInternal(path);
if (!Win32Native.SetCurrentDirectory(fulldestDirName)) {
// If path doesn't exist, this sets last error to 2 (File
// not Found). LEGACY: This may potentially have worked correctly
// on Win9x, maybe.
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Win32Native.ERROR_FILE_NOT_FOUND)
errorCode = Win32Native.ERROR_PATH_NOT_FOUND;
__Error.WinIOError(errorCode, fulldestDirName);
}
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Move(String sourceDirName,String destDirName) {
InternalMove(sourceDirName, destDirName, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeMove(String sourceDirName,String destDirName) {
InternalMove(sourceDirName, destDirName, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalMove(String sourceDirName,String destDirName,bool checkHost) {
if (sourceDirName==null)
throw new ArgumentNullException("sourceDirName");
if (sourceDirName.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceDirName");
if (destDirName==null)
throw new ArgumentNullException("destDirName");
if (destDirName.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName");
Contract.EndContractBlock();
String fullsourceDirName = Path.GetFullPathInternal(sourceDirName);
String sourcePath = GetDemandDir(fullsourceDirName, false);
if (sourcePath.Length >= Path.MAX_DIRECTORY_PATH)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
String fulldestDirName = Path.GetFullPathInternal(destDirName);
String destPath = GetDemandDir(fulldestDirName, false);
if (destPath.Length >= Path.MAX_DIRECTORY_PATH)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
#if FEATURE_CORECLR
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceDirName, sourcePath);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, destPath);
sourceState.EnsureState();
destState.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, sourcePath, false, false);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, destPath, false, false);
#endif
if (String.Compare(sourcePath, destPath, StringComparison.OrdinalIgnoreCase) == 0)
throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent"));
String sourceRoot = Path.GetPathRoot(sourcePath);
String destinationRoot = Path.GetPathRoot(destPath);
if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0)
throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot"));
if (!Win32Native.MoveFile(sourceDirName, destDirName))
{
int hr = Marshal.GetLastWin32Error();
if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // Source dir not found
{
hr = Win32Native.ERROR_PATH_NOT_FOUND;
__Error.WinIOError(hr, fullsourceDirName);
}
// This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons.
if (hr == Win32Native.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp.
throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", sourceDirName), Win32Native.MakeHRFromErrorCode(hr));
__Error.WinIOError(hr, String.Empty);
}
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Delete(String path)
{
String fullPath = Path.GetFullPathInternal(path);
Delete(fullPath, path, false, true);
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Delete(String path, bool recursive)
{
String fullPath = Path.GetFullPathInternal(path);
Delete(fullPath, path, recursive, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeDelete(String path, bool recursive)
{
String fullPath = Path.GetFullPathInternal(path);
Delete(fullPath, path, recursive, false);
}
// Called from DirectoryInfo as well. FullPath is fully qualified,
// while the user path is used for feedback in exceptions.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void Delete(String fullPath, String userPath, bool recursive, bool checkHost)
{
String demandPath;
// If not recursive, do permission check only on this directory
// else check for the whole directory structure rooted below
demandPath = GetDemandDir(fullPath, !recursive);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, userPath, demandPath);
state.EnsureState();
}
#else
// Make sure we have write permission to this directory
new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandPath }, false, false ).Demand();
#endif
// Do not recursively delete through reparse points. Perhaps in a
// future version we will add a new flag to control this behavior,
// but for now we're much safer if we err on the conservative side.
// This applies to symbolic links and mount points.
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = File.FillAttributeInfo(fullPath, ref data, false, true);
if (dataInitialised != 0) {
// Ensure we throw a DirectoryNotFoundException.
if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND)
dataInitialised = Win32Native.ERROR_PATH_NOT_FOUND;
__Error.WinIOError(dataInitialised, fullPath);
}
if (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0)
recursive = false;
DeleteHelper(fullPath, userPath, recursive, true);
}
// Note that fullPath is fully qualified, while userPath may be
// relative. Use userPath for all exception messages to avoid leaking
// fully qualified path information.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void DeleteHelper(String fullPath, String userPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
bool r;
int hr;
Exception ex = null;
// Do not recursively delete through reparse points. Perhaps in a
// future version we will add a new flag to control this behavior,
// but for now we're much safer if we err on the conservative side.
// This applies to symbolic links and mount points.
// Note the logic to check whether fullPath is a reparse point is
// in Delete(String, String, bool), and will set "recursive" to false.
// Note that Win32's DeleteFile and RemoveDirectory will just delete
// the reparse point itself.
if (recursive) {
Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
// Open a Find handle
using (SafeFindHandle hnd = Win32Native.FindFirstFile(fullPath+Path.DirectorySeparatorCharAsString+"*", data)) {
if (hnd.IsInvalid) {
hr = Marshal.GetLastWin32Error();
__Error.WinIOError(hr, fullPath);
}
do {
bool isDir = (0!=(data.dwFileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY));
if (isDir) {
// Skip ".", "..".
if (data.cFileName.Equals(".") || data.cFileName.Equals(".."))
continue;
// Recurse for all directories, unless they are
// reparse points. Do not follow mount points nor
// symbolic links, but do delete the reparse point
// itself.
bool shouldRecurse = (0 == (data.dwFileAttributes & (int) FileAttributes.ReparsePoint));
if (shouldRecurse) {
String newFullPath = Path.InternalCombine(fullPath, data.cFileName);
String newUserPath = Path.InternalCombine(userPath, data.cFileName);
try {
DeleteHelper(newFullPath, newUserPath, recursive, false);
}
catch(Exception e) {
if (ex == null) {
ex = e;
}
}
}
else {
// Check to see if this is a mount point, and
// unmount it.
if (data.dwReserved0 == Win32Native.IO_REPARSE_TAG_MOUNT_POINT) {
// Use full path plus a trailing '\'
String mountPoint = Path.InternalCombine(fullPath, data.cFileName + Path.DirectorySeparatorChar);
r = Win32Native.DeleteVolumeMountPoint(mountPoint);
if (!r) {
hr = Marshal.GetLastWin32Error();
if (hr != Win32Native.ERROR_PATH_NOT_FOUND) {
try {
__Error.WinIOError(hr, data.cFileName);
}
catch(Exception e) {
if (ex == null) {
ex = e;
}
}
}
}
}
// RemoveDirectory on a symbolic link will
// remove the link itself.
String reparsePoint = Path.InternalCombine(fullPath, data.cFileName);
r = Win32Native.RemoveDirectory(reparsePoint);
if (!r) {
hr = Marshal.GetLastWin32Error();
if (hr != Win32Native.ERROR_PATH_NOT_FOUND) {
try {
__Error.WinIOError(hr, data.cFileName);
}
catch(Exception e) {
if (ex == null) {
ex = e;
}
}
}
}
}
}
else {
String fileName = Path.InternalCombine(fullPath, data.cFileName);
r = Win32Native.DeleteFile(fileName);
if (!r) {
hr = Marshal.GetLastWin32Error();
if (hr != Win32Native.ERROR_FILE_NOT_FOUND) {
try {
__Error.WinIOError(hr, data.cFileName);
}
catch (Exception e) {
if (ex == null) {
ex = e;
}
}
}
}
}
} while (Win32Native.FindNextFile(hnd, data));
// Make sure we quit with a sensible error.
hr = Marshal.GetLastWin32Error();
}
if (ex != null)
throw ex;
if (hr!=0 && hr!=Win32Native.ERROR_NO_MORE_FILES)
__Error.WinIOError(hr, userPath);
}
r = Win32Native.RemoveDirectory(fullPath);
if (!r) {
hr = Marshal.GetLastWin32Error();
if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code.
hr = Win32Native.ERROR_PATH_NOT_FOUND;
// This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons.
if (hr == Win32Native.ERROR_ACCESS_DENIED)
throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", userPath));
// don't throw the DirectoryNotFoundException since this is a subdir and there could be a ----
// between two Directory.Delete callers
if (hr == Win32Native.ERROR_PATH_NOT_FOUND && !throwOnTopLevelDirectoryNotFound)
return;
__Error.WinIOError(hr, fullPath);
}
}
// WinNT only. Win9x this code will not work.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static SafeFileHandle OpenHandle(String path)
{
String fullPath = Path.GetFullPathInternal(path);
String root = Path.GetPathRoot(fullPath);
if (root == fullPath && root[1] == Path.VolumeSeparatorChar)
throw new ArgumentException(Environment.GetResourceString("Arg_PathIsVolume"));
#if !FEATURE_CORECLR
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, GetDemandDir(fullPath, true), false, false);
#endif
SafeFileHandle handle = Win32Native.SafeCreateFile (
fullPath,
GENERIC_WRITE,
(FileShare) (FILE_SHARE_WRITE|FILE_SHARE_DELETE),
null,
FileMode.Open,
FILE_FLAG_BACKUP_SEMANTICS,
IntPtr.Zero
);
if (handle.IsInvalid) {
int hr = Marshal.GetLastWin32Error();
__Error.WinIOError(hr, fullPath);
}
return handle;
}
private const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
private const int GENERIC_WRITE = unchecked((int)0x40000000);
private const int FILE_SHARE_WRITE = 0x00000002;
private const int FILE_SHARE_DELETE = 0x00000004;
private const int OPEN_EXISTING = 0x00000003;
private const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
}
}
| |
//#define NO_PROMPT_TO_SAVE
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Globalization;
using Microsoft.Win32;
using System.Windows.Media.Effects;
using System.Diagnostics;
using Xceed.Wpf.Toolkit;
using CartographerLibrary;
using CartographerUtilities;
using System.Text.RegularExpressions;
namespace Cartographer
{
/// <summary>
/// Main application window
/// </summary>
public partial class MainWindow : System.Windows.Window
{
#region Class Members
WindowStateManager windowStateManager;
MruManager mruManager;
string fileName; // name of currently opened file
public BeaconInfo selectedInfo { get; set; }
#endregion Class Members
#region Constructor
public MainWindow()
{
// Create WindowStateManager and associate is with ApplicationSettings.MainWindowStateInfo.
// This allows to set initial window state and track state changes in
// the Settings.MainWindowStateInfo instance.
// When application is closed, ApplicationSettings is saved with new window state
// information. Next time this information is loaded from XML file.
windowStateManager = new WindowStateManager(SettingsManager.ApplicationSettings.MainWindowStateInfo, this);
BeaconInfoList beacons = BeaconInfoManager.Instance().beacons;
this.DataContext = beacons;
if (!Application.Current.Resources.Contains("selectedInfo"))
Application.Current.Resources.Add("selectedInfo", selectedInfo);
InitializeComponent();
SubscribeToEvents();
UpdateTitle();
InitializeDrawingCanvas();
InitializeMruList();
}
#endregion Constructor
#region Application Commands
/// <summary>
/// New file
/// </summary>
void FileNewCommand(object sender, ExecutedRoutedEventArgs args)
{
if (!PromptToSave())
{
return;
}
drawingCanvas.Clear();
fileName = "";
UpdateTitle();
}
/// <summary>
/// Exit
/// </summary>
void FileCloseCommand(object sender, ExecutedRoutedEventArgs args)
{
this.Close();
}
/// <summary>
/// Open file
/// </summary>
void FileOpenMapCommand(object sender, ExecutedRoutedEventArgs args)
{
if (!PromptToSave())
{
return;
}
// Show Open File dialog
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Minimap maps (*.map)|*.map";
dlg.DefaultExt = "map";
dlg.InitialDirectory = SettingsManager.ApplicationSettings.InitialDirectory;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog().GetValueOrDefault() != true)
return;
try { drawingCanvas.LoadMap(dlg.FileName); }
catch (DrawingCanvasException e)
{
ShowError(e.Message);
mruManager.Delete(dlg.FileName);
return;
}
this.fileName = dlg.FileName;
UpdateTitle();
// Remember initial directory
SettingsManager.ApplicationSettings.InitialDirectory = System.IO.Path.GetDirectoryName(dlg.FileName);
}
/// <summary>
/// Open file
/// </summary>
void FileOpenMapImageCommand(object sender, ExecutedRoutedEventArgs args)
{
if (!PromptToSave())
{
return;
}
// Show Open File dialog
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Image files (*.png, *.jpg, *.jpeg, *.gif, *.bmp)|*.png;*.jpg;*.jpeg;*.gif;*.bmp";
//dlg.DefaultExt = "xml";
dlg.InitialDirectory = SettingsManager.ApplicationSettings.InitialDirectory;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog().GetValueOrDefault() != true)
{
return;
}
try
{
// Load file
Uri uri = new Uri(dlg.FileName);
BitmapImage source = new BitmapImage(uri);
imageBackground.Source = source;
double xScale = ActualWidth * 0.8 / source.Width;
double yScale = ActualHeight * 0.8 / source.Height;
drawingCanvas.ActualScale = xScale < yScale ? xScale : yScale;
OpenMapButton.IsEnabled = true;
PromptForWidthAndHeight();
}
catch (DrawingCanvasException e)
{
ShowError(e.Message);
mruManager.Delete(dlg.FileName);
return;
}
// Remember initial directory
SettingsManager.ApplicationSettings.InitialDirectory = System.IO.Path.GetDirectoryName(dlg.FileName);
}
void PromptForWidthAndHeight()
{
MapDimensionsPrompt prompt = new MapDimensionsPrompt { Owner = this };
prompt.ShowDialog();
if (prompt.Next == MapDimensionsPrompt.NextState.New)
{
drawingCanvas.MapWidth = prompt.MapWidth;
drawingCanvas.MapHeight = prompt.MapHeight;
drawingCanvas.MapName = prompt.MapName;
drawingCanvas.Clear();
}
else
{
FileOpenMapCommand(null, null);
drawingCanvas.RefreshClip();
}
}
/// <summary>
/// Save command
/// </summary>
void FileSaveCommand(object sender, ExecutedRoutedEventArgs args)
{
if (string.IsNullOrEmpty(fileName))
{
FileSaveAsCommand(sender, args);
return;
}
Save(fileName);
}
/// <summary>
/// Save As Command
/// </summary>
void FileSaveAsCommand(object sender, ExecutedRoutedEventArgs args)
{
// Show Save File dialog
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Minimap map files (*.map)|*.map";
dlg.OverwritePrompt = true;
dlg.DefaultExt = "map";
dlg.InitialDirectory = SettingsManager.ApplicationSettings.InitialDirectory;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog().GetValueOrDefault() != true)
{
return;
}
// Save
if (!Save(dlg.FileName))
{
return;
}
// Remember initial directory
SettingsManager.ApplicationSettings.InitialDirectory = System.IO.Path.GetDirectoryName(dlg.FileName);
}
/// <summary>
/// Undo command
/// </summary>
void EditUndoCommand(object sender, ExecutedRoutedEventArgs args)
{
drawingCanvas.Undo();
}
/// <summary>
/// Redo command
/// </summary>
void EditRedoCommand(object sender, ExecutedRoutedEventArgs args)
{
drawingCanvas.Redo();
}
#endregion ApplicationCommands
#region Tools Event Handlers
/// <summary>
/// One of Tools menu items is clicked.
/// ToolType enumeration member name is in the item tag.
/// </summary>
void ToolMenuItem_Click(object sender, RoutedEventArgs e)
{
drawingCanvas.Tool = (ToolType)Enum.Parse(typeof(ToolType), ((MenuItem)sender).Tag.ToString());
}
/// <summary>
/// One of Tools toolbar buttons is clicked.
/// ToolType enumeration member name is in the button tag.
///
/// For toolbar buttons I use PreviewMouseDown event instead of Click,
/// because IsChecked property is not handled by standard
/// way. For example, every click on the Pointer button keeps it checked
/// instead of changing state. IsChecked property of every button is bound
/// to DrawingCanvas.Tool property.
/// Using normal Click handler toggles every button, which doesn't
/// match my requirements. So, I catch click in PreviewMouseDown handler
/// and set Handled to true preventing standard IsChecked handling.
///
/// Other way to do the same: handle Click event and set buttons state
/// at application idle time, without binding IsChecked property.
/// </summary>
void ToolButton_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
drawingCanvas.Tool = (ToolType)Enum.Parse(typeof(ToolType), ((System.Windows.Controls.Primitives.ButtonBase)sender).Tag.ToString());
e.Handled = true;
}
#endregion Tools Event Handlers
#region Edit Event Handlers
void menuEditSelectAll_Click(object sender, RoutedEventArgs e)
{
drawingCanvas.SelectAll();
}
void menuEditUnselectAll_Click(object sender, RoutedEventArgs e)
{
drawingCanvas.UnselectAll();
}
void menuEditDelete_Click(object sender, RoutedEventArgs e)
{
drawingCanvas.Delete();
}
void menuEditDeleteAll_Click(object sender, RoutedEventArgs e)
{
drawingCanvas.DeleteAll();
}
void menuEditMoveToFront_Click(object sender, RoutedEventArgs e)
{
drawingCanvas.MoveToFront();
}
void menuEditMoveToBack_Click(object sender, RoutedEventArgs e)
{
drawingCanvas.MoveToBack();
}
void menuEditSetProperties_Click(object sender, RoutedEventArgs e)
{
drawingCanvas.SetProperties();
}
#endregion Edit Event Handlers
#region Properties Event Handlers
/// <summary>
/// Show Font dialog
/// </summary>
void PropertiesFont_Click(object sender, RoutedEventArgs e)
{
Petzold.ChooseFont.FontDialog dlg = new Petzold.ChooseFont.FontDialog();
dlg.Owner = this;
dlg.Background = SystemColors.ControlBrush;
dlg.Title = "Select Font";
dlg.FaceSize = drawingCanvas.TextFontSize;
dlg.Typeface = new Typeface(
new FontFamily(drawingCanvas.TextFontFamilyName),
drawingCanvas.TextFontStyle,
drawingCanvas.TextFontWeight,
drawingCanvas.TextFontStretch);
if (dlg.ShowDialog().GetValueOrDefault() != true)
{
return;
}
// Set new font in drawing canvas
drawingCanvas.TextFontSize = dlg.FaceSize;
drawingCanvas.TextFontFamilyName = dlg.Typeface.FontFamily.ToString();
drawingCanvas.TextFontStyle = dlg.Typeface.Style;
drawingCanvas.TextFontWeight = dlg.Typeface.Weight;
drawingCanvas.TextFontStretch = dlg.Typeface.Stretch;
// Set new font in application settings
SettingsManager.ApplicationSettings.TextFontSize = dlg.FaceSize;
SettingsManager.ApplicationSettings.TextFontFamilyName = dlg.Typeface.FontFamily.ToString();
SettingsManager.ApplicationSettings.TextFontStyle = FontConversions.FontStyleToString(dlg.Typeface.Style);
SettingsManager.ApplicationSettings.TextFontWeight = FontConversions.FontWeightToString(dlg.Typeface.Weight);
SettingsManager.ApplicationSettings.TextFontStretch = FontConversions.FontStretchToString(dlg.Typeface.Stretch);
}
/// <summary>
/// Show Color dialog
/// </summary>
void PropertiesColor_Click(object sender, RoutedEventArgs e)
{
ColorDialog dlg = new ColorDialog();
dlg.Owner = this;
dlg.Color = drawingCanvas.ObjectColor;
if (dlg.ShowDialog().GetValueOrDefault() != true)
{
return;
}
// Set selected color in drawing canvas
// and in application settings
drawingCanvas.ObjectColor = dlg.Color;
SettingsManager.ApplicationSettings.ObjectColor = drawingCanvas.ObjectColor;
}
#endregion Properties Event Handlers
#region Other Event Handlers
/// <summary>
/// File is selected from MRU list
/// </summary>
void mruManager_FileSelected(object sender, MruFileOpenEventArgs e)
{
if (!PromptToSave())
{
return;
}
try
{
// Load file
drawingCanvas.LoadMap(e.FileName);
}
catch (DrawingCanvasException ex)
{
ShowError(ex.Message);
mruManager.Delete(e.FileName);
return;
}
this.fileName = e.FileName;
UpdateTitle();
mruManager.Add(this.fileName);
}
/// <summary>
/// IsDirty is changed
/// </summary>
void drawingCanvas_IsDirtyChanged(object sender, RoutedEventArgs e)
{
UpdateTitle();
}
/// <summary>
/// Check Tools menu items according to active tool
/// </summary>
void menuTools_SubmenuOpened(object sender, RoutedEventArgs e)
{
menuToolsPointer.IsChecked = (drawingCanvas.Tool == ToolType.Pointer);
menuToolsTableBlock.IsChecked = (drawingCanvas.Tool == ToolType.TableBlock);
menuToolsBeacon.IsChecked = (drawingCanvas.Tool == ToolType.Beacon);
menuToolsBarrier.IsChecked = (drawingCanvas.Tool == ToolType.Barrier);
}
/// <summary>
/// Enable Edit menu items according to DrawingCanvas stare
/// </summary>
void menuEdit_SubmenuOpened(object sender, RoutedEventArgs e)
{
menuEditDelete.IsEnabled = drawingCanvas.CanDelete;
menuEditDeleteAll.IsEnabled = drawingCanvas.CanDeleteAll;
menuEditMoveToBack.IsEnabled = drawingCanvas.CanMoveToBack;
menuEditMoveToFront.IsEnabled = drawingCanvas.CanMoveToFront;
menuEditSelectAll.IsEnabled = drawingCanvas.CanSelectAll;
menuEditUnselectAll.IsEnabled = drawingCanvas.CanUnselectAll;
menuEditSetProperties.IsEnabled = drawingCanvas.CanSetProperties;
menuEditUndo.IsEnabled = drawingCanvas.CanUndo;
menuEditRedo.IsEnabled = drawingCanvas.CanRedo;
}
/// <summary>
/// Form is closing - ask to save
/// </summary>
void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!PromptToSave())
{
e.Cancel = true;
}
}
/// <summary>
/// Function executes different actions depending on
/// XAML version.
/// Use one of them in actual program.
/// </summary>
void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
{
// Instead of using control names directly,
// find them dynamically. This allows to compile
// the program with different XAML versions.
Object o = FindName("imageBackground");
if (o == null)
{
// Refresh clip area in the canvas.
// This is required when canvas is used in standalone mode without
// background image.
drawingCanvas.RefreshClip();
return;
}
Image image = o as Image;
if (image == null)
{
return;
}
o = FindName("viewBoxContainer");
if (o == null)
{
return;
}
Viewbox v = o as Viewbox;
if (v == null)
{
return; // precaution
}
// Compute actual scale of image drawn on the screen.
// Image is resized by ViewBox.
//
// Note: when image is placed inside ScrollView with slider,
// the same correction is done in XAML using ActualScale binding.
double viewBoxWidth = v.ActualWidth;
double viewBoxHeight = v.ActualHeight;
double imageWidth = image.Source.Width;
double imageHeight = image.Source.Height;
double scale;
if (viewBoxWidth / imageWidth > viewBoxHeight / imageHeight)
{
scale = viewBoxWidth / imageWidth;
}
else
{
scale = viewBoxHeight / imageHeight;
}
// Apply actual scale to the canvas to keep overlay line width constant.
drawingCanvas.ActualScale = scale;
}
#endregion Other Event Handlers
#region Other Functions
/// <summary>
/// Prompt to save and make Save operation if necessary.
/// </summary>
/// <returns>
/// true - caller can continue (open new file, close program etc.
/// false - caller should cancel current operation.
/// </returns>
bool PromptToSave()
{
#if NO_PROMPT_TO_SAVE
return true;
#else
if (!drawingCanvas.IsDirty)
{
return true; // continue
}
MessageBoxResult result = System.Windows.MessageBox.Show(
this,
"Do you want to save changes?",
Properties.Resources.ApplicationTitle,
MessageBoxButton.YesNoCancel,
MessageBoxImage.Question,
MessageBoxResult.Yes);
switch (result)
{
case MessageBoxResult.Yes:
// Save
FileSaveCommand(null, null); // any better way to do this?
// If Saved succeeded (IsDirty false), return true
return (!drawingCanvas.IsDirty);
case MessageBoxResult.No:
return true; // continue without save
case MessageBoxResult.Cancel:
return false;
default:
return true;
}
#endif
}
/// <summary>
/// Subscribe to different events
/// </summary>
void SubscribeToEvents()
{
this.SizeChanged += new SizeChangedEventHandler(MainWindow_SizeChanged);
this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
drawingCanvas.IsDirtyChanged += new RoutedEventHandler(drawingCanvas_IsDirtyChanged);
// Menu opened - used to set menu items state
menuTools.SubmenuOpened += new RoutedEventHandler(menuTools_SubmenuOpened);
menuEdit.SubmenuOpened += new RoutedEventHandler(menuEdit_SubmenuOpened);
// Tools menu
menuToolsPointer.Click += ToolMenuItem_Click;
menuToolsTableBlock.Click += ToolMenuItem_Click;
menuToolsBeacon.Click += ToolMenuItem_Click;
menuToolsBarrier.Click += ToolMenuItem_Click;
// Tools buttons
buttonToolPointer.PreviewMouseDown += new MouseButtonEventHandler(ToolButton_PreviewMouseDown);
buttonToolTableBlock.PreviewMouseDown += new MouseButtonEventHandler(ToolButton_PreviewMouseDown);
buttonToolBeacon.PreviewMouseDown += new MouseButtonEventHandler(ToolButton_PreviewMouseDown);
buttonToolBarrier.PreviewMouseDown += new MouseButtonEventHandler(ToolButton_PreviewMouseDown);
// Edit menu
menuEditSelectAll.Click += new RoutedEventHandler(menuEditSelectAll_Click);
menuEditUnselectAll.Click += new RoutedEventHandler(menuEditUnselectAll_Click);
menuEditDelete.Click += new RoutedEventHandler(menuEditDelete_Click);
menuEditDeleteAll.Click += new RoutedEventHandler(menuEditDeleteAll_Click);
menuEditMoveToFront.Click += new RoutedEventHandler(menuEditMoveToFront_Click);
menuEditMoveToBack.Click += new RoutedEventHandler(menuEditMoveToBack_Click);
menuEditSetProperties.Click += new RoutedEventHandler(menuEditSetProperties_Click);
}
/// <summary>
/// Initialize MRU list
/// </summary>
void InitializeMruList()
{
mruManager = new MruManager(SettingsManager.ApplicationSettings.RecentFilesList, menuFileRecentFiles);
mruManager.FileSelected += new EventHandler<MruFileOpenEventArgs>(mruManager_FileSelected);
}
/// <summary>
/// Set initial properties of drawing canvas
/// </summary>
void InitializeDrawingCanvas()
{
drawingCanvas.LineWidth = SettingsManager.ApplicationSettings.LineWidth;
drawingCanvas.ObjectColor = SettingsManager.ApplicationSettings.ObjectColor;
drawingCanvas.TextFontSize = SettingsManager.ApplicationSettings.TextFontSize;
drawingCanvas.TextFontFamilyName = SettingsManager.ApplicationSettings.TextFontFamilyName;
drawingCanvas.TextFontStyle = FontConversions.FontStyleFromString(SettingsManager.ApplicationSettings.TextFontStyle);
drawingCanvas.TextFontWeight = FontConversions.FontWeightFromString(SettingsManager.ApplicationSettings.TextFontWeight);
drawingCanvas.TextFontStretch = FontConversions.FontStretchFromString(SettingsManager.ApplicationSettings.TextFontStretch);
}
/// <summary>
/// Show error message
/// </summary>
void ShowError(string message)
{
System.Windows.MessageBox.Show(
this,
message,
Properties.Resources.ApplicationTitle,
MessageBoxButton.OK,
MessageBoxImage.Error);
}
/// <summary>
/// Update window title
/// </summary>
void UpdateTitle()
{
string s = Properties.Resources.ApplicationTitle + " - ";
if (string.IsNullOrEmpty(fileName))
{
s += Properties.Resources.Untitled;
}
else
{
s += System.IO.Path.GetFileName(fileName);
}
if (drawingCanvas.IsDirty)
{
s += " *";
}
this.Title = s;
}
/// <summary>
/// Save to file
/// </summary>
bool Save(string file)
{
try
{
// Save file
drawingCanvas.Save(file);
}
catch (DrawingCanvasException e)
{
ShowError(e.Message);
return false;
}
this.fileName = file;
UpdateTitle();
return true;
}
/// <summary>
/// This function prints graphics when background image doesn't exist
/// </summary>
void PrintWithoutBackground()
{
PrintDialog dlg = new PrintDialog();
if (dlg.ShowDialog().GetValueOrDefault() != true)
{
return;
}
// Calculate rectangle for graphics
double width = dlg.PrintableAreaWidth / 2;
double height = width * drawingCanvas.ActualHeight / drawingCanvas.ActualWidth;
double left = (dlg.PrintableAreaWidth - width) / 2;
double top = (dlg.PrintableAreaHeight - height) / 2;
Rect rect = new Rect(left, top, width, height);
// Create DrawingVisual and get its drawing context
DrawingVisual vs = new DrawingVisual();
DrawingContext dc = vs.RenderOpen();
double scale = width / drawingCanvas.ActualWidth;
// Keep old existing actual scale and set new actual scale.
double oldActualScale = drawingCanvas.ActualScale;
drawingCanvas.ActualScale = scale;
// Remove clip in the canvas - we set our own clip.
drawingCanvas.RemoveClip();
// Draw frame
dc.DrawRectangle(null, new Pen(Brushes.Black, 1),
new Rect(rect.Left - 1, rect.Top - 1, rect.Width + 2, rect.Height + 2));
// Prepare drawing context to draw graphics
dc.PushClip(new RectangleGeometry(rect));
dc.PushTransform(new TranslateTransform(left, top));
dc.PushTransform(new ScaleTransform(scale, scale));
// Ask canvas to draw overlays
drawingCanvas.Draw(dc);
// Restore old actual scale.
drawingCanvas.ActualScale = oldActualScale;
// Restore clip
drawingCanvas.RefreshClip();
dc.Pop();
dc.Pop();
dc.Pop();
dc.Close();
// Print DrawVisual
dlg.PrintVisual(vs, "Graphics");
}
/// <summary>
/// This function prints graphics with background image.
/// </summary>
void PrintWithBackgroundImage(Image image)
{
PrintDialog dlg = new PrintDialog();
if (dlg.ShowDialog().GetValueOrDefault() != true)
{
return;
}
// Calculate rectangle for image
double width = dlg.PrintableAreaWidth / 2;
double height = width * image.Source.Height / image.Source.Width;
double left = (dlg.PrintableAreaWidth - width) / 2;
double top = (dlg.PrintableAreaHeight - height) / 2;
Rect rect = new Rect(left, top, width, height);
// Create DrawingVisual and get its drawing context
DrawingVisual vs = new DrawingVisual();
DrawingContext dc = vs.RenderOpen();
// Draw image
dc.DrawImage(image.Source, rect);
double scale = width / image.Source.Width;
// Keep old existing actual scale and set new actual scale.
double oldActualScale = drawingCanvas.ActualScale;
drawingCanvas.ActualScale = scale;
// Remove clip in the canvas - we set our own clip.
drawingCanvas.RemoveClip();
// Prepare drawing context to draw graphics
dc.PushClip(new RectangleGeometry(rect));
dc.PushTransform(new TranslateTransform(left, top));
dc.PushTransform(new ScaleTransform(scale, scale));
// Ask canvas to draw overlays
drawingCanvas.Draw(dc);
// Restore old actual scale.
drawingCanvas.ActualScale = oldActualScale;
// Restore clip
drawingCanvas.RefreshClip();
dc.Pop();
dc.Pop();
dc.Pop();
dc.Close();
// Print DrawVisual
dlg.PrintVisual(vs, "Graphics");
}
#endregion Other Functions
private void TableBlockSpinnerWide_Spin(object sender, SpinEventArgs e)
{
if (!(drawingCanvas.SelectedObject is GraphicsTableBlock))
return;
ButtonSpinner spinner = (ButtonSpinner)sender;
TextBox txtBox = (TextBox)spinner.Content;
GraphicsTableBlock selected = (drawingCanvas.SelectedObject as GraphicsTableBlock);
if (e.Direction == SpinDirection.Increase)
selected.NumTablesWide++;
else
selected.NumTablesWide--;
txtBox.Text = selected.NumTablesWide.ToString();
}
private void TableBlockSpinnerHeight_Spin(object sender, SpinEventArgs e)
{
if (!(drawingCanvas.SelectedObject is GraphicsTableBlock))
return;
ButtonSpinner spinner = (ButtonSpinner)sender;
TextBox txtBox = (TextBox)spinner.Content;
GraphicsTableBlock selected = (drawingCanvas.SelectedObject as GraphicsTableBlock);
if (e.Direction == SpinDirection.Increase)
selected.NumTablesTall++;
else
selected.NumTablesTall--;
txtBox.Text = selected.NumTablesTall.ToString();
}
private void OpenBluetoothIdWindow(object sender, RoutedEventArgs e)
{
BeaconSettings beaconWindow = new BeaconSettings { Owner = this };
beaconWindow.ShowDialog();
}
Regex shortIdRegex = new Regex(@"^\d+$");
private void BeaconIdSetter_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (shortIdRegex.IsMatch(e.Text))
{
e.Handled = true;
GraphicsBeacon selected = (drawingCanvas.SelectedObject as GraphicsBeacon);
BeaconInfo thisOne = null;
foreach (BeaconInfo check in BeaconInfoManager.Instance().beacons)
{
if (check.DeviceLabel.Equals(e.Text))
{
thisOne = check;
break;
}
}
selected.Info = thisOne;
}
else { }
e.Handled = false;
}
private void RefreshBeaconList(object sender, EventArgs e)
{
BeaconIdSelector.ItemsSource = BeaconInfoManager.Instance().beacons;
BeaconIdSelector.DisplayMemberPath = "DeviceLabel";
}
private void BeaconIdSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!(drawingCanvas.SelectedObject is GraphicsBeacon))
return;
GraphicsBeacon selected = (drawingCanvas.SelectedObject as GraphicsBeacon);
BeaconInfo thisOne = null;
foreach (BeaconInfo check in BeaconInfoManager.Instance().beacons)
{
if (check.Equals(BeaconIdSelector.SelectedValue))
{
thisOne = check;
break;
}
}
selected.Info = thisOne;
}
private void SwapDimensions(object sender, RoutedEventArgs e)
{
if (!(drawingCanvas.SelectedObject is GraphicsTableBlock))
{
int temp = GraphicsTableBlock.DefaultNumTablesTall;
GraphicsTableBlock.DefaultNumTablesTall = GraphicsTableBlock.DefaultNumTablesWide;
GraphicsTableBlock.DefaultNumTablesWide = temp;
}
else
{
GraphicsTableBlock selected = (drawingCanvas.SelectedObject as GraphicsTableBlock);
int temp = selected.NumTablesTall;
selected.NumTablesTall = selected.NumTablesWide;
selected.NumTablesWide = temp;
}
(WidthSpinner.Content as TextBox).Text = GraphicsTableBlock.DefaultNumTablesWide.ToString();
(HeightSpinner.Content as TextBox).Text = GraphicsTableBlock.DefaultNumTablesTall.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using CoreCraft.Models;
using CoreCraft.Models.ManageViewModels;
using CoreCraft.Services;
namespace CoreCraft.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess
? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess
? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess
? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error
? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess
? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess
? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new {Message = message});
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new {PhoneNumber = model.PhoneNumber});
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null
? View("Error")
: View(new VerifyPhoneNumberViewModel {PhoneNumber = phoneNumber});
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new {Message = ManageMessageId.AddPhoneSuccess});
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new {Message = ManageMessageId.RemovePhoneSuccess});
}
}
return RedirectToAction(nameof(Index), new {Message = ManageMessageId.Error});
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new {Message = ManageMessageId.ChangePasswordSuccess});
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new {Message = ManageMessageId.Error});
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new {Message = ManageMessageId.SetPasswordSuccess});
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new {Message = ManageMessageId.Error});
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess
? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess
? "The external login was added."
: message == ManageMessageId.Error
? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins =
_signInManager.GetExternalAuthenticationSchemes()
.Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider))
.ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl,
_userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new {Message = ManageMessageId.Error});
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new {Message = message});
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
using System;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Publishing;
namespace Umbraco.Core.Services
{
/// <summary>
/// The Umbraco ServiceContext, which provides access to the following services:
/// <see cref="IContentService"/>, <see cref="IContentTypeService"/>, <see cref="IDataTypeService"/>,
/// <see cref="IFileService"/>, <see cref="ILocalizationService"/> and <see cref="IMediaService"/>.
/// </summary>
public class ServiceContext
{
private Lazy<ContentService> _contentService;
private Lazy<UserService> _userService;
private Lazy<MemberService> _memberService;
private Lazy<MediaService> _mediaService;
private Lazy<ContentTypeService> _contentTypeService;
private Lazy<DataTypeService> _dataTypeService;
private Lazy<FileService> _fileService;
private Lazy<LocalizationService> _localizationService;
private Lazy<PackagingService> _packagingService;
private Lazy<ServerRegistrationService> _serverRegistrationService;
private Lazy<EntityService> _entityService;
private Lazy<RelationService> _relationService;
private Lazy<ApplicationTreeService> _treeService;
private Lazy<SectionService> _sectionService;
/// <summary>
/// Constructor
/// </summary>
/// <param name="dbUnitOfWorkProvider"></param>
/// <param name="fileUnitOfWorkProvider"></param>
/// <param name="publishingStrategy"></param>
internal ServiceContext(IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider, IUnitOfWorkProvider fileUnitOfWorkProvider, BasePublishingStrategy publishingStrategy, CacheHelper cache)
{
BuildServiceCache(dbUnitOfWorkProvider, fileUnitOfWorkProvider, publishingStrategy, cache,
//this needs to be lazy because when we create the service context it's generally before the
//resolvers have been initialized!
new Lazy<RepositoryFactory>(() => RepositoryResolver.Current.Factory));
}
/// <summary>
/// Builds the various services
/// </summary>
private void BuildServiceCache(
IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider,
IUnitOfWorkProvider fileUnitOfWorkProvider,
BasePublishingStrategy publishingStrategy,
CacheHelper cache,
Lazy<RepositoryFactory> repositoryFactory)
{
var provider = dbUnitOfWorkProvider;
var fileProvider = fileUnitOfWorkProvider;
if (_serverRegistrationService == null)
_serverRegistrationService = new Lazy<ServerRegistrationService>(() => new ServerRegistrationService(provider, repositoryFactory.Value));
if (_userService == null)
_userService = new Lazy<UserService>(() => new UserService(provider, repositoryFactory.Value));
if (_memberService == null)
_memberService = new Lazy<MemberService>(() => new MemberService(provider, repositoryFactory.Value));
if (_contentService == null)
_contentService = new Lazy<ContentService>(() => new ContentService(provider, repositoryFactory.Value, publishingStrategy));
if(_mediaService == null)
_mediaService = new Lazy<MediaService>(() => new MediaService(provider, repositoryFactory.Value));
if(_contentTypeService == null)
_contentTypeService = new Lazy<ContentTypeService>(() => new ContentTypeService(provider, repositoryFactory.Value, _contentService.Value, _mediaService.Value));
if(_dataTypeService == null)
_dataTypeService = new Lazy<DataTypeService>(() => new DataTypeService(provider, repositoryFactory.Value));
if(_fileService == null)
_fileService = new Lazy<FileService>(() => new FileService(fileProvider, provider, repositoryFactory.Value));
if(_localizationService == null)
_localizationService = new Lazy<LocalizationService>(() => new LocalizationService(provider, repositoryFactory.Value));
if(_packagingService == null)
_packagingService = new Lazy<PackagingService>(() => new PackagingService(_contentService.Value, _contentTypeService.Value, _mediaService.Value, _dataTypeService.Value, _fileService.Value, repositoryFactory.Value, provider));
if (_entityService == null)
_entityService = new Lazy<EntityService>(() => new EntityService(provider, repositoryFactory.Value, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _dataTypeService.Value));
if(_relationService == null)
_relationService = new Lazy<RelationService>(() => new RelationService(provider, repositoryFactory.Value, _entityService.Value));
if (_treeService == null)
_treeService = new Lazy<ApplicationTreeService>(() => new ApplicationTreeService(cache));
if (_sectionService == null)
_sectionService = new Lazy<SectionService>(() => new SectionService(_userService.Value, _treeService.Value, cache));
}
/// <summary>
/// Gets the <see cref="ServerRegistrationService"/>
/// </summary>
internal ServerRegistrationService ServerRegistrationService
{
get { return _serverRegistrationService.Value; }
}
/// <summary>
/// Gets the <see cref="EntityService"/>
/// </summary>
public EntityService EntityService
{
get { return _entityService.Value; }
}
/// <summary>
/// Gets the <see cref="RelationService"/>
/// </summary>
public RelationService RelationService
{
get { return _relationService.Value; }
}
/// <summary>
/// Gets the <see cref="IContentService"/>
/// </summary>
public IContentService ContentService
{
get { return _contentService.Value; }
}
/// <summary>
/// Gets the <see cref="IContentTypeService"/>
/// </summary>
public IContentTypeService ContentTypeService
{
get { return _contentTypeService.Value; }
}
/// <summary>
/// Gets the <see cref="IDataTypeService"/>
/// </summary>
public IDataTypeService DataTypeService
{
get { return _dataTypeService.Value; }
}
/// <summary>
/// Gets the <see cref="IFileService"/>
/// </summary>
public IFileService FileService
{
get { return _fileService.Value; }
}
/// <summary>
/// Gets the <see cref="ILocalizationService"/>
/// </summary>
public ILocalizationService LocalizationService
{
get { return _localizationService.Value; }
}
/// <summary>
/// Gets the <see cref="IMediaService"/>
/// </summary>
public IMediaService MediaService
{
get { return _mediaService.Value; }
}
/// <summary>
/// Gets the <see cref="PackagingService"/>
/// </summary>
public PackagingService PackagingService
{
get { return _packagingService.Value; }
}
/// <summary>
/// Gets the <see cref="UserService"/>
/// </summary>
internal IUserService UserService
{
get { return _userService.Value; }
}
/// <summary>
/// Gets the <see cref="MemberService"/>
/// </summary>
internal IMemberService MemberService
{
get { return _memberService.Value; }
}
/// <summary>
/// Gets the <see cref="SectionService"/>
/// </summary>
internal SectionService SectionService
{
get { return _sectionService.Value; }
}
/// <summary>
/// Gets the <see cref="ApplicationTreeService"/>
/// </summary>
internal ApplicationTreeService ApplicationTreeService
{
get { return _treeService.Value; }
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Dynamics.Contacts;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics
{
[Flags]
public enum Category
{
None = 0,
All = int.MaxValue,
Cat1 = 1,
Cat2 = 2,
Cat3 = 4,
Cat4 = 8,
Cat5 = 16,
Cat6 = 32,
Cat7 = 64,
Cat8 = 128,
Cat9 = 256,
Cat10 = 512,
Cat11 = 1024,
Cat12 = 2048,
Cat13 = 4096,
Cat14 = 8192,
Cat15 = 16384,
Cat16 = 32768,
Cat17 = 65536,
Cat18 = 131072,
Cat19 = 262144,
Cat20 = 524288,
Cat21 = 1048576,
Cat22 = 2097152,
Cat23 = 4194304,
Cat24 = 8388608,
Cat25 = 16777216,
Cat26 = 33554432,
Cat27 = 67108864,
Cat28 = 134217728,
Cat29 = 268435456,
Cat30 = 536870912,
Cat31 = 1073741824
}
/// <summary>
/// This proxy is used internally to connect fixtures to the broad-phase.
/// </summary>
public struct FixtureProxy
{
public AABB AABB;
public int ChildIndex;
public Fixture Fixture;
public int ProxyId;
}
public class CollisionFilter
{
private Category _collidesWith;
private Category _collisionCategories;
private short _collisionGroup;
private Dictionary<int, bool> _collisionIgnores = new Dictionary<int, bool>();
private Fixture _fixture;
public CollisionFilter(Fixture fixture)
{
_fixture = fixture;
if (Settings.UseFPECollisionCategories)
_collisionCategories = Category.All;
else
_collisionCategories = Category.Cat1;
_collidesWith = Category.All;
_collisionGroup = 0;
}
/// <summary>
/// Defaults to 0
///
/// If Settings.UseFPECollisionCategories is set to false:
/// Collision groups allow a certain group of objects to never collide (negative)
/// or always collide (positive). Zero means no collision group. Non-zero group
/// filtering always wins against the mask bits.
///
/// If Settings.UseFPECollisionCategories is set to true:
/// If 2 fixtures are in the same collision group, they will not collide.
/// </summary>
public short CollisionGroup
{
set
{
if (_fixture.Body == null)
return;
if (_collisionGroup == value)
return;
_collisionGroup = value;
FilterChanged();
}
get { return _collisionGroup; }
}
/// <summary>
/// Defaults to Category.All
///
/// The collision mask bits. This states the categories that this
/// fixture would accept for collision.
/// Use Settings.UseFPECollisionCategories to change the behavior.
/// </summary>
public Category CollidesWith
{
get { return _collidesWith; }
set
{
if (_fixture.Body == null)
return;
if (_collidesWith == value)
return;
_collidesWith = value;
FilterChanged();
}
}
/// <summary>
/// The collision categories this fixture is a part of.
///
/// If Settings.UseFPECollisionCategories is set to false:
/// Defaults to Category.Cat1
///
/// If Settings.UseFPECollisionCategories is set to true:
/// Defaults to Category.All
/// </summary>
public Category CollisionCategories
{
get { return _collisionCategories; }
set
{
if (_fixture.Body == null)
return;
if (_collisionCategories == value)
return;
_collisionCategories = value;
FilterChanged();
}
}
/// <summary>
/// Adds the category.
/// </summary>
/// <param name="category">The category.</param>
public void AddCollisionCategory(Category category)
{
CollisionCategories |= category;
}
/// <summary>
/// Removes the category.
/// </summary>
/// <param name="category">The category.</param>
public void RemoveCollisionCategory(Category category)
{
CollisionCategories &= ~category;
}
/// <summary>
/// Determines whether this object has the specified category.
/// </summary>
/// <param name="category">The category.</param>
/// <returns>
/// <c>true</c> if the object has the specified category; otherwise, <c>false</c>.
/// </returns>
public bool IsInCollisionCategory(Category category)
{
return (CollisionCategories & category) == category;
}
/// <summary>
/// Adds the category.
/// </summary>
/// <param name="category">The category.</param>
public void AddCollidesWithCategory(Category category)
{
CollidesWith |= category;
}
/// <summary>
/// Removes the category.
/// </summary>
/// <param name="category">The category.</param>
public void RemoveCollidesWithCategory(Category category)
{
CollidesWith &= ~category;
}
/// <summary>
/// Determines whether this object has the specified category.
/// </summary>
/// <param name="category">The category.</param>
/// <returns>
/// <c>true</c> if the object has the specified category; otherwise, <c>false</c>.
/// </returns>
public bool IsInCollidesWithCategory(Category category)
{
return (CollidesWith & category) == category;
}
/// <summary>
/// Restores collisions between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
public void RestoreCollisionWith(Fixture fixture)
{
if (_collisionIgnores.ContainsKey(fixture.FixtureId))
{
_collisionIgnores[fixture.FixtureId] = false;
FilterChanged();
}
}
/// <summary>
/// Ignores collisions between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
public void IgnoreCollisionWith(Fixture fixture)
{
if (_collisionIgnores.ContainsKey(fixture.FixtureId))
_collisionIgnores[fixture.FixtureId] = true;
else
_collisionIgnores.Add(fixture.FixtureId, true);
FilterChanged();
}
/// <summary>
/// Determines whether collisions are ignored between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
/// <returns>
/// <c>true</c> if the fixture is ignored; otherwise, <c>false</c>.
/// </returns>
public bool IsFixtureIgnored(Fixture fixture)
{
if (_collisionIgnores.ContainsKey(fixture.FixtureId))
return _collisionIgnores[fixture.FixtureId];
return false;
}
/// <summary>
/// Contacts are persistant and will keep being persistant unless they are
/// flagged for filtering.
/// This methods flags all contacts associated with the body for filtering.
/// </summary>
private void FilterChanged()
{
// Flag associated contacts for filtering.
ContactEdge edge = _fixture.Body.ContactList;
while (edge != null)
{
Contact contact = edge.Contact;
Fixture fixtureA = contact.FixtureA;
Fixture fixtureB = contact.FixtureB;
if (fixtureA == _fixture || fixtureB == _fixture)
{
contact.FlagForFiltering();
}
edge = edge.Next;
}
}
}
/// <summary>
/// A fixture is used to attach a Shape to a body for collision detection. A fixture
/// inherits its transform from its parent. Fixtures hold additional non-geometric data
/// such as friction, collision filters, etc.
/// Fixtures are created via Body.CreateFixture.
/// Warning: You cannot reuse fixtures.
/// </summary>
public class Fixture : IDisposable
{
private static int _fixtureIdCounter;
/// <summary>
/// Fires after two shapes has collided and are solved. This gives you a chance to get the impact force.
/// </summary>
public AfterCollisionEventHandler AfterCollision;
/// <summary>
/// Fires when two fixtures are close to each other.
/// Due to how the broadphase works, this can be quite inaccurate as shapes are approximated using AABBs.
/// </summary>
public BeforeCollisionEventHandler BeforeCollision;
public CollisionFilter CollisionFilter { get; private set; }
/// <summary>
/// Fires when two shapes collide and a contact is created between them.
/// Note that the first fixture argument is always the fixture that the delegate is subscribed to.
/// </summary>
public OnCollisionEventHandler OnCollision;
/// <summary>
/// Fires when two shapes separate and a contact is removed between them.
/// Note that the first fixture argument is always the fixture that the delegate is subscribed to.
/// </summary>
public OnSeparationEventHandler OnSeparation;
public FixtureProxy[] Proxies;
public int ProxyCount;
public Fixture(Body body, Shape shape)
: this(body, shape, null)
{
}
public Fixture(Body body, Shape shape, Object userData)
{
CollisionFilter = new CollisionFilter(this);
//Fixture defaults
Friction = 0.2f;
Restitution = 0;
IsSensor = false;
Body = body;
UserData = userData;
if (Settings.ConserveMemory)
Shape = shape;
else
Shape = shape.Clone();
// Reserve proxy space
int childCount = Shape.ChildCount;
Proxies = new FixtureProxy[childCount];
for (int i = 0; i < childCount; ++i)
{
Proxies[i] = new FixtureProxy();
Proxies[i].Fixture = null;
Proxies[i].ProxyId = BroadPhase.NullProxy;
}
ProxyCount = 0;
FixtureId = _fixtureIdCounter++;
if ((Body.Flags & BodyFlags.Enabled) == BodyFlags.Enabled)
{
BroadPhase broadPhase = Body.World.ContactManager.BroadPhase;
CreateProxies(broadPhase, ref Body.Xf);
}
Body.FixtureList.Add(this);
// Adjust mass properties if needed.
if (Shape._density > 0.0f)
{
Body.ResetMassData();
}
// Let the world know we have a new fixture. This will cause new contacts
// to be created at the beginning of the next time step.
Body.World.Flags |= WorldFlags.NewFixture;
if (Body.World.FixtureAdded != null)
{
Body.World.FixtureAdded(this);
}
}
/// <summary>
/// Get the type of the child Shape. You can use this to down cast to the concrete Shape.
/// </summary>
/// <value>The type of the shape.</value>
public ShapeType ShapeType
{
get { return Shape.ShapeType; }
}
/// <summary>
/// Get the child Shape. You can modify the child Shape, however you should not change the
/// number of vertices because this will crash some collision caching mechanisms.
/// </summary>
/// <value>The shape.</value>
public Shape Shape { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether this fixture is a sensor.
/// </summary>
/// <value><c>true</c> if this instance is a sensor; otherwise, <c>false</c>.</value>
public bool IsSensor { get; set; }
/// <summary>
/// Get the parent body of this fixture. This is null if the fixture is not attached.
/// </summary>
/// <value>The body.</value>
public Body Body { get; internal set; }
/// <summary>
/// Set the user data. Use this to store your application specific data.
/// </summary>
/// <value>The user data.</value>
public object UserData { get; set; }
/// <summary>
/// Get or set the coefficient of friction.
/// </summary>
/// <value>The friction.</value>
public float Friction { get; set; }
/// <summary>
/// Get or set the coefficient of restitution.
/// </summary>
/// <value>The restitution.</value>
public float Restitution { get; set; }
/// <summary>
/// Gets a unique ID for this fixture.
/// </summary>
/// <value>The fixture id.</value>
public int FixtureId { get; private set; }
#region IDisposable Members
public void Dispose()
{
Body.Dispose();
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Test a point for containment in this fixture.
/// </summary>
/// <param name="point">A point in world coordinates.</param>
/// <returns></returns>
public bool TestPoint(ref Vector2 point)
{
return Shape.TestPoint(ref Body.Xf, ref point);
}
/// <summary>
/// Cast a ray against this Shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="childIndex">Index of the child.</param>
/// <returns></returns>
public bool RayCast(out RayCastOutput output, ref RayCastInput input, int childIndex)
{
return Shape.RayCast(out output, ref input, ref Body.Xf, childIndex);
}
/// <summary>
/// Get the mass data for this fixture. The mass data is based on the density and
/// the Shape. The rotational inertia is about the Shape's origin.
/// </summary>
public MassData GetMassData()
{
return Shape.MassData;
}
/// <summary>
/// Get the fixture's AABB. This AABB may be enlarge and/or stale.
/// If you need a more accurate AABB, compute it using the Shape and
/// the body transform.
/// </summary>
/// <param name="aabb">The aabb.</param>
/// <param name="childIndex">Index of the child.</param>
public void GetAABB(out AABB aabb, int childIndex)
{
Debug.Assert(0 <= childIndex && childIndex < ProxyCount);
aabb = Proxies[childIndex].AABB;
}
internal void Destroy()
{
// The proxies must be destroyed before calling this.
Debug.Assert(ProxyCount == 0);
// Free the proxy array.
Proxies = null;
Shape = null;
if (Body.World.FixtureRemoved != null)
{
Body.World.FixtureRemoved(this);
}
}
// These support body activation/deactivation.
internal void CreateProxies(BroadPhase broadPhase, ref Transform xf)
{
Debug.Assert(ProxyCount == 0);
// Create proxies in the broad-phase.
ProxyCount = Shape.ChildCount;
for (int i = 0; i < ProxyCount; ++i)
{
FixtureProxy proxy = Proxies[i];
Shape.ComputeAABB(out proxy.AABB, ref xf, i);
proxy.Fixture = this;
proxy.ChildIndex = i;
proxy.ProxyId = broadPhase.CreateProxy(ref proxy.AABB, ref proxy);
Proxies[i] = proxy;
}
}
internal void DestroyProxies(BroadPhase broadPhase)
{
// Destroy proxies in the broad-phase.
for (int i = 0; i < ProxyCount; ++i)
{
broadPhase.DestroyProxy(Proxies[i].ProxyId);
Proxies[i].ProxyId = BroadPhase.NullProxy;
}
ProxyCount = 0;
}
internal void Synchronize(BroadPhase broadPhase, ref Transform transform1, ref Transform transform2)
{
if (ProxyCount == 0)
{
return;
}
for (int i = 0; i < ProxyCount; ++i)
{
FixtureProxy proxy = Proxies[i];
// Compute an AABB that covers the swept Shape (may miss some rotation effect).
AABB aabb1, aabb2;
Shape.ComputeAABB(out aabb1, ref transform1, proxy.ChildIndex);
Shape.ComputeAABB(out aabb2, ref transform2, proxy.ChildIndex);
proxy.AABB.Combine(ref aabb1, ref aabb2);
Vector2 displacement = transform2.Position - transform1.Position;
broadPhase.MoveProxy(proxy.ProxyId, ref proxy.AABB, displacement);
}
}
}
}
| |
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
#if SILVERLIGHT4 || SILVERLIGHT5 || NET40 || NET45 || NETFX_CORE
using System.Numerics;
#else
using BigIntegerLibrary;
#endif
using ZXing.Common;
namespace ZXing.PDF417.Internal
{
/// <summary>
/// <p>This class contains the methods for decoding the PDF417 codewords.</p>
///
/// <author>SITA Lab (kevin.osullivan@sita.aero)</author>
/// </summary>
internal static class DecodedBitStreamParser
{
private enum Mode
{
ALPHA,
LOWER,
MIXED,
PUNCT,
ALPHA_SHIFT,
PUNCT_SHIFT
}
private const int TEXT_COMPACTION_MODE_LATCH = 900;
private const int BYTE_COMPACTION_MODE_LATCH = 901;
private const int NUMERIC_COMPACTION_MODE_LATCH = 902;
private const int BYTE_COMPACTION_MODE_LATCH_6 = 924;
private const int BEGIN_MACRO_PDF417_CONTROL_BLOCK = 928;
private const int BEGIN_MACRO_PDF417_OPTIONAL_FIELD = 923;
private const int MACRO_PDF417_TERMINATOR = 922;
private const int MODE_SHIFT_TO_BYTE_COMPACTION_MODE = 913;
private const int MAX_NUMERIC_CODEWORDS = 15;
private const int PL = 25;
private const int LL = 27;
private const int AS = 27;
private const int ML = 28;
private const int AL = 28;
private const int PS = 29;
private const int PAL = 29;
private static readonly char[] PUNCT_CHARS = {
';', '<', '>', '@', '[', '\\', ']', '_', '`', '~', '!',
'\r', '\t', ',', ':', '\n', '-', '.', '$', '/', '"', '|', '*',
'(', ')', '?', '{', '}', '\''
};
private static readonly char[] MIXED_CHARS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '&',
'\r', '\t', ',', ':', '#', '-', '.', '$', '/', '+', '%', '*',
'=', '^'
};
#if SILVERLIGHT4 || SILVERLIGHT5 || NET40 || NET45 || NETFX_CORE
/// <summary>
/// Table containing values for the exponent of 900.
/// This is used in the numeric compaction decode algorithm.
/// </summary>
private static readonly BigInteger[] EXP900;
static DecodedBitStreamParser()
{
EXP900 = new BigInteger[16];
EXP900[0] = BigInteger.One;
BigInteger nineHundred = new BigInteger(900);
EXP900[1] = nineHundred;
for (int i = 2; i < EXP900.Length; i++)
{
EXP900[i] = BigInteger.Multiply(EXP900[i - 1], nineHundred);
}
}
#else
/// <summary>
/// Table containing values for the exponent of 900.
/// This is used in the numeric compaction decode algorithm.
/// </summary>
private static readonly BigInteger[] EXP900;
static DecodedBitStreamParser()
{
EXP900 = new BigInteger[16];
EXP900[0] = BigInteger.One;
BigInteger nineHundred = new BigInteger(900);
EXP900[1] = nineHundred;
for (int i = 2; i < EXP900.Length; i++)
{
EXP900[i] = BigInteger.Multiplication(EXP900[i - 1], nineHundred);
}
}
#endif
private const int NUMBER_OF_SEQUENCE_CODEWORDS = 2;
internal static DecoderResult decode(int[] codewords, String ecLevel)
{
var result = new StringBuilder(codewords.Length * 2);
// Get compaction mode
int codeIndex = 1;
int code = codewords[codeIndex++];
var resultMetadata = new PDF417ResultMetadata();
while (codeIndex < codewords[0])
{
switch (code)
{
case TEXT_COMPACTION_MODE_LATCH:
codeIndex = textCompaction(codewords, codeIndex, result);
break;
case BYTE_COMPACTION_MODE_LATCH:
case BYTE_COMPACTION_MODE_LATCH_6:
case MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
codeIndex = byteCompaction(code, codewords, codeIndex, result);
break;
case NUMERIC_COMPACTION_MODE_LATCH:
codeIndex = numericCompaction(codewords, codeIndex, result);
break;
case BEGIN_MACRO_PDF417_CONTROL_BLOCK:
codeIndex = decodeMacroBlock(codewords, codeIndex, resultMetadata);
break;
case BEGIN_MACRO_PDF417_OPTIONAL_FIELD:
case MACRO_PDF417_TERMINATOR:
// Should not see these outside a macro block
return null;
default:
// Default to text compaction. During testing numerous barcodes
// appeared to be missing the starting mode. In these cases defaulting
// to text compaction seems to work.
codeIndex--;
codeIndex = textCompaction(codewords, codeIndex, result);
break;
}
if (codeIndex < 0)
return null;
if (codeIndex < codewords.Length)
{
code = codewords[codeIndex++];
}
else
{
return null;
}
}
if (result.Length == 0)
{
return null;
}
var decoderResult = new DecoderResult(null, result.ToString(), null, ecLevel);
decoderResult.Other = resultMetadata;
return decoderResult;
}
private static int decodeMacroBlock(int[] codewords, int codeIndex, PDF417ResultMetadata resultMetadata)
{
if (codeIndex + NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0])
{
// we must have at least two bytes left for the segment index
return -1;
}
int[] segmentIndexArray = new int[NUMBER_OF_SEQUENCE_CODEWORDS];
for (int i = 0; i < NUMBER_OF_SEQUENCE_CODEWORDS; i++, codeIndex++)
{
segmentIndexArray[i] = codewords[codeIndex];
}
String s = decodeBase900toBase10(segmentIndexArray, NUMBER_OF_SEQUENCE_CODEWORDS);
if (s == null)
return -1;
resultMetadata.SegmentIndex = Int32.Parse(s);
StringBuilder fileId = new StringBuilder();
codeIndex = textCompaction(codewords, codeIndex, fileId);
resultMetadata.FileId = fileId.ToString();
if (codewords[codeIndex] == BEGIN_MACRO_PDF417_OPTIONAL_FIELD)
{
codeIndex++;
int[] additionalOptionCodeWords = new int[codewords[0] - codeIndex];
int additionalOptionCodeWordsIndex = 0;
bool end = false;
while ((codeIndex < codewords[0]) && !end)
{
int code = codewords[codeIndex++];
if (code < TEXT_COMPACTION_MODE_LATCH)
{
additionalOptionCodeWords[additionalOptionCodeWordsIndex++] = code;
}
else
{
switch (code)
{
case MACRO_PDF417_TERMINATOR:
resultMetadata.IsLastSegment = true;
codeIndex++;
end = true;
break;
default:
return -1;
}
}
}
resultMetadata.OptionalData = new int[additionalOptionCodeWordsIndex];
Array.Copy(additionalOptionCodeWords, resultMetadata.OptionalData, additionalOptionCodeWordsIndex);
}
else if (codewords[codeIndex] == MACRO_PDF417_TERMINATOR)
{
resultMetadata.IsLastSegment = true;
codeIndex++;
}
return codeIndex;
}
/// <summary>
/// Text Compaction mode (see 5.4.1.5) permits all printable ASCII characters to be
/// encoded, i.e. values 32 - 126 inclusive in accordance with ISO/IEC 646 (IRV), as
/// well as selected control characters.
///
/// <param name="codewords">The array of codewords (data + error)</param>
/// <param name="codeIndex">The current index into the codeword array.</param>
/// <param name="result">The decoded data is appended to the result.</param>
/// <returns>The next index into the codeword array.</returns>
/// </summary>
private static int textCompaction(int[] codewords, int codeIndex, StringBuilder result)
{
// 2 character per codeword
int[] textCompactionData = new int[(codewords[0] - codeIndex) << 1];
// Used to hold the byte compaction value if there is a mode shift
int[] byteCompactionData = new int[(codewords[0] - codeIndex) << 1];
int index = 0;
bool end = false;
while ((codeIndex < codewords[0]) && !end)
{
int code = codewords[codeIndex++];
if (code < TEXT_COMPACTION_MODE_LATCH)
{
textCompactionData[index] = code / 30;
textCompactionData[index + 1] = code % 30;
index += 2;
}
else
{
switch (code)
{
case TEXT_COMPACTION_MODE_LATCH:
// reinitialize text compaction mode to alpha sub mode
textCompactionData[index++] = TEXT_COMPACTION_MODE_LATCH;
break;
case BYTE_COMPACTION_MODE_LATCH:
case BYTE_COMPACTION_MODE_LATCH_6:
case NUMERIC_COMPACTION_MODE_LATCH:
case BEGIN_MACRO_PDF417_CONTROL_BLOCK:
case BEGIN_MACRO_PDF417_OPTIONAL_FIELD:
case MACRO_PDF417_TERMINATOR:
codeIndex--;
end = true;
break;
case MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
// The Mode Shift codeword 913 shall cause a temporary
// switch from Text Compaction mode to Byte Compaction mode.
// This switch shall be in effect for only the next codeword,
// after which the mode shall revert to the prevailing sub-mode
// of the Text Compaction mode. Codeword 913 is only available
// in Text Compaction mode; its use is described in 5.4.2.4.
textCompactionData[index] = MODE_SHIFT_TO_BYTE_COMPACTION_MODE;
code = codewords[codeIndex++];
byteCompactionData[index] = code;
index++;
break;
}
}
}
decodeTextCompaction(textCompactionData, byteCompactionData, index, result);
return codeIndex;
}
/// <summary>
/// The Text Compaction mode includes all the printable ASCII characters
/// (i.e. values from 32 to 126) and three ASCII control characters: HT or tab
/// (ASCII value 9), LF or line feed (ASCII value 10), and CR or carriage
/// return (ASCII value 13). The Text Compaction mode also includes various latch
/// and shift characters which are used exclusively within the mode. The Text
/// Compaction mode encodes up to 2 characters per codeword. The compaction rules
/// for converting data into PDF417 codewords are defined in 5.4.2.2. The sub-mode
/// switches are defined in 5.4.2.3.
///
/// <param name="textCompactionData">The text compaction data.</param>
/// <param name="byteCompactionData">The byte compaction data if there</param>
/// was a mode shift.
/// <param name="length">The size of the text compaction and byte compaction data.</param>
/// <param name="result">The decoded data is appended to the result.</param>
/// </summary>
private static void decodeTextCompaction(int[] textCompactionData,
int[] byteCompactionData,
int length,
StringBuilder result)
{
// Beginning from an initial state of the Alpha sub-mode
// The default compaction mode for PDF417 in effect at the start of each symbol shall always be Text
// Compaction mode Alpha sub-mode (uppercase alphabetic). A latch codeword from another mode to the Text
// Compaction mode shall always switch to the Text Compaction Alpha sub-mode.
Mode subMode = Mode.ALPHA;
Mode priorToShiftMode = Mode.ALPHA;
int i = 0;
while (i < length)
{
int subModeCh = textCompactionData[i];
char? ch = null;
switch (subMode)
{
case Mode.ALPHA:
// Alpha (uppercase alphabetic)
if (subModeCh < 26)
{
// Upper case Alpha Character
ch = (char)('A' + subModeCh);
}
else
{
if (subModeCh == 26)
{
ch = ' ';
}
else if (subModeCh == LL)
{
subMode = Mode.LOWER;
}
else if (subModeCh == ML)
{
subMode = Mode.MIXED;
}
else if (subModeCh == PS)
{
// Shift to punctuation
priorToShiftMode = subMode;
subMode = Mode.PUNCT_SHIFT;
}
else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE)
{
result.Append((char)byteCompactionData[i]);
}
else if (subModeCh == TEXT_COMPACTION_MODE_LATCH)
{
subMode = Mode.ALPHA;
}
}
break;
case Mode.LOWER:
// Lower (lowercase alphabetic)
if (subModeCh < 26)
{
ch = (char)('a' + subModeCh);
}
else
{
if (subModeCh == 26)
{
ch = ' ';
}
else if (subModeCh == AS)
{
// Shift to alpha
priorToShiftMode = subMode;
subMode = Mode.ALPHA_SHIFT;
}
else if (subModeCh == ML)
{
subMode = Mode.MIXED;
}
else if (subModeCh == PS)
{
// Shift to punctuation
priorToShiftMode = subMode;
subMode = Mode.PUNCT_SHIFT;
}
else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE)
{
result.Append((char)byteCompactionData[i]);
}
else if (subModeCh == TEXT_COMPACTION_MODE_LATCH)
{
subMode = Mode.ALPHA;
}
}
break;
case Mode.MIXED:
// Mixed (numeric and some punctuation)
if (subModeCh < PL)
{
ch = MIXED_CHARS[subModeCh];
}
else
{
if (subModeCh == PL)
{
subMode = Mode.PUNCT;
}
else if (subModeCh == 26)
{
ch = ' ';
}
else if (subModeCh == LL)
{
subMode = Mode.LOWER;
}
else if (subModeCh == AL)
{
subMode = Mode.ALPHA;
}
else if (subModeCh == PS)
{
// Shift to punctuation
priorToShiftMode = subMode;
subMode = Mode.PUNCT_SHIFT;
}
else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE)
{
result.Append((char)byteCompactionData[i]);
}
else if (subModeCh == TEXT_COMPACTION_MODE_LATCH)
{
subMode = Mode.ALPHA;
}
}
break;
case Mode.PUNCT:
// Punctuation
if (subModeCh < PAL)
{
ch = PUNCT_CHARS[subModeCh];
}
else
{
if (subModeCh == PAL)
{
subMode = Mode.ALPHA;
}
else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE)
{
result.Append((char)byteCompactionData[i]);
}
else if (subModeCh == TEXT_COMPACTION_MODE_LATCH)
{
subMode = Mode.ALPHA;
}
}
break;
case Mode.ALPHA_SHIFT:
// Restore sub-mode
subMode = priorToShiftMode;
if (subModeCh < 26)
{
ch = (char)('A' + subModeCh);
}
else
{
if (subModeCh == 26)
{
ch = ' ';
}
else if (subModeCh == TEXT_COMPACTION_MODE_LATCH)
{
subMode = Mode.ALPHA;
}
}
break;
case Mode.PUNCT_SHIFT:
// Restore sub-mode
subMode = priorToShiftMode;
if (subModeCh < PAL)
{
ch = PUNCT_CHARS[subModeCh];
}
else
{
if (subModeCh == PAL)
{
subMode = Mode.ALPHA;
}
else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE)
{
// PS before Shift-to-Byte is used as a padding character,
// see 5.4.2.4 of the specification
result.Append((char)byteCompactionData[i]);
}
else if (subModeCh == TEXT_COMPACTION_MODE_LATCH)
{
subMode = Mode.ALPHA;
}
}
break;
}
if (ch != null)
{
// Append decoded character to result
result.Append(ch.Value);
}
i++;
}
}
/// <summary>
/// Byte Compaction mode (see 5.4.3) permits all 256 possible 8-bit byte values to be encoded.
/// This includes all ASCII characters value 0 to 127 inclusive and provides for international
/// character set support.
///
/// <param name="mode">The byte compaction mode i.e. 901 or 924</param>
/// <param name="codewords">The array of codewords (data + error)</param>
/// <param name="codeIndex">The current index into the codeword array.</param>
/// <param name="result">The decoded data is appended to the result.</param>
/// <returns>The next index into the codeword array.</returns>
/// </summary>
private static int byteCompaction(int mode, int[] codewords, int codeIndex, StringBuilder result)
{
if (mode == BYTE_COMPACTION_MODE_LATCH)
{
// Total number of Byte Compaction characters to be encoded
// is not a multiple of 6
int count = 0;
long value = 0;
char[] decodedData = new char[6];
int[] byteCompactedCodewords = new int[6];
bool end = false;
int nextCode = codewords[codeIndex++];
while ((codeIndex < codewords[0]) && !end)
{
byteCompactedCodewords[count++] = nextCode;
// Base 900
value = 900 * value + nextCode;
nextCode = codewords[codeIndex++];
// perhaps it should be ok to check only nextCode >= TEXT_COMPACTION_MODE_LATCH
if (nextCode == TEXT_COMPACTION_MODE_LATCH ||
nextCode == BYTE_COMPACTION_MODE_LATCH ||
nextCode == NUMERIC_COMPACTION_MODE_LATCH ||
nextCode == BYTE_COMPACTION_MODE_LATCH_6 ||
nextCode == BEGIN_MACRO_PDF417_CONTROL_BLOCK ||
nextCode == BEGIN_MACRO_PDF417_OPTIONAL_FIELD ||
nextCode == MACRO_PDF417_TERMINATOR)
{
codeIndex--;
end = true;
}
else
{
if ((count%5 == 0) && (count > 0))
{
// Decode every 5 codewords
// Convert to Base 256
for (int j = 0; j < 6; ++j)
{
decodedData[5 - j] = (char) (value%256);
value >>= 8;
}
result.Append(decodedData);
count = 0;
}
}
}
// if the end of all codewords is reached the last codeword needs to be added
if (codeIndex == codewords[0] && nextCode < TEXT_COMPACTION_MODE_LATCH)
byteCompactedCodewords[count++] = nextCode;
// If Byte Compaction mode is invoked with codeword 901,
// the last group of codewords is interpreted directly
// as one byte per codeword, without compaction.
for (int i = 0; i < count; i++)
{
result.Append((char)byteCompactedCodewords[i]);
}
}
else if (mode == BYTE_COMPACTION_MODE_LATCH_6)
{
// Total number of Byte Compaction characters to be encoded
// is an integer multiple of 6
int count = 0;
long value = 0;
bool end = false;
while (codeIndex < codewords[0] && !end)
{
int code = codewords[codeIndex++];
if (code < TEXT_COMPACTION_MODE_LATCH)
{
count++;
// Base 900
value = 900 * value + code;
}
else
{
if (code == TEXT_COMPACTION_MODE_LATCH ||
code == BYTE_COMPACTION_MODE_LATCH ||
code == NUMERIC_COMPACTION_MODE_LATCH ||
code == BYTE_COMPACTION_MODE_LATCH_6 ||
code == BEGIN_MACRO_PDF417_CONTROL_BLOCK ||
code == BEGIN_MACRO_PDF417_OPTIONAL_FIELD ||
code == MACRO_PDF417_TERMINATOR)
{
codeIndex--;
end = true;
}
}
if ((count % 5 == 0) && (count > 0))
{
// Decode every 5 codewords
// Convert to Base 256
char[] decodedData = new char[6];
for (int j = 0; j < 6; ++j)
{
decodedData[5 - j] = (char)(value & 0xFF);
value >>= 8;
}
result.Append(decodedData);
count = 0;
}
}
}
return codeIndex;
}
/// <summary>
/// Numeric Compaction mode (see 5.4.4) permits efficient encoding of numeric data strings.
///
/// <param name="codewords">The array of codewords (data + error)</param>
/// <param name="codeIndex">The current index into the codeword array.</param>
/// <param name="result">The decoded data is appended to the result.</param>
/// <returns>The next index into the codeword array.</returns>
/// </summary>
private static int numericCompaction(int[] codewords, int codeIndex, StringBuilder result)
{
int count = 0;
bool end = false;
int[] numericCodewords = new int[MAX_NUMERIC_CODEWORDS];
while (codeIndex < codewords[0] && !end)
{
int code = codewords[codeIndex++];
if (codeIndex == codewords[0])
{
end = true;
}
if (code < TEXT_COMPACTION_MODE_LATCH)
{
numericCodewords[count] = code;
count++;
}
else
{
if (code == TEXT_COMPACTION_MODE_LATCH ||
code == BYTE_COMPACTION_MODE_LATCH ||
code == BYTE_COMPACTION_MODE_LATCH_6 ||
code == BEGIN_MACRO_PDF417_CONTROL_BLOCK ||
code == BEGIN_MACRO_PDF417_OPTIONAL_FIELD ||
code == MACRO_PDF417_TERMINATOR)
{
codeIndex--;
end = true;
}
}
if (count % MAX_NUMERIC_CODEWORDS == 0 ||
code == NUMERIC_COMPACTION_MODE_LATCH ||
end)
{
// Re-invoking Numeric Compaction mode (by using codeword 902
// while in Numeric Compaction mode) serves to terminate the
// current Numeric Compaction mode grouping as described in 5.4.4.2,
// and then to start a new one grouping.
if (count > 0)
{
String s = decodeBase900toBase10(numericCodewords, count);
if (s == null)
return -1;
result.Append(s);
count = 0;
}
}
}
return codeIndex;
}
/// <summary>
/// Convert a list of Numeric Compacted codewords from Base 900 to Base 10.
/// EXAMPLE
/// Encode the fifteen digit numeric string 000213298174000
/// Prefix the numeric string with a 1 and set the initial value of
/// t = 1 000 213 298 174 000
/// Calculate codeword 0
/// d0 = 1 000 213 298 174 000 mod 900 = 200
///
/// t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082
/// Calculate codeword 1
/// d1 = 1 111 348 109 082 mod 900 = 282
///
/// t = 1 111 348 109 082 div 900 = 1 234 831 232
/// Calculate codeword 2
/// d2 = 1 234 831 232 mod 900 = 632
///
/// t = 1 234 831 232 div 900 = 1 372 034
/// Calculate codeword 3
/// d3 = 1 372 034 mod 900 = 434
///
/// t = 1 372 034 div 900 = 1 524
/// Calculate codeword 4
/// d4 = 1 524 mod 900 = 624
///
/// t = 1 524 div 900 = 1
/// Calculate codeword 5
/// d5 = 1 mod 900 = 1
/// t = 1 div 900 = 0
/// Codeword sequence is: 1, 624, 434, 632, 282, 200
///
/// Decode the above codewords involves
/// 1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 +
/// 632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000
///
/// Remove leading 1 => Result is 000213298174000
/// <param name="codewords">The array of codewords</param>
/// <param name="count">The number of codewords</param>
/// <returns>The decoded string representing the Numeric data.</returns>
/// </summary>
private static String decodeBase900toBase10(int[] codewords, int count)
{
#if SILVERLIGHT4 || SILVERLIGHT5 || NET40 || NET45 || NETFX_CORE
BigInteger result = BigInteger.Zero;
for (int i = 0; i < count; i++)
{
result = BigInteger.Add(result, BigInteger.Multiply(EXP900[count - i - 1], new BigInteger(codewords[i])));
}
String resultString = result.ToString();
if (resultString[0] != '1')
{
return null;
}
return resultString.Substring(1);
#else
BigInteger result = BigInteger.Zero;
for (int i = 0; i < count; i++)
{
result = BigInteger.Addition(result, BigInteger.Multiplication(EXP900[count - i - 1], new BigInteger(codewords[i])));
}
String resultString = result.ToString();
if (resultString[0] != '1')
{
return null;
}
return resultString.Substring(1);
#endif
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Channels
{
using System;
using System.Diagnostics.Contracts;
using System.Net;
using System.Threading.Tasks;
using DotNetty.Common.Concurrency;
using DotNetty.Common.Utilities;
public class DefaultChannelHandlerInvoker : IChannelHandlerInvoker
{
static readonly Action<object> InvokeChannelReadCompleteAction = ctx => ChannelHandlerInvokerUtil.InvokeChannelReadCompleteNow((IChannelHandlerContext)ctx);
static readonly Action<object> InvokeReadAction = ctx => ChannelHandlerInvokerUtil.InvokeReadNow((IChannelHandlerContext)ctx);
static readonly Action<object> InvokeChannelWritabilityChangedAction = ctx => ChannelHandlerInvokerUtil.InvokeChannelWritabilityChangedNow((IChannelHandlerContext)ctx);
static readonly Action<object> InvokeFlushAction = ctx => ChannelHandlerInvokerUtil.InvokeFlushNow((IChannelHandlerContext)ctx);
static readonly Action<object, object> InvokeUserEventTriggeredAction = (ctx, evt) => ChannelHandlerInvokerUtil.InvokeUserEventTriggeredNow((IChannelHandlerContext)ctx, evt);
static readonly Action<object, object> InvokeChannelReadAction = (ctx, msg) => ChannelHandlerInvokerUtil.InvokeChannelReadNow((IChannelHandlerContext)ctx, msg);
static readonly Func<object, object, Task> InvokeWriteAsyncFunc = (ctx, msg) =>
{
var context = (IChannelHandlerContext)ctx;
var channel = (AbstractChannel)context.Channel;
// todo: size is counted twice. is that a problem?
int size = channel.EstimatorHandle.Size(msg);
if (size > 0)
{
ChannelOutboundBuffer buffer = channel.Unsafe.OutboundBuffer;
// Check for null as it may be set to null if the channel is closed already
if (buffer != null)
{
buffer.DecrementPendingOutboundBytes(size);
}
}
return ChannelHandlerInvokerUtil.InvokeWriteAsyncNow(context, msg);
};
readonly IEventExecutor executor;
public DefaultChannelHandlerInvoker(IEventExecutor executor)
{
Contract.Requires(executor != null);
this.executor = executor;
}
public IEventExecutor Executor
{
get { return this.executor; }
}
public void InvokeChannelRegistered(IChannelHandlerContext ctx)
{
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeChannelRegisteredNow(ctx);
}
else
{
this.executor.Execute(() => { ChannelHandlerInvokerUtil.InvokeChannelRegisteredNow(ctx); });
}
}
public void InvokeChannelUnregistered(IChannelHandlerContext ctx)
{
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeChannelUnregisteredNow(ctx);
}
else
{
this.executor.Execute(() => { ChannelHandlerInvokerUtil.InvokeChannelUnregisteredNow(ctx); });
}
}
public void InvokeChannelActive(IChannelHandlerContext ctx)
{
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeChannelActiveNow(ctx);
}
else
{
this.executor.Execute(() => { ChannelHandlerInvokerUtil.InvokeChannelActiveNow(ctx); });
}
}
public void InvokeChannelInactive(IChannelHandlerContext ctx)
{
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeChannelInactiveNow(ctx);
}
else
{
this.executor.Execute(() => { ChannelHandlerInvokerUtil.InvokeChannelInactiveNow(ctx); });
}
}
public void InvokeExceptionCaught(IChannelHandlerContext ctx, Exception cause)
{
Contract.Requires(cause != null);
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeExceptionCaughtNow(ctx, cause);
}
else
{
try
{
this.executor.Execute(() => { ChannelHandlerInvokerUtil.InvokeExceptionCaughtNow(ctx, cause); });
}
catch (Exception t)
{
if (ChannelEventSource.Log.IsWarningEnabled)
{
ChannelEventSource.Log.Warning("Failed to submit an exceptionCaught() event.", t);
ChannelEventSource.Log.Warning("The exceptionCaught() event that was failed to submit was:", cause);
}
}
}
}
public void InvokeUserEventTriggered(IChannelHandlerContext ctx, object evt)
{
Contract.Requires(evt != null);
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeUserEventTriggeredNow(ctx, evt);
}
else
{
this.SafeProcessInboundMessage(InvokeUserEventTriggeredAction, ctx, evt);
}
}
public void InvokeChannelRead(IChannelHandlerContext ctx, object msg)
{
Contract.Requires(msg != null);
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeChannelReadNow(ctx, msg);
}
else
{
this.SafeProcessInboundMessage(InvokeChannelReadAction, ctx, msg);
}
}
public void InvokeChannelReadComplete(IChannelHandlerContext ctx)
{
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeChannelReadCompleteNow(ctx);
}
else
{
this.executor.Execute(InvokeChannelReadCompleteAction, ctx);
}
}
public void InvokeChannelWritabilityChanged(IChannelHandlerContext ctx)
{
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeChannelWritabilityChangedNow(ctx);
}
else
{
this.executor.Execute(InvokeChannelWritabilityChangedAction, ctx);
}
}
public Task InvokeBindAsync(
IChannelHandlerContext ctx, EndPoint localAddress)
{
Contract.Requires(localAddress != null);
// todo: check for cancellation
//if (!validatePromise(ctx, promise, false)) {
// // promise cancelled
// return;
//}
if (this.executor.InEventLoop)
{
return ChannelHandlerInvokerUtil.InvokeBindAsyncNow(ctx, localAddress);
}
else
{
return this.SafeExecuteOutboundAsync(() => ChannelHandlerInvokerUtil.InvokeBindAsyncNow(ctx, localAddress));
}
}
public Task InvokeConnectAsync(
IChannelHandlerContext ctx,
EndPoint remoteAddress, EndPoint localAddress)
{
Contract.Requires(remoteAddress != null);
// todo: check for cancellation
//if (!validatePromise(ctx, promise, false)) {
// // promise cancelled
// return;
//}
if (this.executor.InEventLoop)
{
return ChannelHandlerInvokerUtil.InvokeConnectAsyncNow(ctx, remoteAddress, localAddress);
}
else
{
return this.SafeExecuteOutboundAsync(() => ChannelHandlerInvokerUtil.InvokeConnectAsyncNow(ctx, remoteAddress, localAddress));
}
}
public Task InvokeDisconnectAsync(IChannelHandlerContext ctx)
{
// todo: check for cancellation
//if (!validatePromise(ctx, promise, false)) {
// // promise cancelled
// return;
//}
if (this.executor.InEventLoop)
{
return ChannelHandlerInvokerUtil.InvokeDisconnectAsyncNow(ctx);
}
else
{
return this.SafeExecuteOutboundAsync(() => ChannelHandlerInvokerUtil.InvokeDisconnectAsyncNow(ctx));
}
}
public Task InvokeCloseAsync(IChannelHandlerContext ctx)
{
// todo: check for cancellation
//if (!validatePromise(ctx, promise, false)) {
// // promise cancelled
// return;
//}
if (this.executor.InEventLoop)
{
return ChannelHandlerInvokerUtil.InvokeCloseAsyncNow(ctx);
}
else
{
return this.SafeExecuteOutboundAsync(() => ChannelHandlerInvokerUtil.InvokeCloseAsyncNow(ctx));
}
}
public Task InvokeDeregisterAsync(IChannelHandlerContext ctx)
{
// todo: check for cancellation
//if (!validatePromise(ctx, promise, false)) {
// // promise cancelled
// return;
//}
if (this.executor.InEventLoop)
{
return ChannelHandlerInvokerUtil.InvokeDeregisterAsyncNow(ctx);
}
else
{
return this.SafeExecuteOutboundAsync(() => ChannelHandlerInvokerUtil.InvokeDeregisterAsyncNow(ctx));
}
}
public void InvokeRead(IChannelHandlerContext ctx)
{
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeReadNow(ctx);
}
else
{
this.executor.Execute(InvokeReadAction, ctx);
}
}
public Task InvokeWriteAsync(IChannelHandlerContext ctx, object msg)
{
Contract.Requires(msg != null);
// todo: check for cancellation
//if (!validatePromise(ctx, promise, false)) {
// // promise cancelled
// return;
//}
if (this.executor.InEventLoop)
{
return ChannelHandlerInvokerUtil.InvokeWriteAsyncNow(ctx, msg);
}
else
{
var channel = (AbstractChannel)ctx.Channel;
int size = channel.EstimatorHandle.Size(msg);
if (size > 0)
{
ChannelOutboundBuffer buffer = channel.Unsafe.OutboundBuffer;
// Check for null as it may be set to null if the channel is closed already
if (buffer != null)
{
buffer.IncrementPendingOutboundBytes(size);
}
}
return this.SafeProcessOutboundMessageAsync(InvokeWriteAsyncFunc, ctx, msg);
}
}
public void InvokeFlush(IChannelHandlerContext ctx)
{
if (this.executor.InEventLoop)
{
ChannelHandlerInvokerUtil.InvokeFlushNow(ctx);
}
else
{
this.executor.Execute(InvokeFlushAction, ctx);
}
}
void SafeProcessInboundMessage(Action<object, object> task, object state, object msg)
{
bool success = false;
try
{
this.executor.Execute(task, state, msg);
success = true;
}
finally
{
if (!success)
{
ReferenceCountUtil.Release(msg);
}
}
}
Task SafeExecuteOutboundAsync(Func<Task> task)
{
try
{
return this.executor.SubmitAsync(task);
}
catch (Exception cause)
{
return TaskEx.FromException(cause);
}
}
Task SafeProcessOutboundMessageAsync(Func<object, object, Task> task, object state, object msg)
{
try
{
return this.executor.SubmitAsync(task, state, msg);
}
catch (Exception cause)
{
ReferenceCountUtil.Release(msg);
return TaskEx.FromException(cause);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
public struct ObjectDataBuilder
{
public ObjectDataBuilder(NodeFactory factory)
{
_target = factory.Target;
_data = new ArrayBuilder<byte>();
_relocs = new ArrayBuilder<Relocation>();
Alignment = 1;
DefinedSymbols = new ArrayBuilder<ISymbolNode>();
#if DEBUG
_numReservations = 0;
#endif
}
private TargetDetails _target;
private ArrayBuilder<Relocation> _relocs;
private ArrayBuilder<byte> _data;
internal int Alignment;
internal ArrayBuilder<ISymbolNode> DefinedSymbols;
#if DEBUG
private int _numReservations;
#endif
public int CountBytes
{
get
{
return _data.Count;
}
}
public void RequireAlignment(int align)
{
Alignment = Math.Max(align, Alignment);
}
public void RequirePointerAlignment()
{
RequireAlignment(_target.PointerSize);
}
public void EmitByte(byte emit)
{
_data.Add(emit);
}
public void EmitShort(short emit)
{
EmitByte((byte)(emit & 0xFF));
EmitByte((byte)((emit >> 8) & 0xFF));
}
public void EmitInt(int emit)
{
EmitByte((byte)(emit & 0xFF));
EmitByte((byte)((emit >> 8) & 0xFF));
EmitByte((byte)((emit >> 16) & 0xFF));
EmitByte((byte)((emit >> 24) & 0xFF));
}
public void EmitLong(long emit)
{
EmitByte((byte)(emit & 0xFF));
EmitByte((byte)((emit >> 8) & 0xFF));
EmitByte((byte)((emit >> 16) & 0xFF));
EmitByte((byte)((emit >> 24) & 0xFF));
EmitByte((byte)((emit >> 32) & 0xFF));
EmitByte((byte)((emit >> 40) & 0xFF));
EmitByte((byte)((emit >> 48) & 0xFF));
EmitByte((byte)((emit >> 56) & 0xFF));
}
public void EmitCompressedUInt(uint emit)
{
if (emit < 128)
{
EmitByte((byte)(emit * 2 + 0));
}
else if (emit < 128 * 128)
{
EmitByte((byte)(emit * 4 + 1));
EmitByte((byte)(emit >> 6));
}
else if (emit < 128 * 128 * 128)
{
EmitByte((byte)(emit * 8 + 3));
EmitByte((byte)(emit >> 5));
EmitByte((byte)(emit >> 13));
}
else if (emit < 128 * 128 * 128 * 128)
{
EmitByte((byte)(emit * 16 + 7));
EmitByte((byte)(emit >> 4));
EmitByte((byte)(emit >> 12));
EmitByte((byte)(emit >> 20));
}
else
{
EmitByte((byte)15);
EmitInt((int)emit);
}
}
public void EmitBytes(byte[] bytes)
{
_data.Append(bytes);
}
public void EmitZeroPointer()
{
_data.ZeroExtend(_target.PointerSize);
}
public void EmitZeros(int numBytes)
{
_data.ZeroExtend(numBytes);
}
private Reservation GetReservationTicket(int size)
{
#if DEBUG
_numReservations++;
#endif
Reservation ticket = (Reservation)_data.Count;
_data.ZeroExtend(size);
return ticket;
}
private int ReturnReservationTicket(Reservation reservation)
{
#if DEBUG
Debug.Assert(_numReservations > 0);
_numReservations--;
#endif
return (int)reservation;
}
public Reservation ReserveByte()
{
return GetReservationTicket(1);
}
public void EmitByte(Reservation reservation, byte emit)
{
int offset = ReturnReservationTicket(reservation);
_data[offset] = emit;
}
public Reservation ReserveShort()
{
return GetReservationTicket(2);
}
public void EmitShort(Reservation reservation, short emit)
{
int offset = ReturnReservationTicket(reservation);
_data[offset] = (byte)(emit & 0xFF);
_data[offset + 1] = (byte)((emit >> 8) & 0xFF);
}
public Reservation ReserveInt()
{
return GetReservationTicket(4);
}
public void EmitInt(Reservation reservation, int emit)
{
int offset = ReturnReservationTicket(reservation);
_data[offset] = (byte)(emit & 0xFF);
_data[offset + 1] = (byte)((emit >> 8) & 0xFF);
_data[offset + 2] = (byte)((emit >> 16) & 0xFF);
_data[offset + 3] = (byte)((emit >> 24) & 0xFF);
}
public void AddRelocAtOffset(ISymbolNode symbol, RelocType relocType, int offset, int delta = 0)
{
Relocation symbolReloc = new Relocation();
symbolReloc.Target = symbol;
symbolReloc.RelocType = relocType;
symbolReloc.Offset = offset;
symbolReloc.Delta = delta;
_relocs.Add(symbolReloc);
}
public void EmitReloc(ISymbolNode symbol, RelocType relocType, int delta = 0)
{
AddRelocAtOffset(symbol, relocType, _data.Count, delta);
// And add space for the reloc
switch (relocType)
{
case RelocType.IMAGE_REL_BASED_REL32:
case RelocType.IMAGE_REL_BASED_ABSOLUTE:
EmitInt(0);
break;
case RelocType.IMAGE_REL_BASED_DIR64:
EmitLong(0);
break;
default:
throw new NotImplementedException();
}
}
public void EmitPointerReloc(ISymbolNode symbol, int delta = 0)
{
EmitReloc(symbol, (_target.PointerSize == 8) ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW, delta);
}
public ObjectNode.ObjectData ToObjectData()
{
#if DEBUG
Debug.Assert(_numReservations == 0);
#endif
ObjectNode.ObjectData returnData = new ObjectNode.ObjectData(_data.ToArray(),
_relocs.ToArray(),
Alignment,
DefinedSymbols.ToArray());
return returnData;
}
public enum Reservation { }
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Reflection;
using NUnit.Framework;
#if NET_CORE
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using CS = Microsoft.CodeAnalysis.CSharp;
#endif
namespace Mono.Cecil.Tests {
struct CompilationResult {
internal DateTime source_write_time;
internal string result_file;
public CompilationResult (DateTime write_time, string result_file)
{
this.source_write_time = write_time;
this.result_file = result_file;
}
}
public static class Platform {
public static bool OnMono {
get { return TryGetType ("Mono.Runtime") != null; }
}
public static bool OnCoreClr {
get { return TryGetType ("System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") != null; }
}
public static bool OnWindows {
get { return Environment.OSVersion.Platform == PlatformID.Win32NT; }
}
public static bool HasNativePdbSupport {
get { return OnWindows && !OnMono; }
}
static Type TryGetType (string assemblyQualifiedName)
{
try {
// Note that throwOnError=false only suppresses some exceptions, not all.
return Type.GetType(assemblyQualifiedName, throwOnError: false);
} catch {
return null;
}
}
}
abstract class CompilationService {
Dictionary<string, CompilationResult> files = new Dictionary<string, CompilationResult> ();
bool TryGetResult (string name, out string file_result)
{
file_result = null;
CompilationResult result;
if (!files.TryGetValue (name, out result))
return false;
if (result.source_write_time != File.GetLastWriteTime (name))
return false;
file_result = result.result_file;
return true;
}
public string Compile (string name)
{
string result_file;
if (TryGetResult (name, out result_file))
return result_file;
result_file = CompileFile (name);
RegisterFile (name, result_file);
return result_file;
}
void RegisterFile (string name, string result_file)
{
files [name] = new CompilationResult (File.GetLastWriteTime (name), result_file);
}
protected abstract string CompileFile (string name);
public static string CompileResource (string name)
{
var extension = Path.GetExtension (name);
if (extension == ".il")
return IlasmCompilationService.Instance.Compile (name);
if (extension == ".cs")
#if NET_CORE
return RoslynCompilationService.Instance.Compile (name);
#else
return CodeDomCompilationService.Instance.Compile (name);
#endif
throw new NotSupportedException (extension);
}
protected static string GetCompiledFilePath (string file_name)
{
var tmp_cecil = Path.Combine (Path.GetTempPath (), "cecil");
if (!Directory.Exists (tmp_cecil))
Directory.CreateDirectory (tmp_cecil);
return Path.Combine (tmp_cecil, Path.GetFileName (file_name) + ".dll");
}
public static void Verify (string name)
{
#if !NET_CORE
var output = Platform.OnMono ? ShellService.PEDump (name) : ShellService.PEVerify (name);
if (output.ExitCode != 0)
Assert.Fail (output.ToString ());
#endif
}
}
class IlasmCompilationService : CompilationService {
public static readonly IlasmCompilationService Instance = new IlasmCompilationService ();
protected override string CompileFile (string name)
{
string file = GetCompiledFilePath (name);
var output = ShellService.ILAsm (name, file);
AssertAssemblerResult (output);
return file;
}
static void AssertAssemblerResult (ShellService.ProcessOutput output)
{
if (output.ExitCode != 0)
Assert.Fail (output.ToString ());
}
}
#if NET_CORE
class RoslynCompilationService : CompilationService {
public static readonly RoslynCompilationService Instance = new RoslynCompilationService ();
protected override string CompileFile (string name)
{
var compilation = GetCompilation (name);
var outputName = GetCompiledFilePath (name);
var result = compilation.Emit (outputName);
Assert.IsTrue (result.Success, GetErrorMessage (result));
return outputName;
}
static Compilation GetCompilation (string name)
{
var assemblyName = Path.GetFileNameWithoutExtension (name);
var source = File.ReadAllText (name);
var tpa = BaseAssemblyResolver.TrustedPlatformAssemblies.Value;
var references = new []
{
MetadataReference.CreateFromFile (tpa ["netstandard"]),
MetadataReference.CreateFromFile (tpa ["mscorlib"]),
MetadataReference.CreateFromFile (tpa ["System.Private.CoreLib"]),
MetadataReference.CreateFromFile (tpa ["System.Runtime"]),
MetadataReference.CreateFromFile (tpa ["System.Console"]),
MetadataReference.CreateFromFile (tpa ["System.Security.AccessControl"]),
};
var extension = Path.GetExtension (name);
switch (extension) {
case ".cs":
return CS.CSharpCompilation.Create (
assemblyName,
new [] { CS.SyntaxFactory.ParseSyntaxTree (source) },
references,
new CS.CSharpCompilationOptions (OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release));
default:
throw new NotSupportedException ();
}
}
static string GetErrorMessage (EmitResult result)
{
if (result.Success)
return string.Empty;
var builder = new StringBuilder ();
foreach (var diagnostic in result.Diagnostics)
builder.AppendLine (diagnostic.ToString ());
return builder.ToString ();
}
}
#else
class CodeDomCompilationService : CompilationService {
public static readonly CodeDomCompilationService Instance = new CodeDomCompilationService ();
protected override string CompileFile (string name)
{
string file = GetCompiledFilePath (name);
using (var provider = GetProvider (name)) {
var parameters = GetDefaultParameters (name);
parameters.IncludeDebugInformation = false;
parameters.GenerateExecutable = false;
parameters.OutputAssembly = file;
var results = provider.CompileAssemblyFromFile (parameters, name);
AssertCompilerResults (results);
}
return file;
}
static void AssertCompilerResults (CompilerResults results)
{
Assert.IsFalse (results.Errors.HasErrors, GetErrorMessage (results));
}
static string GetErrorMessage (CompilerResults results)
{
if (!results.Errors.HasErrors)
return string.Empty;
var builder = new StringBuilder ();
foreach (CompilerError error in results.Errors)
builder.AppendLine (error.ToString ());
return builder.ToString ();
}
static CompilerParameters GetDefaultParameters (string name)
{
return GetCompilerInfo (name).CreateDefaultCompilerParameters ();
}
static CodeDomProvider GetProvider (string name)
{
return GetCompilerInfo (name).CreateProvider ();
}
static CompilerInfo GetCompilerInfo (string name)
{
return CodeDomProvider.GetCompilerInfo (
CodeDomProvider.GetLanguageFromExtension (Path.GetExtension (name)));
}
}
#endif
class ShellService {
public class ProcessOutput {
public int ExitCode;
public string StdOut;
public string StdErr;
public ProcessOutput (int exitCode, string stdout, string stderr)
{
ExitCode = exitCode;
StdOut = stdout;
StdErr = stderr;
}
public override string ToString ()
{
return StdOut + StdErr;
}
}
static ProcessOutput RunProcess (string target, params string [] arguments)
{
var stdout = new StringWriter ();
var stderr = new StringWriter ();
var process = new Process {
StartInfo = new ProcessStartInfo {
FileName = target,
Arguments = string.Join (" ", arguments),
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
},
};
process.Start ();
process.OutputDataReceived += (_, args) => stdout.Write (args.Data);
process.ErrorDataReceived += (_, args) => stderr.Write (args.Data);
process.BeginOutputReadLine ();
process.BeginErrorReadLine ();
process.WaitForExit ();
return new ProcessOutput (process.ExitCode, stdout.ToString (), stderr.ToString ());
}
public static ProcessOutput ILAsm (string source, string output)
{
var ilasm = "ilasm";
if (Platform.OnWindows)
ilasm = NetFrameworkTool ("ilasm");
return RunProcess (ilasm, "/nologo", "/dll", "/out:" + Quote (output), Quote (source));
}
static string Quote (string file)
{
return "\"" + file + "\"";
}
public static ProcessOutput PEVerify (string source)
{
return RunProcess (WinSdkTool ("peverify"), "/nologo", Quote (source));
}
public static ProcessOutput PEDump (string source)
{
return RunProcess ("pedump", "--verify code,metadata", Quote (source));
}
static string NetFrameworkTool (string tool)
{
#if NET_CORE
return Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Windows), "Microsoft.NET", "Framework", "v4.0.30319", tool + ".exe");
#else
return Path.Combine (
Path.GetDirectoryName (typeof (object).Assembly.Location),
tool + ".exe");
#endif
}
static string WinSdkTool (string tool)
{
var sdks = new [] {
@"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools",
@"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools",
@"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.1 Tools",
@"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7 Tools",
@"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.2 Tools",
@"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools",
@"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools",
@"Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools",
@"Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools",
@"Microsoft SDKs\Windows\v7.0A\Bin",
};
foreach (var sdk in sdks) {
var pgf = IntPtr.Size == 8
? Environment.GetEnvironmentVariable("ProgramFiles(x86)")
: Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
var exe = Path.Combine (
Path.Combine (pgf, sdk),
tool + ".exe");
if (File.Exists(exe))
return exe;
}
return tool;
}
}
}
| |
//
// VersionTest.cs - NUnit Test Cases for the System.Version class
//
// author:
// Duco Fijma (duco@lorentz.xs4all.nl)
//
// (C) 2002 Duco Fijma
//
using NUnit.Framework;
using System;
namespace MonoTests.System
{
public class VersionTest : TestCase
{
public VersionTest () {}
public void TestCtors ()
{
Version v1;
bool exception;
/*
v1 = new Version ();
AssertEquals ("A1", 0, v1.Major);
AssertEquals ("A2", 0, v1.Minor);
AssertEquals ("A3", -1, v1.Build);
AssertEquals ("A4", -1, v1.Revision);
*/
v1 = new Version (23, 7);
AssertEquals ("A5", 23, v1.Major);
AssertEquals ("A6", 7, v1.Minor);
AssertEquals ("A7", -1, v1.Build);
AssertEquals ("A8", -1, v1.Revision);
v1 = new Version (23, 7, 99);
AssertEquals ("A9", 23, v1.Major);
AssertEquals ("A10", 7, v1.Minor);
AssertEquals ("A11", 99, v1.Build);
AssertEquals ("A12", -1, v1.Revision);
v1 = new Version (23, 7, 99, 42);
AssertEquals ("A13", 23, v1.Major);
AssertEquals ("A14", 7, v1.Minor);
AssertEquals ("A15", 99, v1.Build);
AssertEquals ("A16", 42, v1.Revision);
try {
v1 = new Version (23, -1);
exception = false;
}
catch (ArgumentOutOfRangeException) {
exception = true;
}
Assert ("A17", exception);
try {
v1 = new Version (23, 7, -1);
exception = false;
}
catch (ArgumentOutOfRangeException) {
exception = true;
}
Assert ("A18", exception);
try {
v1 = new Version (23, 7, 99, -1);
exception = false;
}
catch (ArgumentOutOfRangeException) {
exception = true;
}
Assert ("A19", exception);
}
public void TestStringCtor ()
{
Version v1;
bool exception;
v1 = new Version("1.42.79");
AssertEquals ("A1", 1, v1.Major);
AssertEquals ("A2", 42, v1.Minor);
AssertEquals ("A3", 79, v1.Build);
AssertEquals ("A4", -1, v1.Revision);
try {
v1 = new Version ("1.42.-79");
exception = false;
}
catch (ArgumentOutOfRangeException) {
exception = true;
}
Assert ("A5", exception);
try {
v1 = new Version ("1");
exception = false;
}
catch (ArgumentException) {
exception = true;
}
Assert ("A6", exception);
try {
v1 = new Version ("1.2.3.4.5");
exception = false;
}
catch (ArgumentException) {
exception = true;
}
Assert ("A7", exception);
try {
v1 = new Version ((string) null);
exception = false;
}
catch (ArgumentNullException) {
exception = true;
}
Assert ("A6", exception);
}
public void TestClone ()
{
Version v1 = new Version (1, 2, 3, 4);
Version v2 = (Version) v1.Clone ();
Assert ("A1", v1.Equals (v2));
Assert ("A2", !ReferenceEquals (v1, v2));
Version v3 = new Version (); // 0.0
v2 = (Version) v3.Clone ();
Assert ("A3", v3.Equals (v2));
Assert ("A4", !ReferenceEquals (v3, v2));
}
public void TestCompareTo ()
{
Assert ("A1", new Version (1, 2).CompareTo (new Version (1, 1)) > 0);
Assert ("A2", new Version (1, 2, 3).CompareTo (new Version (2, 2, 3)) < 0);
Assert ("A3", new Version (1, 2, 3, 4).CompareTo (new Version (1, 2, 2, 1)) > 0);
Assert ("A4", new Version (1, 3).CompareTo (new Version (1, 2, 2, 1)) > 0);
Assert ("A5", new Version (1, 2, 2).CompareTo (new Version (1, 2, 2, 1)) < 0);
Assert ("A6", new Version (1, 2).CompareTo (new Version (1, 2)) == 0);
Assert ("A7", new Version (1, 2, 3).CompareTo (new Version (1, 2, 3)) == 0);
Assert ("A8", new Version (1, 1) < new Version (1, 2));
Assert ("A9", new Version (1, 2) <= new Version (1, 2));
Assert ("A10", new Version (1, 2) <= new Version (1, 3));
Assert ("A11", new Version (1, 2) >= new Version (1, 2));
Assert ("A12", new Version (1, 3) >= new Version (1, 2));
Assert ("A13", new Version (1, 3) > new Version (1, 2));
Version v1 = new Version(1, 2);
bool exception;
// LAMESPEC: Docs say this should throw a ArgumentNullException,
// but it simply works. Seems any version is subsequent to null
Assert ("A14:", v1.CompareTo (null) > 0);
try {
v1.CompareTo ("A string is not a version");
exception = false;
}
catch (ArgumentException) {
exception = true;
}
Assert ("A15", exception);
}
public void TestEquals ()
{
Version v1 = new Version (1, 2);
Version v2 = new Version (1, 2, 3, 4);
Version v3 = new Version (1, 2, 3, 4);
AssertEquals ("A1", true, v2.Equals (v3));
AssertEquals ("A2", true, v2.Equals (v2));
AssertEquals ("A3", false, v1.Equals (v3));
AssertEquals ("A4", true, v2 == v3);
AssertEquals ("A5", true, v2 == v2);
AssertEquals ("A6", false, v1 == v3);
AssertEquals ("A7", false, v2.Equals ((Version) null));
AssertEquals ("A8", false, v2.Equals ("A string"));
}
public void TestToString ()
{
Version v1 = new Version (1,2);
Version v2 = new Version (1,2,3);
Version v3 = new Version (1,2,3,4);
AssertEquals ("A1", "1.2", v1.ToString ());
AssertEquals ("A2", "1.2.3", v2.ToString ());
AssertEquals ("A3", "1.2.3.4", v3.ToString ());
AssertEquals ("A4", "" , v3.ToString (0));
AssertEquals ("A5", "1" , v3.ToString (1));
AssertEquals ("A6", "1.2" , v3.ToString (2));
AssertEquals ("A7", "1.2.3" , v3.ToString (3));
AssertEquals ("A8", "1.2.3.4" , v3.ToString (4));
bool exception;
try {
v2.ToString (4);
exception = false;
}
catch (ArgumentException) {
exception = true;
}
Assert ("A9", exception);
try {
v3.ToString (42);
exception = false;
}
catch (ArgumentException) {
exception = true;
}
Assert ("A10", exception);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.Net.Abstractions;
using DSharpPlus.Net.Models;
using Newtonsoft.Json;
namespace DSharpPlus.Entities
{
/// <summary>
/// Represents a discord channel.
/// </summary>
public class DiscordChannel : SnowflakeObject, IEquatable<DiscordChannel>
{
/// <summary>
/// Gets ID of the guild to which this channel belongs.
/// </summary>
[JsonProperty("guild_id", NullValueHandling = NullValueHandling.Ignore)]
public ulong GuildId { get; internal set; }
/// <summary>
/// Gets ID of the category that contains this channel.
/// </summary>
[JsonProperty("parent_id", NullValueHandling = NullValueHandling.Include)]
public ulong? ParentId { get; internal set; }
/// <summary>
/// Gets the category that contains this channel.
/// </summary>
[JsonIgnore]
public DiscordChannel Parent
=> this.ParentId.HasValue ? this.Guild.GetChannel(this.ParentId.Value) : null;
/// <summary>
/// Gets the name of this channel.
/// </summary>
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; internal set; }
/// <summary>
/// Gets the type of this channel.
/// </summary>
[JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)]
public ChannelType Type { get; internal set; }
/// <summary>
/// Gets the position of this channel.
/// </summary>
[JsonProperty("position", NullValueHandling = NullValueHandling.Ignore)]
public int Position { get; internal set; }
/// <summary>
/// Gets whether this channel is a DM channel.
/// </summary>
[JsonIgnore]
public bool IsPrivate
=> this.Type == ChannelType.Private || this.Type == ChannelType.Group;
/// <summary>
/// Gets whether this channel is a channel category.
/// </summary>
[JsonIgnore]
public bool IsCategory
=> this.Type == ChannelType.Category;
/// <summary>
/// Gets the guild to which this channel belongs.
/// </summary>
[JsonIgnore]
public DiscordGuild Guild
=> this.Discord.Guilds.TryGetValue(this.GuildId, out var guild) ? guild : null;
/// <summary>
/// Gets a collection of permission overwrites for this channel.
/// </summary>
[JsonIgnore]
public IReadOnlyList<DiscordOverwrite> PermissionOverwrites
=> this._permissionOverwritesLazy.Value;
[JsonProperty("permission_overwrites", NullValueHandling = NullValueHandling.Ignore)]
internal List<DiscordOverwrite> _permissionOverwrites = new List<DiscordOverwrite>();
[JsonIgnore]
private Lazy<IReadOnlyList<DiscordOverwrite>> _permissionOverwritesLazy;
/// <summary>
/// Gets the channel's topic. This is applicable to text channels only.
/// </summary>
[JsonProperty("topic", NullValueHandling = NullValueHandling.Ignore)]
public string Topic { get; internal set; } = "";
/// <summary>
/// Gets the ID of the last message sent in this channel. This is applicable to text channels only.
/// </summary>
[JsonProperty("last_message_id", NullValueHandling = NullValueHandling.Ignore)]
public ulong LastMessageId { get; internal set; } = 0;
/// <summary>
/// Gets this channel's bitrate. This is applicable to voice channels only.
/// </summary>
[JsonProperty("bitrate", NullValueHandling = NullValueHandling.Ignore)]
public int Bitrate { get; internal set; }
/// <summary>
/// Gets this channel's user limit. This is applicable to voice channels only.
/// </summary>
[JsonProperty("user_limit", NullValueHandling = NullValueHandling.Ignore)]
public int UserLimit { get; internal set; }
/// <summary>
/// <para>Gets the slow mode delay configured for this channel.</para>
/// <para>All bots, as well as users with <see cref="Permissions.ManageChannels"/> or <see cref="Permissions.ManageMessages"/> permissions in the channel are exempt from slow mode.</para>
/// </summary>
[JsonProperty("rate_limit_per_user")]
public int? PerUserRateLimit { get; internal set; }
/// <summary>
/// Gets this channel's mention string.
/// </summary>
[JsonIgnore]
public string Mention
=> Formatter.Mention(this);
/// <summary>
/// Gets this channel's children. This applies only to channel categories.
/// </summary>
[JsonIgnore]
public IEnumerable<DiscordChannel> Children
{
get
{
if (!IsCategory)
throw new ArgumentException("Only channel categories contain children.");
return Guild._channels.Values.Where(e => e.ParentId == Id);
}
}
/// <summary>
/// Gets the list of members currently in the channel (if voice channel), or members who can see the channel (otherwise).
/// </summary>
[JsonIgnore]
public virtual IEnumerable<DiscordMember> Users
{
get
{
if (this.Guild == null)
throw new InvalidOperationException("Cannot query users outside of guild channels.");
if (this.Type == ChannelType.Voice)
return Guild.Members.Values.Where(x => x.VoiceState?.ChannelId == this.Id);
return Guild.Members.Values.Where(x => (this.PermissionsFor(x) & Permissions.AccessChannels) == Permissions.AccessChannels);
}
}
/// <summary>
/// Gets whether this channel is an NSFW channel.
/// </summary>
[JsonProperty("nsfw")]
public bool IsNSFW { get; internal set; }
internal DiscordChannel()
{
this._permissionOverwritesLazy = new Lazy<IReadOnlyList<DiscordOverwrite>>(() => new ReadOnlyCollection<DiscordOverwrite>(this._permissionOverwrites));
}
#region Methods
/// <summary>
/// Sends a message to this channel.
/// </summary>
/// <param name="content">Content of the message to send.</param>
/// <param name="tts">Whether the message is to be read using TTS.</param>
/// <param name="embed">Embed to attach to the message.</param>
/// <param name="mentions">Allowed mentions in the message</param>
/// <returns>The sent message.</returns>
public Task<DiscordMessage> SendMessageAsync(string content = null, bool tts = false, DiscordEmbed embed = null, IEnumerable<IMention> mentions = null)
{
if (this.Type != ChannelType.Text && this.Type != ChannelType.Private && this.Type != ChannelType.Group && this.Type != ChannelType.News)
throw new ArgumentException("Cannot send a text message to a non-text channel.");
return this.Discord.ApiClient.CreateMessageAsync(this.Id, content, tts, embed, mentions);
}
/// <summary>
/// Sends a message containing an attached file to this channel.
/// </summary>
/// <param name="fileData">Stream containing the data to attach to the message as a file.</param>
/// <param name="fileName">Name of the file to attach to the message.</param>
/// <param name="content">Content of the message to send.</param>
/// <param name="tts">Whether the message is to be read using TTS.</param>
/// <param name="embed">Embed to attach to the message.</param>
/// <param name="mentions">Allowed mentions in the message</param>
/// <returns>The sent message.</returns>
public Task<DiscordMessage> SendFileAsync(string fileName, Stream fileData, string content = null, bool tts = false, DiscordEmbed embed = null, IEnumerable<IMention> mentions = null)
{
if (this.Type != ChannelType.Text && this.Type != ChannelType.Private && this.Type != ChannelType.Group && this.Type != ChannelType.News)
throw new ArgumentException("Cannot send a file to a non-text channel.");
return this.Discord.ApiClient.UploadFileAsync(this.Id, fileData, fileName, content, tts, embed, mentions);
}
/// <summary>
/// Sends a message containing an attached file to this channel.
/// </summary>
/// <param name="fileData">Stream containing the data to attach to the message as a file.</param>
/// <param name="content">Content of the message to send.</param>
/// <param name="tts">Whether the message is to be read using TTS.</param>
/// <param name="embed">Embed to attach to the message.</param>
/// <param name="mentions">Allowed mentions in the message</param>
/// <returns>The sent message.</returns>
public Task<DiscordMessage> SendFileAsync(FileStream fileData, string content = null, bool tts = false, DiscordEmbed embed = null, IEnumerable<IMention> mentions = null)
{
if (this.Type != ChannelType.Text && this.Type != ChannelType.Private && this.Type != ChannelType.Group && this.Type != ChannelType.News)
throw new ArgumentException("Cannot send a file to a non-text channel.");
return this.Discord.ApiClient.UploadFileAsync(this.Id, fileData, Path.GetFileName(fileData.Name), content,
tts, embed, mentions);
}
/// <summary>
/// Sends a message containing an attached file to this channel.
/// </summary>
/// <param name="filePath">Path to the file to be attached to the message.</param>
/// <param name="content">Content of the message to send.</param>
/// <param name="tts">Whether the message is to be read using TTS.</param>
/// <param name="embed">Embed to attach to the message.</param>
/// <param name="mentions">Allowed mentions in the message</param>
/// <returns>The sent message.</returns>
public async Task<DiscordMessage> SendFileAsync(string filePath, string content = null, bool tts = false, DiscordEmbed embed = null, IEnumerable<IMention> mentions = null)
{
if (this.Type != ChannelType.Text && this.Type != ChannelType.Private && this.Type != ChannelType.Group && this.Type != ChannelType.News)
throw new ArgumentException("Cannot send a file to a non-text channel.");
using (var fs = File.OpenRead(filePath))
return await this.Discord.ApiClient.UploadFileAsync(this.Id, fs, Path.GetFileName(fs.Name), content, tts, embed, mentions).ConfigureAwait(false);
}
/// <summary>
/// Sends a message with several attached files to this channel.
/// </summary>
/// <param name="files">A filename to data stream mapping.</param>
/// <param name="content">Content of the message to send.</param>
/// <param name="tts">Whether the message is to be read using TTS.</param>
/// <param name="embed">Embed to attach to the message.</param>
/// <param name="mentions">Allowed mentions in the message</param>
/// <returns>The sent message.</returns>
public Task<DiscordMessage> SendMultipleFilesAsync(Dictionary<string, Stream> files, string content = "", bool tts = false, DiscordEmbed embed = null, IEnumerable<IMention> mentions = null)
{
if (this.Type != ChannelType.Text && this.Type != ChannelType.Private && this.Type != ChannelType.Group && this.Type != ChannelType.News)
throw new ArgumentException("Cannot send a file to a non-text channel.");
if (files.Count > 10)
throw new ArgumentException("Cannot send more than 10 files with a single message.");
return this.Discord.ApiClient.UploadFilesAsync(this.Id, files, content, tts, embed, mentions);
}
// Please send memes to Naamloos#2887 at discord <3 thank you
/// <summary>
/// Deletes a guild channel
/// </summary>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
public Task DeleteAsync(string reason = null)
=> this.Discord.ApiClient.DeleteChannelAsync(Id, reason);
/// <summary>
/// Clones this channel. This operation will create a channel with identical settings to this one. Note that this will not copy messages.
/// </summary>
/// <param name="reason">Reason for audit logs.</param>
/// <returns>Newly-created channel.</returns>
public async Task<DiscordChannel> CloneAsync(string reason = null)
{
if (this.Guild == null)
throw new InvalidOperationException("Non-guild channels cannot be cloned.");
var ovrs = new List<DiscordOverwriteBuilder>();
foreach (var ovr in this._permissionOverwrites)
ovrs.Add(await new DiscordOverwriteBuilder().FromAsync(ovr).ConfigureAwait(false));
int? bitrate = this.Bitrate;
int? userLimit = this.UserLimit;
Optional<int?> perUserRateLimit = this.PerUserRateLimit;
if (this.Type != ChannelType.Voice)
{
bitrate = null;
userLimit = null;
}
if (this.Type != ChannelType.Text)
{
perUserRateLimit = Optional.FromNoValue<int?>();
}
return await this.Guild.CreateChannelAsync(this.Name, this.Type, this.Parent, this.Topic, bitrate, userLimit, ovrs, this.IsNSFW, perUserRateLimit, reason).ConfigureAwait(false);
}
/// <summary>
/// Returns a specific message
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<DiscordMessage> GetMessageAsync(ulong id)
{
if (this.Discord.Configuration.MessageCacheSize > 0 && this.Discord is DiscordClient dc && dc.MessageCache.TryGet(xm => xm.Id == id && xm.ChannelId == this.Id, out var msg))
return msg;
return await this.Discord.ApiClient.GetMessageAsync(Id, id).ConfigureAwait(false);
}
/// <summary>
/// Modifies the current channel.
/// </summary>
/// <param name="action">Action to perform on this channel</param>
/// <returns></returns>
public Task ModifyAsync(Action<ChannelEditModel> action)
{
var mdl = new ChannelEditModel();
action(mdl);
return this.Discord.ApiClient.ModifyChannelAsync(this.Id, mdl.Name, mdl.Position, mdl.Topic, mdl.Nsfw,
mdl.Parent.HasValue ? mdl.Parent.Value?.Id : default(Optional<ulong?>), mdl.Bitrate, mdl.Userlimit, mdl.PerUserRateLimit,
mdl.AuditLogReason);
}
/// <summary>
/// Updates the channel position
/// </summary>
/// <param name="position"></param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
public Task ModifyPositionAsync(int position, string reason = null)
{
if (this.Guild == null)
throw new InvalidOperationException("Cannot modify order of non-guild channels.");
var chns = this.Guild._channels.Values.Where(xc => xc.Type == this.Type).OrderBy(xc => xc.Position).ToArray();
var pmds = new RestGuildChannelReorderPayload[chns.Length];
for (var i = 0; i < chns.Length; i++)
{
pmds[i] = new RestGuildChannelReorderPayload
{
ChannelId = chns[i].Id
};
if (chns[i].Id == this.Id)
pmds[i].Position = position;
else
pmds[i].Position = chns[i].Position >= position ? chns[i].Position + 1 : chns[i].Position;
}
return this.Discord.ApiClient.ModifyGuildChannelPositionAsync(this.Guild.Id, pmds, reason);
}
/// <summary>
/// Returns a list of messages before a certain message.
/// <param name="limit">The amount of messages to fetch.</param>
/// <param name="before">Message to fetch before from.</param>
/// </summary>
public Task<IReadOnlyList<DiscordMessage>> GetMessagesBeforeAsync(ulong before, int limit = 100)
=> this.GetMessagesInternalAsync(limit, before, null, null);
/// <summary>
/// Returns a list of messages after a certain message.
/// <param name="limit">The amount of messages to fetch.</param>
/// <param name="after">Message to fetch after from.</param>
/// </summary>
public Task<IReadOnlyList<DiscordMessage>> GetMessagesAfterAsync(ulong after, int limit = 100)
=> this.GetMessagesInternalAsync(limit, null, after, null);
/// <summary>
/// Returns a list of messages around a certain message.
/// <param name="limit">The amount of messages to fetch.</param>
/// <param name="around">Message to fetch around from.</param>
/// </summary>
public Task<IReadOnlyList<DiscordMessage>> GetMessagesAroundAsync(ulong around, int limit = 100)
=> this.GetMessagesInternalAsync(limit, null, null, around);
/// <summary>
/// Returns a list of messages from the last message in the channel.
/// <param name="limit">The amount of messages to fetch.</param>
/// </summary>
public Task<IReadOnlyList<DiscordMessage>> GetMessagesAsync(int limit = 100) =>
this.GetMessagesInternalAsync(limit, null, null, null);
private async Task<IReadOnlyList<DiscordMessage>> GetMessagesInternalAsync(int limit = 100, ulong? before = null, ulong? after = null, ulong? around = null)
{
if (this.Type != ChannelType.Text && this.Type != ChannelType.Private && this.Type != ChannelType.Group && this.Type != ChannelType.News)
throw new ArgumentException("Cannot get the messages of a non-text channel.");
if (limit < 0)
throw new ArgumentException("Cannot get a negative number of messages.");
if (limit == 0)
return new DiscordMessage[0];
//return this.Discord.ApiClient.GetChannelMessagesAsync(this.Id, limit, before, after, around);
if (limit > 100 && around != null)
throw new InvalidOperationException("Cannot get more than 100 messages around the specified ID.");
var msgs = new List<DiscordMessage>(limit);
var remaining = limit;
var lastCount = 0;
ulong? last = null;
var isAfter = after != null;
do
{
var fetchSize = remaining > 100 ? 100 : remaining;
var fetch = await this.Discord.ApiClient.GetChannelMessagesAsync(this.Id, fetchSize, !isAfter ? last ?? before : null, isAfter ? last ?? after : null, around).ConfigureAwait(false);
lastCount = fetch.Count;
remaining -= lastCount;
if (!isAfter)
{
msgs.AddRange(fetch);
last = fetch.LastOrDefault()?.Id;
}
else
{
msgs.InsertRange(0, fetch);
last = fetch.FirstOrDefault()?.Id;
}
}
while (remaining > 0 && lastCount > 0);
return new ReadOnlyCollection<DiscordMessage>(msgs);
}
/// <summary>
/// Deletes multiple messages
/// </summary>
/// <param name="messages"></param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
public async Task DeleteMessagesAsync(IEnumerable<DiscordMessage> messages, string reason = null)
{
// don't enumerate more than once
var msgs = messages.Where(x => x.Channel.Id == this.Id).Select(x => x.Id).ToArray();
if (messages == null || !msgs.Any())
throw new ArgumentException("You need to specify at least one message to delete.");
if (msgs.Count() < 2)
{
await this.Discord.ApiClient.DeleteMessageAsync(this.Id, msgs.Single(), reason).ConfigureAwait(false);
return;
}
for (var i = 0; i < msgs.Count(); i += 100)
await this.Discord.ApiClient.DeleteMessagesAsync(this.Id, msgs.Skip(i).Take(100), reason).ConfigureAwait(false);
}
/// <summary>
/// Deletes a message
/// </summary>
/// <param name="message"></param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
public Task DeleteMessageAsync(DiscordMessage message, string reason = null)
=> this.Discord.ApiClient.DeleteMessageAsync(this.Id, message.Id, reason);
/// <summary>
/// Returns a list of invite objects
/// </summary>
/// <returns></returns>
public Task<IReadOnlyList<DiscordInvite>> GetInvitesAsync()
{
if (this.Guild == null)
throw new ArgumentException("Cannot get the invites of a channel that does not belong to a guild.");
return this.Discord.ApiClient.GetChannelInvitesAsync(Id);
}
/// <summary>
/// Create a new invite object
/// </summary>
/// <param name="max_age"></param>
/// <param name="max_uses"></param>
/// <param name="temporary"></param>
/// <param name="unique"></param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
public Task<DiscordInvite> CreateInviteAsync(int max_age = 86400, int max_uses = 0, bool temporary = false, bool unique = false, string reason = null)
=> this.Discord.ApiClient.CreateChannelInviteAsync(Id, max_age, max_uses, temporary, unique, reason);
/// <summary>
/// Adds a channel permission overwrite for specified member.
/// </summary>
/// <param name="member"></param>
/// <param name="allow"></param>
/// <param name="deny"></param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
public Task AddOverwriteAsync(DiscordMember member, Permissions allow = Permissions.None, Permissions deny = Permissions.None, string reason = null)
=> this.Discord.ApiClient.EditChannelPermissionsAsync(this.Id, member.Id, allow, deny, "member", reason);
/// <summary>
/// Adds a channel permission overwrite for specified role.
/// </summary>
/// <param name="role"></param>
/// <param name="allow"></param>
/// <param name="deny"></param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
public Task AddOverwriteAsync(DiscordRole role, Permissions allow = Permissions.None, Permissions deny = Permissions.None, string reason = null)
=> this.Discord.ApiClient.EditChannelPermissionsAsync(this.Id, role.Id, allow, deny, "role", reason);
/// <summary>
/// Post a typing indicator
/// </summary>
/// <returns></returns>
public Task TriggerTypingAsync()
{
if (this.Type != ChannelType.Text && this.Type != ChannelType.Private && this.Type != ChannelType.Group && this.Type != ChannelType.News)
throw new ArgumentException("Cannot start typing in a non-text channel.");
return this.Discord.ApiClient.TriggerTypingAsync(Id);
}
/// <summary>
/// Returns all pinned messages
/// </summary>
/// <returns></returns>
public Task<IReadOnlyList<DiscordMessage>> GetPinnedMessagesAsync()
{
if (this.Type != ChannelType.Text && this.Type != ChannelType.Private && this.Type != ChannelType.Group && this.Type != ChannelType.News)
throw new ArgumentException("A non-text channel does not have pinned messages.");
return this.Discord.ApiClient.GetPinnedMessagesAsync(this.Id);
}
/// <summary>
/// Create a new webhook
/// </summary>
/// <param name="name"></param>
/// <param name="avatar"></param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
public async Task<DiscordWebhook> CreateWebhookAsync(string name, Optional<Stream> avatar = default, string reason = null)
{
var av64 = Optional.FromNoValue<string>();
if (avatar.HasValue && avatar.Value != null)
using (var imgtool = new ImageTool(avatar.Value))
av64 = imgtool.GetBase64();
else if (avatar.HasValue)
av64 = null;
return await this.Discord.ApiClient.CreateWebhookAsync(this.Id, name, av64, reason).ConfigureAwait(false);
}
/// <summary>
/// Returns a list of webhooks
/// </summary>
/// <returns></returns>
public Task<IReadOnlyList<DiscordWebhook>> GetWebhooksAsync()
=> this.Discord.ApiClient.GetChannelWebhooksAsync(this.Id);
/// <summary>
/// Moves a member to this voice channel
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
public async Task PlaceMemberAsync(DiscordMember member)
{
if (this.Type != ChannelType.Voice)
throw new ArgumentException("Cannot place a member in a non-voice channel!"); // be a little more angery, let em learn!!1
await this.Discord.ApiClient.ModifyGuildMemberAsync(this.Guild.Id, member.Id, default, default, default,
default, this.Id, null).ConfigureAwait(false);
}
/// <summary>
/// Calculates permissions for a given member.
/// </summary>
/// <param name="mbr">Member to calculate permissions for.</param>
/// <returns>Calculated permissions for a given member.</returns>
public Permissions PermissionsFor(DiscordMember mbr)
{
// future note: might be able to simplify @everyone role checks to just check any role ... but i'm not sure
// xoxo, ~uwx
//
// you should use a single tilde
// ~emzi
// user > role > everyone
// allow > deny > undefined
// =>
// user allow > user deny > role allow > role deny > everyone allow > everyone deny
// thanks to meew0
if (this.IsPrivate || this.Guild == null)
return Permissions.None;
if (this.Guild.OwnerId == mbr.Id)
return PermissionMethods.FULL_PERMS;
Permissions perms;
// assign @everyone permissions
var everyoneRole = this.Guild.EveryoneRole;
perms = everyoneRole.Permissions;
// roles that member is in
var mbRoles = mbr.Roles.Where(xr => xr.Id != everyoneRole.Id).ToArray();
// assign permissions from member's roles (in order)
perms |= mbRoles.Aggregate(Permissions.None, (c, role) => c | role.Permissions);
// Adminstrator grants all permissions and cannot be overridden
if ((perms & Permissions.Administrator) == Permissions.Administrator)
return PermissionMethods.FULL_PERMS;
// channel overrides for roles that member is in
var mbRoleOverrides = mbRoles
.Select(xr => this._permissionOverwrites.FirstOrDefault(xo => xo.Id == xr.Id))
.Where(xo => xo != null)
.ToList();
// assign channel permission overwrites for @everyone pseudo-role
var everyoneOverwrites = this._permissionOverwrites.FirstOrDefault(xo => xo.Id == everyoneRole.Id);
if (everyoneOverwrites != null)
{
perms &= ~everyoneOverwrites.Denied;
perms |= everyoneOverwrites.Allowed;
}
// assign channel permission overwrites for member's roles (explicit deny)
perms &= ~mbRoleOverrides.Aggregate(Permissions.None, (c, overs) => c | overs.Denied);
// assign channel permission overwrites for member's roles (explicit allow)
perms |= mbRoleOverrides.Aggregate(Permissions.None, (c, overs) => c | overs.Allowed);
// channel overrides for just this member
var mbOverrides = this._permissionOverwrites.FirstOrDefault(xo => xo.Id == mbr.Id);
if (mbOverrides == null) return perms;
// assign channel permission overwrites for just this member
perms &= ~mbOverrides.Denied;
perms |= mbOverrides.Allowed;
return perms;
}
/// <summary>
/// Returns a string representation of this channel.
/// </summary>
/// <returns>String representation of this channel.</returns>
public override string ToString()
{
if (this.Type == ChannelType.Category)
return $"Channel Category {this.Name} ({this.Id})";
if (this.Type == ChannelType.Text || this.Type == ChannelType.News)
return $"Channel #{this.Name} ({this.Id})";
if (!string.IsNullOrWhiteSpace(this.Name))
return $"Channel {this.Name} ({this.Id})";
return $"Channel {this.Id}";
}
#endregion
/// <summary>
/// Checks whether this <see cref="DiscordChannel"/> is equal to another object.
/// </summary>
/// <param name="obj">Object to compare to.</param>
/// <returns>Whether the object is equal to this <see cref="DiscordChannel"/>.</returns>
public override bool Equals(object obj)
{
return this.Equals(obj as DiscordChannel);
}
/// <summary>
/// Checks whether this <see cref="DiscordChannel"/> is equal to another <see cref="DiscordChannel"/>.
/// </summary>
/// <param name="e"><see cref="DiscordChannel"/> to compare to.</param>
/// <returns>Whether the <see cref="DiscordChannel"/> is equal to this <see cref="DiscordChannel"/>.</returns>
public bool Equals(DiscordChannel e)
{
if (ReferenceEquals(e, null))
return false;
if (ReferenceEquals(this, e))
return true;
return this.Id == e.Id;
}
/// <summary>
/// Gets the hash code for this <see cref="DiscordChannel"/>.
/// </summary>
/// <returns>The hash code for this <see cref="DiscordChannel"/>.</returns>
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
/// <summary>
/// Gets whether the two <see cref="DiscordChannel"/> objects are equal.
/// </summary>
/// <param name="e1">First channel to compare.</param>
/// <param name="e2">Second channel to compare.</param>
/// <returns>Whether the two channels are equal.</returns>
public static bool operator ==(DiscordChannel e1, DiscordChannel e2)
{
var o1 = e1 as object;
var o2 = e2 as object;
if ((o1 == null && o2 != null) || (o1 != null && o2 == null))
return false;
if (o1 == null && o2 == null)
return true;
return e1.Id == e2.Id;
}
/// <summary>
/// Gets whether the two <see cref="DiscordChannel"/> objects are not equal.
/// </summary>
/// <param name="e1">First channel to compare.</param>
/// <param name="e2">Second channel to compare.</param>
/// <returns>Whether the two channels are not equal.</returns>
public static bool operator !=(DiscordChannel e1, DiscordChannel e2)
=> !(e1 == e2);
}
}
| |
// <copyright file=CuttingEarsTriangulatorNEW.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// 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>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:57 PM</date>
using HciLab.Utilities.Mathematics.Core;
using System.Windows.Media;
using System.Collections.ObjectModel;
namespace HciLab.Utilities.Mash3D
{
/// <summary>
/// A cutting ears triangulator for simple polygons with no holes. O(n^2)
/// This algorithm is based on the implementation of the Helix Toolkit (http://helixtoolkit.codeplex.com/)
/// </summary>
/// <remarks>
/// Regarding the Helix Toolkit:
/// Based on http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
/// References
/// http://en.wikipedia.org/wiki/Polygon_triangulation
/// http://computacion.cs.cinvestav.mx/~anzures/geom/triangulation.php
/// http://www.codeproject.com/KB/recipes/cspolygontriangulation.aspx
/// </remarks>
public static class CuttingEarsTriangulatorNEW
{
/// <summary>
/// The epsilon.
/// </summary>
private const double Epsilon = 1e-10;
/// <summary>
/// Triangulate a polygon using the cutting ears algorithm.
/// </summary>
/// <remarks>
/// The algorithm does not support holes.
/// </remarks>
/// <param name="contour">
/// the polygon contour
/// </param>
/// <returns>
/// collection of triangle Vector2s
/// </returns>
public static Int32Collection Triangulate(ObservableCollection<Vector2> contour)
{
// allocate and initialize list of indices in polygon
Int32Collection result = new Int32Collection();
int n = contour.Count;
if (n < 3)
{
return null;
}
var V = new int[n];
// we want a counter-clockwise polygon in V
if (Area(contour) > 0)
{
for (int v = 0; v < n; v++)
{
V[v] = v;
}
}
else
{
for (int v = 0; v < n; v++)
{
V[v] = (n - 1) - v;
}
}
int nv = n;
// remove nv-2 Vertices, creating 1 triangle every time
int count = 2 * nv; // error detection
for (int m = 0, v = nv - 1; nv > 2; )
{
// if we loop, it is probably a non-simple polygon
if (0 >= (count--))
{
// ERROR - probable bad polygon!
//return null;
return result;
}
// three consecutive vertices in current polygon, <u,v,w>
int u = v;
if (nv <= u)
{
u = 0; // previous
}
v = u + 1;
if (nv <= v)
{
v = 0; // new v
}
int w = v + 1;
if (nv <= w)
{
w = 0; // next
}
if (Snip(contour, u, v, w, nv, V))
{
int s, t;
// true names of the vertices
int a = V[u];
int b = V[v];
int c = V[w];
// output Triangle
result.Add((ushort)a);
result.Add((ushort)b);
result.Add((ushort)c);
m++;
// remove v from remaining polygon
for (s = v, t = v + 1; t < nv; s++, t++)
{
V[s] = V[t];
}
nv--;
// resest error detection counter
count = 2 * nv;
}
}
return result;
}
// compute area of a contour/polygon
/// <summary>
/// Calculates the area.
/// </summary>
/// <param name="contour">The contour.</param>
/// <returns>The area.</returns>
private static double Area(ObservableCollection<Vector2> contour)
{
int n = contour.Count;
double A = 0.0;
for (int p = n - 1, q = 0; q < n; p = q++)
{
A += contour[p].X * contour[q].Y - contour[q].X * contour[p].Y;
}
return A * 0.5f;
}
/// <summary>
/// Decide if Vector2 (Px,Py) is inside triangle defined by (Ax,Ay) (Bx,By) (Cx,Cy).
/// </summary>
/// <param name="Ax">
/// The ax.
/// </param>
/// <param name="Ay">
/// The ay.
/// </param>
/// <param name="Bx">
/// The bx.
/// </param>
/// <param name="By">
/// The by.
/// </param>
/// <param name="Cx">
/// The cx.
/// </param>
/// <param name="Cy">
/// The cy.
/// </param>
/// <param name="Px">
/// The px.
/// </param>
/// <param name="Py">
/// The py.
/// </param>
/// <returns>
/// The inside triangle.
/// </returns>
private static bool InsideTriangle(
double Ax, double Ay, double Bx, double By, double Cx, double Cy, double Px, double Py)
{
double ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
double cCROSSap, bCROSScp, aCROSSbp;
ax = Cx - Bx;
ay = Cy - By;
bx = Ax - Cx;
by = Ay - Cy;
cx = Bx - Ax;
cy = By - Ay;
apx = Px - Ax;
apy = Py - Ay;
bpx = Px - Bx;
bpy = Py - By;
cpx = Px - Cx;
cpy = Py - Cy;
aCROSSbp = ax * bpy - ay * bpx;
cCROSSap = cx * apy - cy * apx;
bCROSScp = bx * cpy - by * cpx;
return (aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f);
}
/// <summary>
/// The snip.
/// </summary>
/// <param name="contour">The contour.</param>
/// <param name="u">The u.</param>
/// <param name="v">The v.</param>
/// <param name="w">The w.</param>
/// <param name="n">The n.</param>
/// <param name="V">The v.</param>
/// <returns>The snip.</returns>
private static bool Snip(ObservableCollection<Vector2> contour, int u, int v, int w, int n, int[] V)
{
int p;
double Ax, Ay, Bx, By, Cx, Cy, Px, Py;
Ax = contour[V[u]].X;
Ay = contour[V[u]].Y;
Bx = contour[V[v]].X;
By = contour[V[v]].Y;
Cx = contour[V[w]].X;
Cy = contour[V[w]].Y;
if (Epsilon > (((Bx - Ax) * (Cy - Ay)) - ((By - Ay) * (Cx - Ax))))
{
return false;
}
for (p = 0; p < n; p++)
{
if ((p == u) || (p == v) || (p == w))
{
continue;
}
Px = contour[V[p]].X;
Py = contour[V[p]].Y;
if (InsideTriangle(Ax, Ay, Bx, By, Cx, Cy, Px, Py))
{
return false;
}
}
return true;
}
}
}
| |
#region License, Terms and Conditions
//
// Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono
// Written by Atif Aziz (www.raboof.com)
// Copyright (c) 2005 Atif Aziz. All rights reserved.
//
// 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 3 of the License, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#endregion
namespace Jayrock.Json
{
#region Imports
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
using Jayrock.Json.Conversion;
#endregion
/// <summary>
/// Represents a JSON Number. This class models a number as a string
/// and only converts to a native numerical representation when needed
/// and therefore told.
/// </summary>
/// <remarks>
/// This class cannot be used to compare two numbers or perform
/// mathematical operations like addition and substraction without
/// first converting to an actual native numerical data type.
/// Use <see cref="LogicallyEquals"/> to test for equality.
/// </remarks>
[ Serializable ]
public struct JsonNumber : IConvertible
{
private readonly string _value;
public JsonNumber(string value)
{
if (value != null && !IsValid(value))
throw new ArgumentException("value");
_value = value;
}
private string Value
{
get { return Mask.EmptyString(_value, "0"); }
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override bool Equals(object obj)
{
return obj != null && (obj is JsonNumber) && Equals((JsonNumber) obj);
}
public bool Equals(JsonNumber other)
{
return Value.Equals(other.Value);
}
public override string ToString()
{
return Value;
}
public bool LogicallyEquals(object o)
{
if (o == null)
return false;
return Convert.ChangeType(this, o.GetType(), CultureInfo.InvariantCulture).Equals(o);
}
//
// IMPORTANT! The following ToXXX methods will throw
// OverflowException in case the JsonNumber instance contains a value
// that is too big or small to be represented as the request type.
//
public bool ToBoolean()
{
return ToInt64() != 0;
}
public char ToChar()
{
return (char) Convert.ToUInt16(Value, CultureInfo.InvariantCulture);
}
public byte ToByte()
{
return Convert.ToByte(Value, CultureInfo.InvariantCulture);
}
public short ToInt16()
{
return Convert.ToInt16(Value, CultureInfo.InvariantCulture);
}
public int ToInt32()
{
return Convert.ToInt32(Value, CultureInfo.InvariantCulture);
}
public long ToInt64()
{
return Convert.ToInt64(Value, CultureInfo.InvariantCulture);
}
public float ToSingle()
{
return Convert.ToSingle(Value, CultureInfo.InvariantCulture);
}
public double ToDouble()
{
return Convert.ToDouble(Value, CultureInfo.InvariantCulture);
}
public decimal ToDecimal()
{
return decimal.Parse(Value, NumberStyles.Float, CultureInfo.InvariantCulture);
}
public DateTime ToDateTime()
{
return UnixTime.ToDateTime(ToInt64());
}
#region IConvertible implementation
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return ToBoolean();
}
char IConvertible.ToChar(IFormatProvider provider)
{
return ToChar();
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(ToInt32());
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return ToByte();
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return ToInt16();
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(Value, provider);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return ToInt32();
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(Value, provider);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return ToInt64();
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(Value, provider);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return ToSingle();
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return ToDouble();
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return ToDecimal();
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return ToDateTime();
}
string IConvertible.ToString(IFormatProvider provider)
{
return ToString();
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return Convert.ChangeType(this, conversionType, provider);
}
#endregion
//
// Explicit conversion operators.
//
public static explicit operator byte(JsonNumber number)
{
return number.ToByte();
}
public static explicit operator short(JsonNumber number)
{
return number.ToInt16();
}
public static explicit operator int(JsonNumber number)
{
return number.ToInt32();
}
public static explicit operator long(JsonNumber number)
{
return number.ToInt64();
}
public static explicit operator float(JsonNumber number)
{
return number.ToSingle();
}
public static explicit operator double(JsonNumber number)
{
return number.ToDouble();
}
public static explicit operator decimal(JsonNumber number)
{
return number.ToDecimal();
}
public static explicit operator DateTime(JsonNumber number)
{
return number.ToDateTime();
}
/// <summary>
/// Determines if given text is a valid number per JSON grammar
/// described in RFC 4627.
/// </summary>
public static bool IsValid(string text)
{
return IsValid(text, NumberStyles.None);
}
/// <summary>
/// Determines if given text is a valid number per JSON grammar
/// described in RFC 4627. An additional parameter can be used
/// to specify whether leading and/or trailing white space should
/// be allowed or not.
/// </summary>
/// <remarks>
/// If whitespace is allowed then any whitespace as per Unicode
/// is permitted, which is a wider set than what, for example,
/// <see cref="NumberStyles.AllowTrailingWhite"/> and
/// <see cref="NumberStyles.AllowLeadingWhite"/> list in their
/// documentation.
/// </remarks>
public static bool IsValid(string text, NumberStyles styles)
{
if (text == null) throw new ArgumentNullException("text");
if (styles >= 0 && (int) styles < _grammars.Length)
return _grammars[(int) styles].IsMatch(text);
throw new ArgumentException(null, "styles");
}
// WARNING! There be dragons!
// We assume that MS will never change the values assigned to
// the members of NumberStyles, at least not the following ones.
private static readonly Regex[] _grammars = new Regex[]
{
Regex(false, false), // 0 = None
Regex(true, false), // 1 = AllowLeadingWhite
Regex(false, true), // 2 = AllowTrailingWhite
Regex(true, true), // 3 = AllowLeadingWhite | AllowTrailingWhite
};
private static Regex Regex(bool lws, bool rws)
{
return new Regex(
"^"
+ (lws ? @"\s*" : null)
/*
number = [ minus ] int [ frac ] [ exp ]
decimal-point = %x2E ; .
digit1-9 = %x31-39 ; 1-9
e = %x65 / %x45 ; e E
exp = e [ minus / plus ] 1*DIGIT
frac = decimal-point 1*DIGIT
int = zero / ( digit1-9 *DIGIT )
minus = %x2D ; -
plus = %x2B ; +
zero = %x30 ; 0
*/
+ @" -? # [ minus ]
# int
( 0 # zero
| [1-9][0-9]* ) # / ( digit1-9 *DIGIT )
# [ frac ]
( \. # decimal-point
[0-9]+ )? # 1*DIGIT
# [ exp ]
( [eE] # e
[+-]? # [ minus / plus ]
[0-9]+ )? # 1*DIGIT
" // NOTE! DO NOT move the closing quote
// Moving it to the line above change the pattern!
+ (rws ? @"\s*" : null)
+ "$",
RegexOptions.IgnorePatternWhitespace
| RegexOptions.ExplicitCapture
| RegexOptions.Compiled);
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using TIKSN.Finance.ForeignExchange.Bank;
using TIKSN.Globalization;
using TIKSN.Time;
using Xunit;
namespace TIKSN.Finance.ForeignExchange.Tests
{
public class FederalReserveSystemTests
{
const string skip = "API changed, code needs to be adopted";
private readonly ICurrencyFactory _currencyFactory;
private readonly ITimeProvider _timeProvider;
public FederalReserveSystemTests()
{
var services = new ServiceCollection();
services.AddMemoryCache();
services.AddSingleton<ICurrencyFactory, CurrencyFactory>();
services.AddSingleton<IRegionFactory, RegionFactory>();
services.AddSingleton<ITimeProvider, TimeProvider>();
var serviceProvider = services.BuildServiceProvider();
_currencyFactory = serviceProvider.GetRequiredService<ICurrencyFactory>();
_timeProvider = serviceProvider.GetRequiredService<ITimeProvider>();
}
[Fact(Skip = skip)]
public async Task Calculation001()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var pairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default);
foreach (var pair in pairs)
{
var Before = new Money(pair.BaseCurrency);
var rate = await Bank.GetExchangeRateAsync(pair, DateTime.Now, default);
var After = await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTime.Now, default);
Assert.True(After.Amount == rate * Before.Amount);
}
}
[Fact(Skip = skip)]
public async Task ConversionDirection001()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var USDollar = new CurrencyInfo(new System.Globalization.RegionInfo("US"));
var PoundSterling = new CurrencyInfo(new System.Globalization.RegionInfo("GB"));
var BeforeInPound = new Money(PoundSterling, 100m);
var AfterInDollar = await Bank.ConvertCurrencyAsync(BeforeInPound, USDollar, DateTime.Now, default);
Assert.True(BeforeInPound.Amount < AfterInDollar.Amount);
}
[Fact(Skip = skip)]
public async Task ConvertCurrency001()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
foreach (var pair in await Bank.GetCurrencyPairsAsync(DateTime.Now, default))
{
var Before = new Money(pair.BaseCurrency, 10m);
var After = await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTime.Now, default);
Assert.True(After.Amount > decimal.Zero);
Assert.True(After.Currency == pair.CounterCurrency);
}
}
[Fact(Skip = skip)]
public async Task ConvertCurrency002()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var LastYear = DateTime.Now.AddYears(-1);
foreach (var pair in await Bank.GetCurrencyPairsAsync(LastYear, default))
{
var Before = new Money(pair.BaseCurrency, 10m);
var After = await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, LastYear, default);
Assert.True(After.Amount > decimal.Zero);
Assert.True(After.Currency == pair.CounterCurrency);
}
}
[Fact(Skip = skip)]
public async Task ConvertCurrency003()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
foreach (var pair in await Bank.GetCurrencyPairsAsync(DateTime.Now, default))
{
var Before = new Money(pair.BaseCurrency, 10m);
await
Assert.ThrowsAsync<ArgumentException>(
async () =>
await Bank.ConvertCurrencyAsync(Before, pair.CounterCurrency, DateTime.Now.AddMinutes(1d), default));
}
}
[Fact(Skip = skip)]
public async Task ConvertCurrency004()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var Before = new Money(new CurrencyInfo(new System.Globalization.RegionInfo("AL")), 10m);
await
Assert.ThrowsAsync<ArgumentException>(
async () =>
await Bank.ConvertCurrencyAsync(Before, new CurrencyInfo(new System.Globalization.RegionInfo("AM")), DateTime.Now.AddMinutes(1d), default));
}
[Fact(Skip = skip)]
public async Task GetCurrencyPairs001()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var pairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default);
foreach (var pair in pairs)
{
var reversed = new CurrencyPair(pair.CounterCurrency, pair.BaseCurrency);
Assert.Contains(pairs, C => C == reversed);
}
}
[Fact(Skip = skip)]
public async Task GetCurrencyPairs002()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var pairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default);
var uniquePairs = new System.Collections.Generic.HashSet<CurrencyPair>();
foreach (var pair in pairs)
{
Assert.True(uniquePairs.Add(pair));
}
Assert.True(uniquePairs.Count == pairs.Count());
}
[Fact(Skip = skip)]
public async Task GetCurrencyPairs003()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
await
Assert.ThrowsAsync<ArgumentException>(
async () =>
await Bank.GetCurrencyPairsAsync(DateTime.Now.AddMinutes(1d), default));
}
[Fact(Skip = skip)]
public async Task GetCurrencyPairs004()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var pairs = await Bank.GetCurrencyPairsAsync(DateTime.Now, default);
Assert.Contains(pairs, C => C.ToString() == "AUD/USD");
Assert.Contains(pairs, C => C.ToString() == "BRL/USD");
Assert.Contains(pairs, C => C.ToString() == "CAD/USD");
Assert.Contains(pairs, C => C.ToString() == "CNY/USD");
Assert.Contains(pairs, C => C.ToString() == "DKK/USD");
Assert.Contains(pairs, C => C.ToString() == "EUR/USD");
Assert.Contains(pairs, C => C.ToString() == "HKD/USD");
Assert.Contains(pairs, C => C.ToString() == "INR/USD");
Assert.Contains(pairs, C => C.ToString() == "JPY/USD");
Assert.Contains(pairs, C => C.ToString() == "MYR/USD");
Assert.Contains(pairs, C => C.ToString() == "MXN/USD");
Assert.Contains(pairs, C => C.ToString() == "NZD/USD");
Assert.Contains(pairs, C => C.ToString() == "NOK/USD");
Assert.Contains(pairs, C => C.ToString() == "SGD/USD");
Assert.Contains(pairs, C => C.ToString() == "ZAR/USD");
Assert.Contains(pairs, C => C.ToString() == "KRW/USD");
Assert.Contains(pairs, C => C.ToString() == "LKR/USD");
Assert.Contains(pairs, C => C.ToString() == "SEK/USD");
Assert.Contains(pairs, C => C.ToString() == "CHF/USD");
Assert.Contains(pairs, C => C.ToString() == "TWD/USD");
Assert.Contains(pairs, C => C.ToString() == "THB/USD");
Assert.Contains(pairs, C => C.ToString() == "GBP/USD");
Assert.Contains(pairs, C => C.ToString() == "USD/AUD");
Assert.Contains(pairs, C => C.ToString() == "USD/BRL");
Assert.Contains(pairs, C => C.ToString() == "USD/CAD");
Assert.Contains(pairs, C => C.ToString() == "USD/CNY");
Assert.Contains(pairs, C => C.ToString() == "USD/DKK");
Assert.Contains(pairs, C => C.ToString() == "USD/EUR");
Assert.Contains(pairs, C => C.ToString() == "USD/HKD");
Assert.Contains(pairs, C => C.ToString() == "USD/INR");
Assert.Contains(pairs, C => C.ToString() == "USD/JPY");
Assert.Contains(pairs, C => C.ToString() == "USD/MYR");
Assert.Contains(pairs, C => C.ToString() == "USD/MXN");
Assert.Contains(pairs, C => C.ToString() == "USD/NZD");
Assert.Contains(pairs, C => C.ToString() == "USD/NOK");
Assert.Contains(pairs, C => C.ToString() == "USD/SGD");
Assert.Contains(pairs, C => C.ToString() == "USD/ZAR");
Assert.Contains(pairs, C => C.ToString() == "USD/KRW");
Assert.Contains(pairs, C => C.ToString() == "USD/LKR");
Assert.Contains(pairs, C => C.ToString() == "USD/SEK");
Assert.Contains(pairs, C => C.ToString() == "USD/CHF");
Assert.Contains(pairs, C => C.ToString() == "USD/TWD");
Assert.Contains(pairs, C => C.ToString() == "USD/THB");
Assert.Contains(pairs, C => C.ToString() == "USD/GBP");
}
[Fact(Skip = skip)]
public async Task GetExchangeRate001()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
foreach (var pair in await Bank.GetCurrencyPairsAsync(DateTime.Now, default))
{
var rate = await Bank.GetExchangeRateAsync(pair, DateTime.Now, default);
Assert.True(rate > decimal.Zero);
}
}
[Fact(Skip = skip)]
public async Task GetExchangeRate002()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var LastYear = DateTime.Now.AddYears(-1);
foreach (var pair in await Bank.GetCurrencyPairsAsync(LastYear, default))
{
var rate = await Bank.GetExchangeRateAsync(pair, LastYear, default);
Assert.True(rate > decimal.Zero);
}
}
[Fact(Skip = skip)]
public async Task GetExchangeRate003()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
foreach (var pair in await Bank.GetCurrencyPairsAsync(DateTime.Now, default))
{
await Assert.ThrowsAsync<ArgumentException>(
async () =>
await Bank.GetExchangeRateAsync(pair, DateTime.Now.AddMinutes(1d), default));
}
}
[Fact(Skip = skip)]
public async Task GetExchangeRate004()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var pair = new CurrencyPair(new CurrencyInfo(new System.Globalization.RegionInfo("AL")), new CurrencyInfo(new System.Globalization.RegionInfo("AM")));
await Assert.ThrowsAsync<ArgumentException>(async () => await Bank.GetExchangeRateAsync(pair, DateTime.Now.AddMinutes(1d), default));
}
[Fact(Skip = skip)]
public async Task GetExchangeRate005()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var pair = new CurrencyPair(new CurrencyInfo(new System.Globalization.RegionInfo("US")), new CurrencyInfo(new System.Globalization.RegionInfo("CN")));
var rate = await Bank.GetExchangeRateAsync(pair, DateTime.Now, default);
Assert.True(rate > decimal.One);
}
[Fact(Skip = skip)]
public async Task GetExchangeRate006()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var pair = new CurrencyPair(new CurrencyInfo(new System.Globalization.RegionInfo("US")), new CurrencyInfo(new System.Globalization.RegionInfo("SG")));
var rate = await Bank.GetExchangeRateAsync(pair, DateTime.Now, default);
Assert.True(rate > decimal.One);
}
[Fact(Skip = skip)]
public async Task GetExchangeRate007()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var pair = new CurrencyPair(new CurrencyInfo(new System.Globalization.RegionInfo("US")), new CurrencyInfo(new System.Globalization.RegionInfo("DE")));
var rate = await Bank.GetExchangeRateAsync(pair, DateTime.Now, default);
Assert.True(rate < decimal.One);
}
[Fact(Skip = skip)]
public async Task GetExchangeRate008()
{
var Bank = new FederalReserveSystem(_currencyFactory, _timeProvider);
var pair = new CurrencyPair(new CurrencyInfo(new System.Globalization.RegionInfo("US")), new CurrencyInfo(new System.Globalization.RegionInfo("GB")));
var rate = await Bank.GetExchangeRateAsync(pair, DateTime.Now, default);
Assert.True(rate < decimal.One);
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Linq.Tests
{
public class QueryableTests
{
[Fact]
public void AsQueryable()
{
Assert.NotNull(((IEnumerable)(new int[] { })).AsQueryable());
}
[Fact]
public void AsQueryableT()
{
Assert.NotNull((new int[] { }).AsQueryable());
}
[Fact]
public void NullAsQueryableT()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).AsQueryable());
}
[Fact]
public void NullAsQueryable()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable)null).AsQueryable());
}
private class NonGenericEnumerableSoWeDontNeedADependencyOnTheAssemblyWithNonGeneric : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield break;
}
}
[Fact]
public void NonGenericToQueryable()
{
Assert.Throws<ArgumentException>(() => new NonGenericEnumerableSoWeDontNeedADependencyOnTheAssemblyWithNonGeneric().AsQueryable());
}
[Fact]
public void ReturnsSelfIfPossible()
{
IEnumerable<int> query = Enumerable.Repeat(1, 2).AsQueryable();
Assert.Same(query, query.AsQueryable());
}
[Fact]
public void ReturnsSelfIfPossibleNonGeneric()
{
IEnumerable query = Enumerable.Repeat(1, 2).AsQueryable();
Assert.Same(query, query.AsQueryable());
}
[Fact]
public static void QueryableOfQueryable()
{
IQueryable<int> queryable1 = new [] { 1, 2, 3 }.AsQueryable();
IQueryable<int>[] queryableArray1 = { queryable1, queryable1 };
IQueryable<IQueryable<int>> queryable2 = queryableArray1.AsQueryable();
ParameterExpression expression1 = Expression.Parameter(typeof(IQueryable<int>), "i");
ParameterExpression[] expressionArray1 = { expression1 };
IQueryable<IQueryable<int>> queryable3 = queryable2.Select(Expression.Lambda<Func<IQueryable<int>, IQueryable<int>>>(expression1, expressionArray1));
int i = queryable3.Count();
Assert.Equal(2, i);
}
[Fact]
public static void MatchSequencePattern()
{
// If a change to Queryable has required a change to the exception list in this test
// make the same change at src/System.Linq/tests/ConsistencyTests.cs
MethodInfo enumerableNotInQueryable = GetMissingExtensionMethod(
typeof(Enumerable),
typeof(Queryable),
new [] {
"ToLookup",
"ToDictionary",
"ToArray",
"AsEnumerable",
"ToList",
"Fold",
"LeftJoin",
"Append",
"Prepend",
}
);
Assert.True(enumerableNotInQueryable == null, string.Format("Enumerable method {0} not defined by Queryable", enumerableNotInQueryable));
MethodInfo queryableNotInEnumerable = GetMissingExtensionMethod(
typeof(Queryable),
typeof(Enumerable),
new [] {
"AsQueryable"
}
);
Assert.True(queryableNotInEnumerable == null, string.Format("Queryable method {0} not defined by Enumerable", queryableNotInEnumerable));
}
private static MethodInfo GetMissingExtensionMethod(Type a, Type b, IEnumerable<string> excludedMethods)
{
var dex = new HashSet<string>(excludedMethods);
var aMethods =
a.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => m.CustomAttributes.Any(c => c.AttributeType == typeof(ExtensionAttribute)))
.ToLookup(m => m.Name);
MethodComparer mc = new MethodComparer();
var bMethods = b.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => m.CustomAttributes.Any(c => c.AttributeType == typeof(ExtensionAttribute)))
.ToLookup(m => m, mc);
foreach (var group in aMethods.Where(g => !dex.Contains(g.Key)))
{
foreach (MethodInfo m in group)
{
if (!bMethods.Contains(m))
return m;
}
}
return null;
}
private class MethodComparer : IEqualityComparer<MethodInfo>
{
public int GetHashCode(MethodInfo m) => m.Name.GetHashCode();
public bool Equals(MethodInfo a, MethodInfo b)
{
if (a.Name != b.Name)
return false;
ParameterInfo[] pas = a.GetParameters();
ParameterInfo[] pbs = b.GetParameters();
if (pas.Length != pbs.Length)
return false;
Type[] aArgs = a.GetGenericArguments();
Type[] bArgs = b.GetGenericArguments();
for (int i = 0, n = pas.Length; i < n; i++)
{
ParameterInfo pa = pas[i];
ParameterInfo pb = pbs[i];
Type ta = Strip(pa.ParameterType);
Type tb = Strip(pb.ParameterType);
if (ta.GetTypeInfo().IsGenericType && tb.GetTypeInfo().IsGenericType)
{
if (ta.GetGenericTypeDefinition() != tb.GetGenericTypeDefinition())
{
return false;
}
}
else if (ta.IsGenericParameter && tb.IsGenericParameter)
{
return Array.IndexOf(aArgs, ta) == Array.IndexOf(bArgs, tb);
}
else if (ta != tb)
{
return false;
}
}
return true;
}
private Type Strip(Type t)
{
if (t.GetTypeInfo().IsGenericType)
{
Type g = t;
if (!g.GetTypeInfo().IsGenericTypeDefinition)
{
g = t.GetGenericTypeDefinition();
}
if (g == typeof(IQueryable<>) || g == typeof(IEnumerable<>))
{
return typeof(IEnumerable);
}
if (g == typeof(Expression<>))
{
return t.GetGenericArguments()[0];
}
if (g == typeof(IOrderedEnumerable<>) || g == typeof(IOrderedQueryable<>))
{
return typeof(IOrderedQueryable);
}
}
else
{
if (t == typeof(IQueryable))
{
return typeof(IEnumerable);
}
}
return t;
}
}
}
}
| |
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MessagePack.LZ4;
using Nerdbank.Streams;
namespace MessagePack
{
/// <summary>
/// High-Level API of MessagePack for C#.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Each overload has sufficiently unique required parameters.")]
public static partial class MessagePackSerializer
{
private const int LZ4NotCompressionSizeInLz4BlockType = 64;
/// <summary>
/// Gets or sets the default set of options to use when not explicitly specified for a method call.
/// </summary>
/// <value>The default value is <see cref="MessagePackSerializerOptions.Standard"/>.</value>
/// <remarks>
/// This is an AppDomain or process-wide setting.
/// If you're writing a library, you should NOT set or rely on this property but should instead pass
/// in <see cref="MessagePackSerializerOptions.Standard"/> (or the required options) explicitly to every method call
/// to guarantee appropriate behavior in any application.
/// If you are an app author, realize that setting this property impacts the entire application so it should only be
/// set once, and before any use of <see cref="MessagePackSerializer"/> occurs.
/// </remarks>
public static MessagePackSerializerOptions DefaultOptions { get; set; } = MessagePackSerializerOptions.Standard;
/// <summary>
/// A thread-local, recyclable array that may be used for short bursts of code.
/// </summary>
[ThreadStatic]
private static byte[] scratchArray;
/// <summary>
/// Serializes a given value with the specified buffer writer.
/// </summary>
/// <param name="writer">The buffer writer to serialize with.</param>
/// <param name="value">The value to serialize.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception>
public static void Serialize<T>(IBufferWriter<byte> writer, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
var fastWriter = new MessagePackWriter(writer)
{
CancellationToken = cancellationToken,
};
Serialize(ref fastWriter, value, options);
fastWriter.Flush();
}
/// <summary>
/// Serializes a given value with the specified buffer writer.
/// </summary>
/// <param name="writer">The buffer writer to serialize with.</param>
/// <param name="value">The value to serialize.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception>
public static void Serialize<T>(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options = null)
{
options = options ?? DefaultOptions;
bool originalOldSpecValue = writer.OldSpec;
if (options.OldSpec.HasValue)
{
writer.OldSpec = options.OldSpec.Value;
}
try
{
if (options.Compression.IsCompression() && !PrimitiveChecker<T>.IsMessagePackFixedSizePrimitive)
{
using (var scratchRental = SequencePool.Shared.Rent())
{
var scratch = scratchRental.Value;
MessagePackWriter scratchWriter = writer.Clone(scratch);
options.Resolver.GetFormatterWithVerify<T>().Serialize(ref scratchWriter, value, options);
scratchWriter.Flush();
ToLZ4BinaryCore(scratch, ref writer, options.Compression);
}
}
else
{
options.Resolver.GetFormatterWithVerify<T>().Serialize(ref writer, value, options);
}
}
catch (Exception ex)
{
throw new MessagePackSerializationException($"Failed to serialize {typeof(T).FullName} value.", ex);
}
finally
{
writer.OldSpec = originalOldSpecValue;
}
}
/// <summary>
/// Serializes a given value with the specified buffer writer.
/// </summary>
/// <param name="value">The value to serialize.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>A byte array with the serialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception>
public static byte[] Serialize<T>(T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
byte[] array = scratchArray;
if (array == null)
{
scratchArray = array = new byte[65536];
}
var msgpackWriter = new MessagePackWriter(SequencePool.Shared, array)
{
CancellationToken = cancellationToken,
};
Serialize(ref msgpackWriter, value, options);
return msgpackWriter.FlushAndGetArray();
}
/// <summary>
/// Serializes a given value to the specified stream.
/// </summary>
/// <param name="stream">The stream to serialize to.</param>
/// <param name="value">The value to serialize.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception>
public static void Serialize<T>(Stream stream, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
using (SequencePool.Rental sequenceRental = SequencePool.Shared.Rent())
{
Serialize<T>(sequenceRental.Value, value, options, cancellationToken);
try
{
foreach (ReadOnlyMemory<byte> segment in sequenceRental.Value.AsReadOnlySequence)
{
cancellationToken.ThrowIfCancellationRequested();
stream.Write(segment.Span);
}
}
catch (Exception ex)
{
throw new MessagePackSerializationException("Error occurred while writing the serialized data to the stream.", ex);
}
}
}
/// <summary>
/// Serializes a given value to the specified stream.
/// </summary>
/// <param name="stream">The stream to serialize to.</param>
/// <param name="value">The value to serialize.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>A task that completes with the result of the async serialization operation.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception>
public static async Task SerializeAsync<T>(Stream stream, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
using (SequencePool.Rental sequenceRental = SequencePool.Shared.Rent())
{
Serialize<T>(sequenceRental.Value, value, options, cancellationToken);
try
{
foreach (ReadOnlyMemory<byte> segment in sequenceRental.Value.AsReadOnlySequence)
{
cancellationToken.ThrowIfCancellationRequested();
await stream.WriteAsync(segment, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex)
{
throw new MessagePackSerializationException("Error occurred while writing the serialized data to the stream.", ex);
}
}
}
/// <summary>
/// Deserializes a value of a given type from a sequence of bytes.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="byteSequence">The sequence to deserialize from.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
public static T Deserialize<T>(in ReadOnlySequence<byte> byteSequence, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
var reader = new MessagePackReader(byteSequence)
{
CancellationToken = cancellationToken,
};
return Deserialize<T>(ref reader, options);
}
/// <summary>
/// Deserializes a value of a given type from a sequence of bytes.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="reader">The reader to deserialize from.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
public static T Deserialize<T>(ref MessagePackReader reader, MessagePackSerializerOptions options = null)
{
options = options ?? DefaultOptions;
try
{
if (options.Compression.IsCompression())
{
using (var msgPackUncompressedRental = SequencePool.Shared.Rent())
{
var msgPackUncompressed = msgPackUncompressedRental.Value;
if (TryDecompress(ref reader, msgPackUncompressed))
{
MessagePackReader uncompressedReader = reader.Clone(msgPackUncompressed.AsReadOnlySequence);
return options.Resolver.GetFormatterWithVerify<T>().Deserialize(ref uncompressedReader, options);
}
else
{
return options.Resolver.GetFormatterWithVerify<T>().Deserialize(ref reader, options);
}
}
}
else
{
return options.Resolver.GetFormatterWithVerify<T>().Deserialize(ref reader, options);
}
}
catch (Exception ex)
{
throw new MessagePackSerializationException($"Failed to deserialize {typeof(T).FullName} value.", ex);
}
}
/// <summary>
/// Deserializes a value of a given type from a sequence of bytes.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="buffer">The buffer to deserialize from.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
public static T Deserialize<T>(ReadOnlyMemory<byte> buffer, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
var reader = new MessagePackReader(buffer)
{
CancellationToken = cancellationToken,
};
return Deserialize<T>(ref reader, options);
}
/// <summary>
/// Deserializes a value of a given type from a sequence of bytes.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="buffer">The memory to deserialize from.</param>
/// <param name="bytesRead">The number of bytes read.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
public static T Deserialize<T>(ReadOnlyMemory<byte> buffer, out int bytesRead, CancellationToken cancellationToken = default) => Deserialize<T>(buffer, options: null, out bytesRead, cancellationToken);
/// <summary>
/// Deserializes a value of a given type from a sequence of bytes.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="buffer">The memory to deserialize from.</param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="bytesRead">The number of bytes read.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
public static T Deserialize<T>(ReadOnlyMemory<byte> buffer, MessagePackSerializerOptions options, out int bytesRead, CancellationToken cancellationToken = default)
{
var reader = new MessagePackReader(buffer)
{
CancellationToken = cancellationToken,
};
T result = Deserialize<T>(ref reader, options);
bytesRead = buffer.Slice(0, (int)reader.Consumed).Length;
return result;
}
/// <summary>
/// Deserializes the entire content of a <see cref="Stream"/>.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="stream">
/// The stream to deserialize from.
/// The entire stream will be read, and the first msgpack token deserialized will be returned.
/// If <see cref="Stream.CanSeek"/> is true on the stream, its position will be set to just after the last deserialized byte.
/// </param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
/// <remarks>
/// If multiple top-level msgpack data structures are expected on the stream, use <see cref="MessagePackStreamReader"/> instead.
/// </remarks>
public static T Deserialize<T>(Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
if (TryDeserializeFromMemoryStream(stream, options, cancellationToken, out T result))
{
return result;
}
using (var sequenceRental = SequencePool.Shared.Rent())
{
var sequence = sequenceRental.Value;
try
{
int bytesRead;
do
{
cancellationToken.ThrowIfCancellationRequested();
Span<byte> span = sequence.GetSpan(stream.CanSeek ? (int)(stream.Length - stream.Position) : 0);
bytesRead = stream.Read(span);
sequence.Advance(bytesRead);
}
while (bytesRead > 0);
}
catch (Exception ex)
{
throw new MessagePackSerializationException("Error occurred while reading from the stream.", ex);
}
return DeserializeFromSequenceAndRewindStreamIfPossible<T>(stream, options, sequence, cancellationToken);
}
}
/// <summary>
/// Deserializes the entire content of a <see cref="Stream"/>.
/// </summary>
/// <typeparam name="T">The type of value to deserialize.</typeparam>
/// <param name="stream">
/// The stream to deserialize from.
/// The entire stream will be read, and the first msgpack token deserialized will be returned.
/// If <see cref="Stream.CanSeek"/> is true on the stream, its position will be set to just after the last deserialized byte.
/// </param>
/// <param name="options">The options. Use <c>null</c> to use default options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The deserialized value.</returns>
/// <exception cref="MessagePackSerializationException">Thrown when any error occurs during deserialization.</exception>
/// <remarks>
/// If multiple top-level msgpack data structures are expected on the stream, use <see cref="MessagePackStreamReader"/> instead.
/// </remarks>
public static async ValueTask<T> DeserializeAsync<T>(Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
{
if (TryDeserializeFromMemoryStream(stream, options, cancellationToken, out T result))
{
return result;
}
using (var sequenceRental = SequencePool.Shared.Rent())
{
var sequence = sequenceRental.Value;
try
{
int bytesRead;
do
{
Memory<byte> memory = sequence.GetMemory(stream.CanSeek ? (int)(stream.Length - stream.Position) : 0);
bytesRead = await stream.ReadAsync(memory, cancellationToken).ConfigureAwait(false);
sequence.Advance(bytesRead);
}
while (bytesRead > 0);
}
catch (Exception ex)
{
throw new MessagePackSerializationException("Error occurred while reading from the stream.", ex);
}
return DeserializeFromSequenceAndRewindStreamIfPossible<T>(stream, options, sequence, cancellationToken);
}
}
private delegate int LZ4Transform(ReadOnlySpan<byte> input, Span<byte> output);
private static readonly LZ4Transform LZ4CodecEncode = LZ4Codec.Encode;
private static readonly LZ4Transform LZ4CodecDecode = LZ4Codec.Decode;
private static bool TryDeserializeFromMemoryStream<T>(Stream stream, MessagePackSerializerOptions options, CancellationToken cancellationToken, out T result)
{
cancellationToken.ThrowIfCancellationRequested();
if (stream is MemoryStream ms && ms.TryGetBuffer(out ArraySegment<byte> streamBuffer))
{
result = Deserialize<T>(streamBuffer.AsMemory(checked((int)ms.Position)), options, out int bytesRead, cancellationToken);
// Emulate that we had actually "read" from the stream.
ms.Seek(bytesRead, SeekOrigin.Current);
return true;
}
result = default;
return false;
}
private static T DeserializeFromSequenceAndRewindStreamIfPossible<T>(Stream streamToRewind, MessagePackSerializerOptions options, ReadOnlySequence<byte> sequence, CancellationToken cancellationToken)
{
if (streamToRewind is null)
{
throw new ArgumentNullException(nameof(streamToRewind));
}
var reader = new MessagePackReader(sequence)
{
CancellationToken = cancellationToken,
};
T result = Deserialize<T>(ref reader, options);
if (streamToRewind.CanSeek && !reader.End)
{
// Reverse the stream as many bytes as we left unread.
int bytesNotRead = checked((int)reader.Sequence.Slice(reader.Position).Length);
streamToRewind.Seek(-bytesNotRead, SeekOrigin.Current);
}
return result;
}
/// <summary>
/// Performs LZ4 compression or decompression.
/// </summary>
/// <param name="input">The input for the operation.</param>
/// <param name="output">The buffer to write the result of the operation.</param>
/// <param name="lz4Operation">The LZ4 codec transformation.</param>
/// <returns>The number of bytes written to the <paramref name="output"/>.</returns>
private static int LZ4Operation(in ReadOnlySequence<byte> input, Span<byte> output, LZ4Transform lz4Operation)
{
ReadOnlySpan<byte> inputSpan;
byte[] rentedInputArray = null;
if (input.IsSingleSegment)
{
inputSpan = input.First.Span;
}
else
{
rentedInputArray = ArrayPool<byte>.Shared.Rent((int)input.Length);
input.CopyTo(rentedInputArray);
inputSpan = rentedInputArray.AsSpan(0, (int)input.Length);
}
try
{
return lz4Operation(inputSpan, output);
}
finally
{
if (rentedInputArray != null)
{
ArrayPool<byte>.Shared.Return(rentedInputArray);
}
}
}
private static bool TryDecompress(ref MessagePackReader reader, IBufferWriter<byte> writer)
{
if (!reader.End)
{
// Try to find LZ4Block
if (reader.NextMessagePackType == MessagePackType.Extension)
{
MessagePackReader peekReader = reader.CreatePeekReader();
ExtensionHeader header = peekReader.ReadExtensionFormatHeader();
if (header.TypeCode == ThisLibraryExtensionTypeCodes.Lz4Block)
{
// Read the extension using the original reader, so we "consume" it.
ExtensionResult extension = reader.ReadExtensionFormat();
var extReader = new MessagePackReader(extension.Data);
// The first part of the extension payload is a MessagePack-encoded Int32 that
// tells us the length the data will be AFTER decompression.
int uncompressedLength = extReader.ReadInt32();
// The rest of the payload is the compressed data itself.
ReadOnlySequence<byte> compressedData = extReader.Sequence.Slice(extReader.Position);
Span<byte> uncompressedSpan = writer.GetSpan(uncompressedLength).Slice(0, uncompressedLength);
int actualUncompressedLength = LZ4Operation(compressedData, uncompressedSpan, LZ4CodecDecode);
Debug.Assert(actualUncompressedLength == uncompressedLength, "Unexpected length of uncompressed data.");
writer.Advance(actualUncompressedLength);
return true;
}
}
// Try to find LZ4BlockArray
if (reader.NextMessagePackType == MessagePackType.Array)
{
MessagePackReader peekReader = reader.CreatePeekReader();
var arrayLength = peekReader.ReadArrayHeader();
if (arrayLength != 0 && peekReader.NextMessagePackType == MessagePackType.Extension)
{
ExtensionHeader header = peekReader.ReadExtensionFormatHeader();
if (header.TypeCode == ThisLibraryExtensionTypeCodes.Lz4BlockArray)
{
// switch peekReader as original reader.
reader = peekReader;
// Read from [Ext(98:int,int...), bin,bin,bin...]
var sequenceCount = arrayLength - 1;
var uncompressedLengths = ArrayPool<int>.Shared.Rent(sequenceCount);
try
{
for (int i = 0; i < sequenceCount; i++)
{
uncompressedLengths[i] = reader.ReadInt32();
}
for (int i = 0; i < sequenceCount; i++)
{
var uncompressedLength = uncompressedLengths[i];
var lz4Block = reader.ReadBytes();
Span<byte> uncompressedSpan = writer.GetSpan(uncompressedLength).Slice(0, uncompressedLength);
var actualUncompressedLength = LZ4Operation(lz4Block.Value, uncompressedSpan, LZ4CodecDecode);
Debug.Assert(actualUncompressedLength == uncompressedLength, "Unexpected length of uncompressed data.");
writer.Advance(actualUncompressedLength);
}
return true;
}
finally
{
ArrayPool<int>.Shared.Return(uncompressedLengths);
}
}
}
}
}
return false;
}
private static void ToLZ4BinaryCore(in ReadOnlySequence<byte> msgpackUncompressedData, ref MessagePackWriter writer, MessagePackCompression compression)
{
if (compression == MessagePackCompression.Lz4Block)
{
if (msgpackUncompressedData.Length < LZ4NotCompressionSizeInLz4BlockType)
{
writer.WriteRaw(msgpackUncompressedData);
return;
}
var maxCompressedLength = LZ4Codec.MaximumOutputLength((int)msgpackUncompressedData.Length);
var lz4Span = ArrayPool<byte>.Shared.Rent(maxCompressedLength);
try
{
int lz4Length = LZ4Operation(msgpackUncompressedData, lz4Span, LZ4CodecEncode);
const int LengthOfUncompressedDataSizeHeader = 5;
writer.WriteExtensionFormatHeader(new ExtensionHeader(ThisLibraryExtensionTypeCodes.Lz4Block, LengthOfUncompressedDataSizeHeader + (uint)lz4Length));
writer.WriteInt32((int)msgpackUncompressedData.Length);
writer.WriteRaw(lz4Span.AsSpan(0, lz4Length));
}
finally
{
ArrayPool<byte>.Shared.Return(lz4Span);
}
}
else if (compression == MessagePackCompression.Lz4BlockArray)
{
// Write to [Ext(98:int,int...), bin,bin,bin...]
var sequenceCount = 0;
var extHeaderSize = 0;
foreach (var item in msgpackUncompressedData)
{
sequenceCount++;
extHeaderSize += GetUInt32WriteSize((uint)item.Length);
}
writer.WriteArrayHeader(sequenceCount + 1);
writer.WriteExtensionFormatHeader(new ExtensionHeader(ThisLibraryExtensionTypeCodes.Lz4BlockArray, extHeaderSize));
{
foreach (var item in msgpackUncompressedData)
{
writer.Write(item.Length);
}
}
foreach (var item in msgpackUncompressedData)
{
var maxCompressedLength = LZ4Codec.MaximumOutputLength(item.Length);
var lz4Span = writer.GetSpan(maxCompressedLength + 5);
int lz4Length = LZ4Codec.Encode(item.Span, lz4Span.Slice(5, lz4Span.Length - 5));
WriteBin32Header((uint)lz4Length, lz4Span);
writer.Advance(lz4Length + 5);
}
}
else
{
throw new ArgumentException("Invalid MessagePackCompression Code. Code:" + compression);
}
}
private static int GetUInt32WriteSize(uint value)
{
if (value <= MessagePackRange.MaxFixPositiveInt)
{
return 1;
}
else if (value <= byte.MaxValue)
{
return 2;
}
else if (value <= ushort.MaxValue)
{
return 3;
}
else
{
return 5;
}
}
private static void WriteBin32Header(uint value, Span<byte> span)
{
unchecked
{
span[0] = MessagePackCode.Bin32;
// Write to highest index first so the JIT skips bounds checks on subsequent writes.
span[4] = (byte)value;
span[3] = (byte)(value >> 8);
span[2] = (byte)(value >> 16);
span[1] = (byte)(value >> 24);
}
}
private static class PrimitiveChecker<T>
{
public static readonly bool IsMessagePackFixedSizePrimitive;
static PrimitiveChecker()
{
IsMessagePackFixedSizePrimitive = IsMessagePackFixedSizePrimitiveTypeHelper(typeof(T));
}
}
private static bool IsMessagePackFixedSizePrimitiveTypeHelper(Type type)
{
return type == typeof(short)
|| type == typeof(int)
|| type == typeof(long)
|| type == typeof(ushort)
|| type == typeof(uint)
|| type == typeof(ulong)
|| type == typeof(float)
|| type == typeof(double)
|| type == typeof(bool)
|| type == typeof(byte)
|| type == typeof(sbyte)
|| type == typeof(char)
;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.SignalR.Json;
using Microsoft.AspNet.SignalR.Messaging;
using Microsoft.Extensions.Logging;
using Microsoft.AspNet.SignalR.Transports;
using Newtonsoft.Json;
namespace Microsoft.AspNet.SignalR.Infrastructure
{
public class Connection : IConnection, ITransportConnection, ISubscriber
{
private readonly IMessageBus _bus;
private readonly JsonSerializer _serializer;
private readonly string _baseSignal;
private readonly string _connectionId;
private readonly IList<string> _signals;
private readonly DiffSet<string> _groups;
private readonly IPerformanceCounterManager _counters;
private bool _aborted;
private bool _initializing;
private readonly ILogger _logger;
private readonly IAckHandler _ackHandler;
private readonly IProtectedData _protectedData;
private readonly Func<Message, bool> _excludeMessage;
private readonly IMemoryPool _pool;
public Connection(IMessageBus newMessageBus,
JsonSerializer jsonSerializer,
string baseSignal,
string connectionId,
IList<string> signals,
IList<string> groups,
ILoggerFactory loggerFactory,
IAckHandler ackHandler,
IPerformanceCounterManager performanceCounterManager,
IProtectedData protectedData,
IMemoryPool pool)
{
if (loggerFactory == null)
{
throw new ArgumentNullException("loggerFactory");
}
_bus = newMessageBus;
_serializer = jsonSerializer;
_baseSignal = baseSignal;
_connectionId = connectionId;
_signals = new List<string>(signals.Concat(groups));
_groups = new DiffSet<string>(groups);
_logger = loggerFactory.CreateLogger<Connection>();
_ackHandler = ackHandler;
_counters = performanceCounterManager;
_protectedData = protectedData;
_excludeMessage = m => ExcludeMessage(m);
_pool = pool;
}
public string DefaultSignal
{
get
{
return _baseSignal;
}
}
IList<string> ISubscriber.EventKeys
{
get
{
return _signals;
}
}
public event Action<ISubscriber, string> EventKeyAdded;
public event Action<ISubscriber, string> EventKeyRemoved;
public Action<TextWriter> WriteCursor { get; set; }
public string Identity
{
get
{
return _connectionId;
}
}
public Subscription Subscription
{
get;
set;
}
public Task Send(ConnectionMessage message)
{
if (!String.IsNullOrEmpty(message.Signal) &&
message.Signals != null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
Resources.Error_AmbiguousMessage,
message.Signal,
String.Join(", ", message.Signals)));
}
if (message.Signals != null)
{
return MultiSend(message.Signals, message.Value, message.ExcludedSignals);
}
else
{
Message busMessage = CreateMessage(message.Signal, message.Value);
busMessage.Filter = GetFilter(message.ExcludedSignals);
if (busMessage.WaitForAck)
{
Task ackTask = _ackHandler.CreateAck(busMessage.CommandId);
return _bus.Publish(busMessage).Then(task => task, ackTask);
}
return _bus.Publish(busMessage);
}
}
private Task MultiSend(IList<string> signals, object value, IList<string> excludedSignals)
{
if (signals.Count == 0)
{
// If there's nobody to send to then do nothing
return TaskAsyncHelper.Empty;
}
// Serialize once
ArraySegment<byte> messageBuffer = GetMessageBuffer(value);
string filter = GetFilter(excludedSignals);
var tasks = new Task[signals.Count];
// Send the same data to each connection id
for (int i = 0; i < signals.Count; i++)
{
var message = new Message(_connectionId, signals[i], messageBuffer);
if (!String.IsNullOrEmpty(filter))
{
message.Filter = filter;
}
tasks[i] = _bus.Publish(message);
}
// Return a task that represents all
return Task.WhenAll(tasks);
}
private static string GetFilter(IList<string> excludedSignals)
{
if (excludedSignals != null)
{
return String.Join("|", excludedSignals);
}
return null;
}
private Message CreateMessage(string key, object value)
{
ArraySegment<byte> messageBuffer = GetMessageBuffer(value);
var message = new Message(_connectionId, key, messageBuffer);
var command = value as Command;
if (command != null)
{
// Set the command id
message.CommandId = command.Id;
message.WaitForAck = command.WaitForAck;
}
return message;
}
private ArraySegment<byte> GetMessageBuffer(object value)
{
ArraySegment<byte> messageBuffer;
// We can't use "as" like we do for Command since ArraySegment is a struct
if (value is ArraySegment<byte>)
{
// We assume that any ArraySegment<byte> is already JSON serialized
messageBuffer = (ArraySegment<byte>)value;
}
else
{
messageBuffer = SerializeMessageValue(value);
}
return messageBuffer;
}
private ArraySegment<byte> SerializeMessageValue(object value)
{
using (var writer = new MemoryPoolTextWriter(_pool))
{
_serializer.Serialize(value, writer);
writer.Flush();
var data = writer.Buffer;
var buffer = new byte[data.Count];
Buffer.BlockCopy(data.Array, data.Offset, buffer, 0, data.Count);
return new ArraySegment<byte>(buffer);
}
}
public IDisposable Receive(string messageId, Func<PersistentResponse, object, Task<bool>> callback, int maxMessages, object state)
{
var receiveContext = new ReceiveContext(this, callback, state);
return _bus.Subscribe(this,
messageId,
(result, s) => MessageBusCallback(result, s),
maxMessages,
receiveContext);
}
private static Task<bool> MessageBusCallback(MessageResult result, object state)
{
var context = (ReceiveContext)state;
return context.InvokeCallback(result);
}
private PersistentResponse GetResponse(MessageResult result)
{
// Do a single sweep through the results to process commands and extract values
ProcessResults(result);
Debug.Assert(WriteCursor != null, "Unable to resolve the cursor since the method is null");
var response = new PersistentResponse(_excludeMessage, WriteCursor);
response.Terminal = result.Terminal;
if (!result.Terminal)
{
// Only set these properties if the message isn't terminal
response.Messages = result.Messages;
response.Aborted = _aborted;
response.TotalCount = result.TotalCount;
response.Initializing = _initializing;
_initializing = false;
}
PopulateResponseState(response);
_counters.ConnectionMessagesReceivedTotal.IncrementBy(result.TotalCount);
_counters.ConnectionMessagesReceivedPerSec.IncrementBy(result.TotalCount);
return response;
}
private bool ExcludeMessage(Message message)
{
if (String.IsNullOrEmpty(message.Filter))
{
return false;
}
string[] exclude = message.Filter.Split('|');
return exclude.Any(signal => Identity.Equals(signal, StringComparison.OrdinalIgnoreCase) ||
_signals.Contains(signal) ||
_groups.Contains(signal));
}
private void ProcessResults(MessageResult result)
{
result.Messages.Enumerate<Connection>(message => message.IsCommand,
(connection, message) => ProcessResultsCore(connection, message), this);
}
private static void ProcessResultsCore(Connection connection, Message message)
{
if (message.IsAck)
{
connection._logger.LogError("Connection {0} received an unexpected ACK message.", connection.Identity);
return;
}
var command = connection._serializer.Parse<Command>(message.Value, message.Encoding);
connection.ProcessCommand(command);
// Only send the ack if this command is waiting for it
if (message.WaitForAck)
{
connection._bus.Ack(
acker: connection._connectionId,
commandId: message.CommandId).Catch(connection._logger);
}
}
private void ProcessCommand(Command command)
{
switch (command.CommandType)
{
case CommandType.AddToGroup:
{
var name = command.Value;
if (EventKeyAdded != null)
{
_groups.Add(name);
EventKeyAdded(this, name);
}
}
break;
case CommandType.RemoveFromGroup:
{
var name = command.Value;
if (EventKeyRemoved != null)
{
_groups.Remove(name);
EventKeyRemoved(this, name);
}
}
break;
case CommandType.Initializing:
_initializing = true;
break;
case CommandType.Abort:
_aborted = true;
break;
}
}
private void PopulateResponseState(PersistentResponse response)
{
PopulateResponseState(response, _groups, _serializer, _protectedData, _connectionId);
}
internal static void PopulateResponseState(PersistentResponse response,
DiffSet<string> groupSet,
JsonSerializer serializer,
IProtectedData protectedData,
string connectionId)
{
bool anyChanges = groupSet.DetectChanges();
if (anyChanges)
{
// Create a protected payload of the sorted list
IEnumerable<string> groups = groupSet.GetSnapshot();
// Remove group prefixes before any thing goes over the wire
string groupsString = connectionId + ':' + serializer.Stringify(PrefixHelper.RemoveGroupPrefixes(groups)); ;
// The groups token
response.GroupsToken = protectedData.Protect(groupsString, Purposes.Groups);
}
}
private class ReceiveContext
{
private readonly Connection _connection;
private readonly Func<PersistentResponse, object, Task<bool>> _callback;
private readonly object _callbackState;
public ReceiveContext(Connection connection, Func<PersistentResponse, object, Task<bool>> callback, object callbackState)
{
_connection = connection;
_callback = callback;
_callbackState = callbackState;
}
public Task<bool> InvokeCallback(MessageResult result)
{
var response = _connection.GetResponse(result);
return _callback(response, _callbackState);
}
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\combStreamers2.tcl
// output file is AVcombStreamers2.cs
/// <summary>
/// The testing class derived from AVcombStreamers2
/// </summary>
public class AVcombStreamers2Class
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVcombStreamers2(String [] argv)
{
//Prefix Content is: ""
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
// create pipeline[]
//[]
pl3d = new vtkMultiBlockPLOT3DReader();
pl3d.SetXYZFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combxyz.bin");
pl3d.SetQFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combq.bin");
pl3d.SetScalarFunctionNumber((int)100);
pl3d.SetVectorFunctionNumber((int)202);
pl3d.Update();
ps = new vtkPlaneSource();
ps.SetXResolution((int)4);
ps.SetYResolution((int)4);
ps.SetOrigin((double)2,(double)-2,(double)26);
ps.SetPoint1((double)2,(double)2,(double)26);
ps.SetPoint2((double)2,(double)-2,(double)32);
psMapper = vtkPolyDataMapper.New();
psMapper.SetInputConnection(ps.GetOutputPort());
psActor = new vtkActor();
psActor.SetMapper((vtkMapper)psMapper);
psActor.GetProperty().SetRepresentationToWireframe();
streamer = new vtkDashedStreamLine();
streamer.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0));
streamer.SetSourceConnection(ps.GetOutputPort());
streamer.SetMaximumPropagationTime((double)100);
streamer.SetIntegrationStepLength((double).2);
streamer.SetStepLength((double).001);
streamer.SetNumberOfThreads((int)1);
streamer.SetIntegrationDirectionToForward();
streamMapper = vtkPolyDataMapper.New();
streamMapper.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort());
streamMapper.SetScalarRange(
(double)((vtkDataSet)pl3d.GetOutput().GetBlock(0)).GetScalarRange()[0],
(double)((vtkDataSet)pl3d.GetOutput().GetBlock(0)).GetScalarRange()[1]);
streamline = new vtkActor();
streamline.SetMapper((vtkMapper)streamMapper);
outline = new vtkStructuredGridOutlineFilter();
outline.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0));
outlineMapper = vtkPolyDataMapper.New();
outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort());
outlineActor = new vtkActor();
outlineActor.SetMapper((vtkMapper)outlineMapper);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor((vtkProp)psActor);
ren1.AddActor((vtkProp)outlineActor);
ren1.AddActor((vtkProp)streamline);
ren1.SetBackground((double)1,(double)1,(double)1);
renWin.SetSize((int)300,(int)300);
ren1.SetBackground((double)0.1,(double)0.2,(double)0.4);
cam1 = ren1.GetActiveCamera();
cam1.SetClippingRange((double)3.95297,(double)50);
cam1.SetFocalPoint((double)9.71821,(double)0.458166,(double)29.3999);
cam1.SetPosition((double)2.7439,(double)-37.3196,(double)38.7167);
cam1.SetViewUp((double)-0.16123,(double)0.264271,(double)0.950876);
// render the image[]
//[]
renWin.Render();
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkMultiBlockPLOT3DReader pl3d;
static vtkPlaneSource ps;
static vtkPolyDataMapper psMapper;
static vtkActor psActor;
static vtkDashedStreamLine streamer;
static vtkPolyDataMapper streamMapper;
static vtkActor streamline;
static vtkStructuredGridOutlineFilter outline;
static vtkPolyDataMapper outlineMapper;
static vtkActor outlineActor;
static vtkCamera cam1;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkMultiBlockPLOT3DReader Getpl3d()
{
return pl3d;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setpl3d(vtkMultiBlockPLOT3DReader toSet)
{
pl3d = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPlaneSource Getps()
{
return ps;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setps(vtkPlaneSource toSet)
{
ps = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetpsMapper()
{
return psMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetpsMapper(vtkPolyDataMapper toSet)
{
psMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetpsActor()
{
return psActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetpsActor(vtkActor toSet)
{
psActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDashedStreamLine Getstreamer()
{
return streamer;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setstreamer(vtkDashedStreamLine toSet)
{
streamer = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetstreamMapper()
{
return streamMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetstreamMapper(vtkPolyDataMapper toSet)
{
streamMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getstreamline()
{
return streamline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setstreamline(vtkActor toSet)
{
streamline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStructuredGridOutlineFilter Getoutline()
{
return outline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoutline(vtkStructuredGridOutlineFilter toSet)
{
outline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetoutlineMapper()
{
return outlineMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineMapper(vtkPolyDataMapper toSet)
{
outlineMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetoutlineActor()
{
return outlineActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineActor(vtkActor toSet)
{
outlineActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcam1()
{
return cam1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcam1(vtkCamera toSet)
{
cam1 = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(pl3d!= null){pl3d.Dispose();}
if(ps!= null){ps.Dispose();}
if(psMapper!= null){psMapper.Dispose();}
if(psActor!= null){psActor.Dispose();}
if(streamer!= null){streamer.Dispose();}
if(streamMapper!= null){streamMapper.Dispose();}
if(streamline!= null){streamline.Dispose();}
if(outline!= null){outline.Dispose();}
if(outlineMapper!= null){outlineMapper.Dispose();}
if(outlineActor!= null){outlineActor.Dispose();}
if(cam1!= null){cam1.Dispose();}
}
}
//--- end of script --//
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Mocks;
namespace PythonToolsUITests {
[TestClass]
public class CondaEnvironmentManagerTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
}
private static readonly List<string> DeleteFolder = new List<string>();
private static readonly PackageSpec[] NonExistingPackages = new[] {
PackageSpec.FromArguments("python=0.1"),
};
private static readonly PackageSpec[] Python27Packages = new[] {
PackageSpec.FromArguments("python=2.7"),
};
private static readonly PackageSpec[] Python27AndFlask012Packages = new[] {
PackageSpec.FromArguments("python=2.7"),
PackageSpec.FromArguments("flask=0.12"),
};
[ClassCleanup]
public static void DoCleanup() {
foreach (var folder in DeleteFolder) {
FileUtils.DeleteDirectory(folder);
}
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task CreateEnvironmentByPath() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
var envPath = Path.Combine(TestData.GetTempPath(), "newenv");
bool result = await mgr.CreateAsync(envPath, Python27Packages, ui, CancellationToken.None);
Assert.IsTrue(result, "Create failed.");
Assert.IsTrue(Directory.Exists(envPath), "Environment folder not found.");
Assert.IsTrue(ui.OutputText.Any(line => line.Contains($"Successfully created '{envPath}'")));
AssertCondaMetaFiles(envPath, "python-2.7.*.json");
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task CreateEnvironmentByPathNonExistingPackage() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
var envPath = Path.Combine(TestData.GetTempPath(), "newenvunk");
bool result = await mgr.CreateAsync(envPath, NonExistingPackages, ui, CancellationToken.None);
Assert.IsFalse(result, "Create did not fail.");
// Account for Anaconda version differences
Assert.IsTrue(
ui.ErrorText.Any(line => line.Contains("The following packages are not available from current channels")) ||
ui.OutputText.Any(line => line.Contains("PackageNotFoundError")),
"Expected a message indicating packages were not found."
);
Assert.IsTrue(ui.OutputText.Any(line => line.Contains($"Failed to create '{envPath}'")));
Assert.IsFalse(Directory.Exists(envPath), "Environment folder was found.");
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task CreateEnvironmentByName() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
var envName = GetUnusedEnvironmentName(mgr);
bool result = await mgr.CreateAsync(envName, Python27Packages, ui, CancellationToken.None);
var envPath = EnqueueEnvironmentDeletion(mgr, envName);
Assert.IsTrue(result, "Create failed.");
Assert.IsTrue(Directory.Exists(envPath), "Environment folder not found.");
Assert.IsTrue(ui.OutputText.Any(line => line.Contains($"Successfully created '{envName}'")));
AssertCondaMetaFiles(envPath, "python-2.7.*.json");
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task CreateEnvironmentByNameRelativePath() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
// Relative path passed to conda.exe using -n (by name) argument.
// It's created in a subfolder of the usual default location.
var envName = GetUnusedEnvironmentName(mgr);
var envRelName = "relative\\" + envName;
bool result = await mgr.CreateAsync(envRelName, Python27Packages, ui, CancellationToken.None);
var envPath = EnqueueEnvironmentDeletion(mgr, envName);
Assert.IsTrue(result, "Create failed.");
Assert.IsTrue(Directory.Exists(envPath), "Environment folder not found.");
Assert.IsTrue(ui.OutputText.Any(line => line.Contains($"Successfully created '{envRelName}'")));
AssertCondaMetaFiles(envPath, "python-2.7.*.json");
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task CreateEnvironmentByNameInvalidChars() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
var envName = "<invalid*name>";
bool result = await mgr.CreateAsync(envName, Python27Packages, ui, CancellationToken.None);
Assert.IsFalse(result, "Create did not fail.");
Assert.IsTrue(ui.ErrorText.Any(line => line.Contains($"Invalid name or path '{envName}'")));
Assert.IsTrue(ui.OutputText.Any(line => line.Contains($"Failed to create '{envName}'")));
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task CreateEnvironmentByPathFromEnvironmentFileCondaOnly() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
// cookies conda package
var envPath = Path.Combine(TestData.GetTempPath(), "conda-only");
var envFilePath = TestData.GetPath("TestData", "CondaEnvironments", "conda-only.yml");
bool result = await mgr.CreateFromEnvironmentFileAsync(envPath, envFilePath, ui, CancellationToken.None);
Assert.IsTrue(result, "Create failed.");
AssertSitePackagesFile(envPath, "cookies.py");
AssertCondaMetaFiles(envPath, "cookies-2.2.1*.json", "python-*.json");
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task CreateEnvironmentByPathFromEnvironmentFileCondaAndPip() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
// python 3.4 conda package, flask conda package and flask_testing pip package
var envPath = Path.Combine(TestData.GetTempPath(), "conda-and-pip");
var envFilePath = TestData.GetPath("TestData", "CondaEnvironments", "conda-and-pip.yml");
var result = await mgr.CreateFromEnvironmentFileAsync(envPath, envFilePath, ui, CancellationToken.None);
Assert.IsTrue(result, "Create failed.");
AssertSitePackagesFile(envPath, @"flask\__init__.py");
AssertSitePackagesFile(envPath, @"flask_testing\__init__.py");
AssertCondaMetaFiles(envPath, "flask-*.json", "python-3.4.*.json");
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task CreateEnvironmentByPathFromEnvironmentFileNonExisting() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
var envPath = Path.Combine(TestData.GetTempPath(), "testenv");
var envFilePath = TestData.GetPath("TestData", "CondaEnvironments", "non-existing.yml");
var result = await mgr.CreateFromEnvironmentFileAsync(envPath, envFilePath, ui, CancellationToken.None);
Assert.IsFalse(result, "Create did not fail.");
Assert.IsTrue(ui.ErrorText.Any(line => line.Contains($"File not found '{envFilePath}'")));
Assert.IsTrue(ui.OutputText.Any(line => line.Contains($"Failed to create '{envPath}'")));
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task CreateEnvironmentByPathFromExistingEnvironment() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
var sourceEnvPath = await CreatePython27AndFlask012EnvAsync(mgr, ui, "envsrc");
var envPath = Path.Combine(TestData.GetTempPath(), "envdst");
var result = await mgr.CreateFromExistingEnvironmentAsync(envPath, sourceEnvPath, ui, CancellationToken.None);
Assert.IsTrue(result, "Clone failed.");
AssertCondaMetaFiles(envPath, "flask-*.json", "python-2.7.*.json");
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task ExportEnvironmentFile() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
var envPath = await CreatePython27AndFlask012EnvAsync(mgr, ui, "envtoexport");
var destinationPath = Path.Combine(TestData.GetTempPath(), "exported.yml");
var result = await mgr.ExportEnvironmentFileAsync(envPath, destinationPath, ui, CancellationToken.None);
Assert.IsTrue(result, "Export failed.");
var definition = File.ReadAllText(destinationPath, Encoding.UTF8);
Debug.WriteLine($"Contents of '{destinationPath}':");
Debug.WriteLine(definition);
AssertUtil.Contains(definition, "name:", "dependencies:", "prefix:");
AssertUtil.Contains(definition, "python=2.7.", "flask=0.12.");
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task ExportExplicitSpecificationFile() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
var envPath = await CreatePython27AndFlask012EnvAsync(mgr, ui, "envtoexport");
var destinationPath = Path.Combine(TestData.GetTempPath(), "exported.txt");
var result = await mgr.ExportExplicitSpecificationFileAsync(envPath, destinationPath, ui, CancellationToken.None);
Assert.IsTrue(result, "Export failed.");
var definition = File.ReadAllText(destinationPath, Encoding.UTF8);
Debug.WriteLine($"Contents of '{destinationPath}':");
Debug.WriteLine(definition);
AssertUtil.Contains(definition, "# platform:", "@EXPLICIT");
AssertUtil.Contains(definition, "python-2.7.", "flask-0.12.");
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task DeleteEnvironment() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
var envPath = await CreatePython27AndFlask012EnvAsync(mgr, ui, "envtodelete");
var result = await mgr.DeleteAsync(envPath, ui, CancellationToken.None);
Assert.IsTrue(result, "Delete failed.");
Assert.IsFalse(Directory.Exists(envPath), "Environment folder was not deleted.");
}
[TestMethod, Priority(0)]
[TestCategory("10s")]
public async Task DeleteEnvironmentNonExisting() {
var mgr = CreateEnvironmentManager();
var ui = new MockCondaEnvironmentManagerUI();
var envPath = Path.Combine(TestData.GetTempPath(), "test");
var result = await mgr.DeleteAsync(envPath, ui, CancellationToken.None);
Assert.IsFalse(result, "Delete did not fail.");
Assert.IsTrue(ui.ErrorText.Any(line => line.Contains($"Folder not found '{envPath}'")));
Assert.IsTrue(ui.OutputText.Any(line => line.Contains($"Failed to delete '{envPath}'")));
}
private static async Task<string> CreatePython27AndFlask012EnvAsync(CondaEnvironmentManager mgr, MockCondaEnvironmentManagerUI ui, string name) {
var envPath = Path.Combine(TestData.GetTempPath(), name);
var result = await mgr.CreateAsync(envPath, Python27AndFlask012Packages, ui, CancellationToken.None);
Assert.IsTrue(result, "Create failed.");
AssertCondaMetaFiles(envPath, "flask-*.json", "python-2.7.*.json");
ui.Clear();
return envPath;
}
private static void AssertCondaMetaFiles(string expectedEnvPath, params string[] fileFilters) {
foreach (var fileFilter in fileFilters) {
Assert.IsTrue(Directory.EnumerateFiles(Path.Combine(expectedEnvPath, "conda-meta"), fileFilter).Any(), $"{fileFilter} not found.");
}
}
private static void AssertSitePackagesFile(string envPath, string fileRelativePath) {
Assert.IsTrue(File.Exists(Path.Combine(envPath, "Lib", "site-packages", fileRelativePath)), $"{fileRelativePath} not found.");
}
private static string EnqueueEnvironmentDeletion(CondaEnvironmentManager mgr, string envName) {
var envPath = GetEnvironmentPath(mgr, envName);
if (envPath != null) {
DeleteFolder.Add(envPath);
} else {
Assert.Fail($"Path to '{envName}' was not found in conda info results.");
}
return envPath;
}
private static string GetEnvironmentPath(CondaEnvironmentManager mgr, string envName) {
var info = CondaEnvironmentFactoryProvider.ExecuteCondaInfo(mgr.CondaPath);
return info.EnvironmentFolders.SingleOrDefault(absPath => string.Compare(PathUtils.GetFileOrDirectoryName(absPath), envName, StringComparison.OrdinalIgnoreCase) == 0);
}
private static string GetUnusedEnvironmentName(CondaEnvironmentManager mgr) {
// Avoid names already used by any of the existing environments.
var info = CondaEnvironmentFactoryProvider.ExecuteCondaInfo(mgr.CondaPath);
var used = info.EnvironmentFolders.Select(absPath => PathUtils.GetFileOrDirectoryName(absPath));
string name;
do {
// Pick a random name (instead of incrementing a numerical suffix)
// so this works better if we ever run tests in parallel.
name = Path.GetRandomFileName();
} while (used.Contains(name, StringComparer.OrdinalIgnoreCase));
return name;
}
private static CondaEnvironmentManager CreateEnvironmentManager() {
if (!PythonPaths.AnacondaVersions.Any()) {
Assert.Inconclusive("Anaconda is required.");
}
var version = PythonPaths.AnacondaVersions.FirstOrDefault();
string condaPath = CondaUtils.GetCondaExecutablePath(version.PrefixPath, allowBatch: false);
Assert.IsTrue(File.Exists(condaPath), $"Conda executable not found: '{condaPath}' for environment prefix at '{version.PrefixPath}'");
return CondaEnvironmentManager.Create(condaPath);
}
class MockCondaEnvironmentManagerUI : ICondaEnvironmentManagerUI {
public readonly List<string> ErrorText = new List<string>();
public readonly List<string> OperationFinished = new List<string>();
public readonly List<string> OperationStarted = new List<string>();
public readonly List<string> OutputText = new List<string>();
public void Clear() {
ErrorText.Clear();
OperationFinished.Clear();
OperationStarted.Clear();
OutputText.Clear();
}
public void OnErrorTextReceived(ICondaEnvironmentManager sender, string text) {
ErrorText.Add(text);
Debug.WriteLine(text);
}
public void OnOperationFinished(ICondaEnvironmentManager sender, string operation, bool success) {
OperationFinished.Add(operation);
Debug.WriteLine(operation + $"; success={success}");
}
public void OnOperationStarted(ICondaEnvironmentManager sender, string operation) {
OperationStarted.Add(operation);
Debug.WriteLine(operation);
}
public void OnOutputTextReceived(ICondaEnvironmentManager sender, string text) {
OutputText.Add(text);
Debug.WriteLine(text);
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* 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.
* - Neither the name of the openmetaverse.org 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;
namespace OpenMetaverse.Imaging
{
public class ManagedImage
{
[Flags]
public enum ImageChannels
{
Gray = 1,
Color = 2,
Alpha = 4,
Bump = 8
};
public enum ImageResizeAlgorithm
{
NearestNeighbor
}
/// <summary>
/// Image width
/// </summary>
public int Width;
/// <summary>
/// Image height
/// </summary>
public int Height;
/// <summary>
/// Image channel flags
/// </summary>
public ImageChannels Channels;
/// <summary>
/// Red channel data
/// </summary>
public byte[] Red;
/// <summary>
/// Green channel data
/// </summary>
public byte[] Green;
/// <summary>
/// Blue channel data
/// </summary>
public byte[] Blue;
/// <summary>
/// Alpha channel data
/// </summary>
public byte[] Alpha;
/// <summary>
/// Bump channel data
/// </summary>
public byte[] Bump;
/// <summary>
/// Create a new blank image
/// </summary>
/// <param name="width">width</param>
/// <param name="height">height</param>
/// <param name="channels">channel flags</param>
public ManagedImage(int width, int height, ImageChannels channels)
{
Width = width;
Height = height;
Channels = channels;
int n = width * height;
if ((channels & ImageChannels.Gray) != 0)
{
Red = new byte[n];
}
else if ((channels & ImageChannels.Color) != 0)
{
Red = new byte[n];
Green = new byte[n];
Blue = new byte[n];
}
if ((channels & ImageChannels.Alpha) != 0)
Alpha = new byte[n];
if ((channels & ImageChannels.Bump) != 0)
Bump = new byte[n];
}
#if !NO_UNSAFE
/// <summary>
///
/// </summary>
/// <param name="bitmap"></param>
public ManagedImage(System.Drawing.Bitmap bitmap)
{
Width = bitmap.Width;
Height = bitmap.Height;
int pixelCount = Width * Height;
if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
{
Channels = ImageChannels.Alpha | ImageChannels.Color;
Red = new byte[pixelCount];
Green = new byte[pixelCount];
Blue = new byte[pixelCount];
Alpha = new byte[pixelCount];
System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
unsafe
{
byte* pixel = (byte*)bd.Scan0;
for (int i = 0; i < pixelCount; i++)
{
// GDI+ gives us BGRA and we need to turn that in to RGBA
Blue[i] = *(pixel++);
Green[i] = *(pixel++);
Red[i] = *(pixel++);
Alpha[i] = *(pixel++);
}
}
bitmap.UnlockBits(bd);
}
else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format16bppGrayScale)
{
Channels = ImageChannels.Gray;
Red = new byte[pixelCount];
throw new NotImplementedException("16bpp grayscale image support is incomplete");
}
else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
{
Channels = ImageChannels.Color;
Red = new byte[pixelCount];
Green = new byte[pixelCount];
Blue = new byte[pixelCount];
System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
unsafe
{
byte* pixel = (byte*)bd.Scan0;
for (int i = 0; i < pixelCount; i++)
{
// GDI+ gives us BGR and we need to turn that in to RGB
Blue[i] = *(pixel++);
Green[i] = *(pixel++);
Red[i] = *(pixel++);
}
}
bitmap.UnlockBits(bd);
}
else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppRgb)
{
Channels = ImageChannels.Color;
Red = new byte[pixelCount];
Green = new byte[pixelCount];
Blue = new byte[pixelCount];
System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
unsafe
{
byte* pixel = (byte*)bd.Scan0;
for (int i = 0; i < pixelCount; i++)
{
// GDI+ gives us BGR and we need to turn that in to RGB
Blue[i] = *(pixel++);
Green[i] = *(pixel++);
Red[i] = *(pixel++);
pixel++; // Skip over the empty byte where the Alpha info would normally be
}
}
bitmap.UnlockBits(bd);
}
else
{
throw new NotSupportedException("Unrecognized pixel format: " + bitmap.PixelFormat.ToString());
}
}
#endif
/// <summary>
/// Convert the channels in the image. Channels are created or destroyed as required.
/// </summary>
/// <param name="channels">new channel flags</param>
public void ConvertChannels(ImageChannels channels)
{
if (Channels == channels)
return;
int n = Width * Height;
ImageChannels add = Channels ^ channels & channels;
ImageChannels del = Channels ^ channels & Channels;
if ((add & ImageChannels.Color) != 0)
{
Red = new byte[n];
Green = new byte[n];
Blue = new byte[n];
}
else if ((del & ImageChannels.Color) != 0)
{
Red = null;
Green = null;
Blue = null;
}
if ((add & ImageChannels.Alpha) != 0)
{
Alpha = new byte[n];
FillArray(Alpha, 255);
}
else if ((del & ImageChannels.Alpha) != 0)
Alpha = null;
if ((add & ImageChannels.Bump) != 0)
Bump = new byte[n];
else if ((del & ImageChannels.Bump) != 0)
Bump = null;
Channels = channels;
}
/// <summary>
/// Resize or stretch the image using nearest neighbor (ugly) resampling
/// </summary>
/// <param name="width">new width</param>
/// <param name="height">new height</param>
public void ResizeNearestNeighbor(int width, int height)
{
if (width == Width && height == Height)
return;
byte[]
red = null,
green = null,
blue = null,
alpha = null,
bump = null;
int n = width * height;
int di = 0, si;
if (Red != null) red = new byte[n];
if (Green != null) green = new byte[n];
if (Blue != null) blue = new byte[n];
if (Alpha != null) alpha = new byte[n];
if (Bump != null) bump = new byte[n];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
si = (y * Height / height) * Width + (x * Width / width);
if (Red != null) red[di] = Red[si];
if (Green != null) green[di] = Green[si];
if (Blue != null) blue[di] = Blue[si];
if (Alpha != null) alpha[di] = Alpha[si];
if (Bump != null) bump[di] = Bump[si];
di++;
}
}
Width = width;
Height = height;
Red = red;
Green = green;
Blue = blue;
Alpha = alpha;
Bump = bump;
}
/// <summary>
/// Create a byte array containing 32-bit RGBA data with a bottom-left
/// origin, suitable for feeding directly into OpenGL
/// </summary>
/// <returns>A byte array containing raw texture data</returns>
public byte[] ExportRaw()
{
byte[] raw = new byte[Width * Height * 4];
if ((Channels & ImageChannels.Alpha) != 0)
{
if ((Channels & ImageChannels.Color) != 0)
{
// RGBA
for (int h = 0; h < Height; h++)
{
for (int w = 0; w < Width; w++)
{
int pos = (Height - 1 - h) * Width + w;
int srcPos = h * Width + w;
raw[pos * 4 + 0] = Red[srcPos];
raw[pos * 4 + 1] = Green[srcPos];
raw[pos * 4 + 2] = Blue[srcPos];
raw[pos * 4 + 3] = Alpha[srcPos];
}
}
}
else
{
// Alpha only
for (int h = 0; h < Height; h++)
{
for (int w = 0; w < Width; w++)
{
int pos = (Height - 1 - h) * Width + w;
int srcPos = h * Width + w;
raw[pos * 4 + 0] = Alpha[srcPos];
raw[pos * 4 + 1] = Alpha[srcPos];
raw[pos * 4 + 2] = Alpha[srcPos];
raw[pos * 4 + 3] = Byte.MaxValue;
}
}
}
}
else
{
// RGB
for (int h = 0; h < Height; h++)
{
for (int w = 0; w < Width; w++)
{
int pos = (Height - 1 - h) * Width + w;
int srcPos = h * Width + w;
raw[pos * 4 + 0] = Red[srcPos];
raw[pos * 4 + 1] = Green[srcPos];
raw[pos * 4 + 2] = Blue[srcPos];
raw[pos * 4 + 3] = Byte.MaxValue;
}
}
}
return raw;
}
/// <summary>
/// Create a byte array containing 32-bit RGBA data with a bottom-left
/// origin, suitable for feeding directly into OpenGL
/// </summary>
/// <returns>A byte array containing raw texture data</returns>
public System.Drawing.Bitmap ExportBitmap()
{
byte[] raw = new byte[Width * Height * 4];
if ((Channels & ImageChannels.Alpha) != 0)
{
if ((Channels & ImageChannels.Color) != 0)
{
// RGBA
for (int pos = 0; pos < Height * Width; pos++)
{
raw[pos * 4 + 0] = Blue[pos];
raw[pos * 4 + 1] = Green[pos];
raw[pos * 4 + 2] = Red[pos];
raw[pos * 4 + 3] = Alpha[pos];
}
}
else
{
// Alpha only
for (int pos = 0; pos < Height * Width; pos++)
{
raw[pos * 4 + 0] = Alpha[pos];
raw[pos * 4 + 1] = Alpha[pos];
raw[pos * 4 + 2] = Alpha[pos];
raw[pos * 4 + 3] = Byte.MaxValue;
}
}
}
else
{
// RGB
for (int pos = 0; pos < Height * Width; pos++)
{
raw[pos * 4 + 0] = Blue[pos];
raw[pos * 4 + 1] = Green[pos];
raw[pos * 4 + 2] = Red[pos];
raw[pos * 4 + 3] = Byte.MaxValue;
}
}
System.Drawing.Bitmap b = new System.Drawing.Bitmap(
Width,
Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
System.Drawing.Imaging.BitmapData bd = b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height),
System.Drawing.Imaging.ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
System.Runtime.InteropServices.Marshal.Copy(raw, 0, bd.Scan0, Width * Height * 4);
b.UnlockBits(bd);
return b;
}
public byte[] ExportTGA()
{
byte[] tga = new byte[Width * Height * ((Channels & ImageChannels.Alpha) == 0 ? 3 : 4) + 32];
int di = 0;
tga[di++] = 0; // idlength
tga[di++] = 0; // colormaptype = 0: no colormap
tga[di++] = 2; // image type = 2: uncompressed RGB
tga[di++] = 0; // color map spec is five zeroes for no color map
tga[di++] = 0; // color map spec is five zeroes for no color map
tga[di++] = 0; // color map spec is five zeroes for no color map
tga[di++] = 0; // color map spec is five zeroes for no color map
tga[di++] = 0; // color map spec is five zeroes for no color map
tga[di++] = 0; // x origin = two bytes
tga[di++] = 0; // x origin = two bytes
tga[di++] = 0; // y origin = two bytes
tga[di++] = 0; // y origin = two bytes
tga[di++] = (byte)(Width & 0xFF); // width - low byte
tga[di++] = (byte)(Width >> 8); // width - hi byte
tga[di++] = (byte)(Height & 0xFF); // height - low byte
tga[di++] = (byte)(Height >> 8); // height - hi byte
tga[di++] = (byte)((Channels & ImageChannels.Alpha) == 0 ? 24 : 32); // 24/32 bits per pixel
tga[di++] = (byte)((Channels & ImageChannels.Alpha) == 0 ? 32 : 40); // image descriptor byte
int n = Width * Height;
if ((Channels & ImageChannels.Alpha) != 0)
{
if ((Channels & ImageChannels.Color) != 0)
{
// RGBA
for (int i = 0; i < n; i++)
{
tga[di++] = Blue[i];
tga[di++] = Green[i];
tga[di++] = Red[i];
tga[di++] = Alpha[i];
}
}
else
{
// Alpha only
for (int i = 0; i < n; i++)
{
tga[di++] = Alpha[i];
tga[di++] = Alpha[i];
tga[di++] = Alpha[i];
tga[di++] = Byte.MaxValue;
}
}
}
else
{
// RGB
for (int i = 0; i < n; i++)
{
tga[di++] = Blue[i];
tga[di++] = Green[i];
tga[di++] = Red[i];
}
}
return tga;
}
private static void FillArray(byte[] array, byte value)
{
if (array != null)
{
for (int i = 0; i < array.Length; i++)
array[i] = value;
}
}
public void Clear()
{
FillArray(Red, 0);
FillArray(Green, 0);
FillArray(Blue, 0);
FillArray(Alpha, 0);
FillArray(Bump, 0);
}
public ManagedImage Clone()
{
ManagedImage image = new ManagedImage(Width, Height, Channels);
if (Red != null) image.Red = (byte[])Red.Clone();
if (Green != null) image.Green = (byte[])Green.Clone();
if (Blue != null) image.Blue = (byte[])Blue.Clone();
if (Alpha != null) image.Alpha = (byte[])Alpha.Clone();
if (Bump != null) image.Bump = (byte[])Bump.Clone();
return image;
}
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Xml;
using System.IO;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using FluorineFx.Exceptions;
using FluorineFx.AMF3;
using FluorineFx.Configuration;
using FluorineFx.IO.Writers;
using FluorineFx.Collections;
using FluorineFx.Util;
#if !(NET_1_1)
using System.Collections.Generic;
using FluorineFx.Collections.Generic;
#endif
#if !(NET_1_1) && !(NET_2_0)
using System.Xml.Linq;
#endif
#if SILVERLIGHT
//using System.Xml.Linq;
#else
using System.Data;
using log4net;
#endif
namespace FluorineFx.IO
{
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
public class AMFWriter : BinaryWriter
{
#if !SILVERLIGHT
private static readonly ILog log = LogManager.GetLogger(typeof(AMFWriter));
#endif
bool _useLegacyCollection = true;
bool _useLegacyThrowable = true;
#if !(NET_1_1)
static CopyOnWriteDictionary<string, ClassDefinition> classDefinitions;
Dictionary<Object, int> _amf0ObjectReferences;
Dictionary<Object, int> _objectReferences;
Dictionary<Object, int> _stringReferences;
Dictionary<ClassDefinition, int> _classDefinitionReferences;
static Dictionary<Type, IAMFWriter>[] AmfWriterTable;
#else
static CopyOnWriteDictionary classDefinitions;
Hashtable _amf0ObjectReferences;
Hashtable _objectReferences;
Hashtable _stringReferences;
Hashtable _classDefinitionReferences;
static Hashtable[] AmfWriterTable;
#endif
static AMFWriter()
{
#if !(NET_1_1)
Dictionary<Type, IAMFWriter> amf0Writers = new Dictionary<Type, IAMFWriter>();
#else
Hashtable amf0Writers = new Hashtable();
#endif
AMF0NumberWriter amf0NumberWriter = new AMF0NumberWriter();
amf0Writers.Add(typeof(System.SByte), amf0NumberWriter);
amf0Writers.Add(typeof(System.Byte), amf0NumberWriter);
amf0Writers.Add(typeof(System.Int16), amf0NumberWriter);
amf0Writers.Add(typeof(System.UInt16), amf0NumberWriter);
amf0Writers.Add(typeof(System.Int32), amf0NumberWriter);
amf0Writers.Add(typeof(System.UInt32), amf0NumberWriter);
amf0Writers.Add(typeof(System.Int64), amf0NumberWriter);
amf0Writers.Add(typeof(System.UInt64), amf0NumberWriter);
amf0Writers.Add(typeof(System.Single), amf0NumberWriter);
amf0Writers.Add(typeof(System.Double), amf0NumberWriter);
amf0Writers.Add(typeof(System.Decimal), amf0NumberWriter);
amf0Writers.Add(typeof(System.DBNull), new AMF0NullWriter());
#if !SILVERLIGHT
AMF0SqlTypesWriter amf0SqlTypesWriter = new AMF0SqlTypesWriter();
amf0Writers.Add(typeof(System.Data.SqlTypes.INullable), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlByte), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlInt16), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlInt32), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlInt64), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlSingle), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlDouble), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlDecimal), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlMoney), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlDateTime), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlString), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlGuid), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlBinary), amf0SqlTypesWriter);
amf0Writers.Add(typeof(System.Data.SqlTypes.SqlBoolean), amf0SqlTypesWriter);
amf0Writers.Add(typeof(CacheableObject), new AMF0CacheableObjectWriter());
amf0Writers.Add(typeof(XmlDocument), new AMF0XmlDocumentWriter());
amf0Writers.Add(typeof(DataTable), new AMF0DataTableWriter());
amf0Writers.Add(typeof(DataSet), new AMF0DataSetWriter());
amf0Writers.Add(typeof(RawBinary), new RawBinaryWriter());
amf0Writers.Add(typeof(System.Collections.Specialized.NameObjectCollectionBase), new AMF0NameObjectCollectionWriter());
#endif
#if !(NET_1_1) && !(NET_2_0)
amf0Writers.Add(typeof(XDocument), new AMF0XDocumentWriter());
amf0Writers.Add(typeof(XElement), new AMF0XElementWriter());
#endif
amf0Writers.Add(typeof(Guid), new AMF0GuidWriter());
amf0Writers.Add(typeof(string), new AMF0StringWriter());
amf0Writers.Add(typeof(bool), new AMF0BooleanWriter());
amf0Writers.Add(typeof(Enum), new AMF0EnumWriter());
amf0Writers.Add(typeof(Char), new AMF0CharWriter());
amf0Writers.Add(typeof(DateTime), new AMF0DateTimeWriter());
amf0Writers.Add(typeof(Array), new AMF0ArrayWriter());
amf0Writers.Add(typeof(ASObject), new AMF0ASObjectWriter());
#if !(NET_1_1)
Dictionary<Type, IAMFWriter> amf3Writers = new Dictionary<Type, IAMFWriter>();
#else
Hashtable amf3Writers = new Hashtable();
#endif
AMF3IntWriter amf3IntWriter = new AMF3IntWriter();
AMF3DoubleWriter amf3DoubleWriter = new AMF3DoubleWriter();
amf3Writers.Add(typeof(System.SByte), amf3IntWriter);
amf3Writers.Add(typeof(System.Byte), amf3IntWriter);
amf3Writers.Add(typeof(System.Int16), amf3IntWriter);
amf3Writers.Add(typeof(System.UInt16), amf3IntWriter);
amf3Writers.Add(typeof(System.Int32), amf3IntWriter);
amf3Writers.Add(typeof(System.UInt32), amf3IntWriter);
amf3Writers.Add(typeof(System.Int64), amf3DoubleWriter);
amf3Writers.Add(typeof(System.UInt64), amf3DoubleWriter);
amf3Writers.Add(typeof(System.Single), amf3DoubleWriter);
amf3Writers.Add(typeof(System.Double), amf3DoubleWriter);
amf3Writers.Add(typeof(System.Decimal), amf3DoubleWriter);
amf3Writers.Add(typeof(System.DBNull), new AMF3DBNullWriter());
#if !SILVERLIGHT
AMF3SqlTypesWriter amf3SqlTypesWriter = new AMF3SqlTypesWriter();
amf3Writers.Add(typeof(System.Data.SqlTypes.INullable), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlByte), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlInt16), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlInt32), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlInt64), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlSingle), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlDouble), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlDecimal), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlMoney), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlDateTime), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlString), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlGuid), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlBinary), amf3SqlTypesWriter);
amf3Writers.Add(typeof(System.Data.SqlTypes.SqlBoolean), amf3SqlTypesWriter);
amf3Writers.Add(typeof(CacheableObject), new AMF3CacheableObjectWriter());
amf3Writers.Add(typeof(XmlDocument), new AMF3XmlDocumentWriter());
amf3Writers.Add(typeof(DataTable), new AMF3DataTableWriter());
amf3Writers.Add(typeof(DataSet), new AMF3DataSetWriter());
amf3Writers.Add(typeof(RawBinary), new RawBinaryWriter());
amf3Writers.Add(typeof(System.Collections.Specialized.NameObjectCollectionBase), new AMF3NameObjectCollectionWriter());
#endif
#if !(NET_1_1) && !(NET_2_0)
amf3Writers.Add(typeof(XDocument), new AMF3XDocumentWriter());
amf3Writers.Add(typeof(XElement), new AMF3XElementWriter());
#endif
amf3Writers.Add(typeof(Guid), new AMF3GuidWriter());
amf3Writers.Add(typeof(string), new AMF3StringWriter());
amf3Writers.Add(typeof(bool), new AMF3BooleanWriter());
amf3Writers.Add(typeof(Enum), new AMF3EnumWriter());
amf3Writers.Add(typeof(Char), new AMF3CharWriter());
amf3Writers.Add(typeof(DateTime), new AMF3DateTimeWriter());
amf3Writers.Add(typeof(Array), new AMF3ArrayWriter());
amf3Writers.Add(typeof(ASObject), new AMF3ASObjectWriter());
amf3Writers.Add(typeof(ByteArray), new AMF3ByteArrayWriter());
amf3Writers.Add(typeof(byte[]), new AMF3ByteArrayWriter());
//amf3Writers.Add(typeof(List<int>), new AMF3IntVectorWriter());
//amf3Writers.Add(typeof(IList<int>), new AMF3IntVectorWriter());
#if !(NET_1_1)
AmfWriterTable = new Dictionary<Type, IAMFWriter>[4] { amf0Writers, null, null, amf3Writers };
classDefinitions = new CopyOnWriteDictionary<string,ClassDefinition>();
#else
AmfWriterTable = new Hashtable[4]{amf0Writers, null, null, amf3Writers};
classDefinitions = new CopyOnWriteDictionary();
#endif
}
/// <summary>
/// Initializes a new instance of the AMFReader class based on the supplied stream and using UTF8Encoding.
/// </summary>
/// <param name="stream"></param>
public AMFWriter(Stream stream) : base(stream)
{
Reset();
}
internal AMFWriter(AMFWriter writer, Stream stream)
: base(stream)
{
_amf0ObjectReferences = writer._amf0ObjectReferences;
_objectReferences = writer._objectReferences;
_stringReferences = writer._stringReferences;
_classDefinitionReferences = writer._classDefinitionReferences;
_useLegacyCollection = writer._useLegacyCollection;
}
/// <summary>
/// Resets object references.
/// </summary>
public void Reset()
{
#if !(NET_1_1)
_amf0ObjectReferences = new Dictionary<Object, int>(5);
_objectReferences = new Dictionary<Object, int>(5);
_stringReferences = new Dictionary<Object, int>(5);
_classDefinitionReferences = new Dictionary<ClassDefinition, int>();
#else
_amf0ObjectReferences = new Hashtable(5);
_objectReferences = new Hashtable(5);
_stringReferences = new Hashtable(5);
_classDefinitionReferences = new Hashtable();
#endif
}
/// <summary>
/// Gets or sets whether legacy collection serialization is used for AMF3.
/// </summary>
public bool UseLegacyCollection
{
get{ return _useLegacyCollection; }
set{ _useLegacyCollection = value; }
}
/// <summary>
/// Gets or sets whether legacy exception serialization is used for AMF3.
/// </summary>
public bool UseLegacyThrowable
{
get { return _useLegacyThrowable; }
set { _useLegacyThrowable = value; }
}
/// <summary>
/// Writes a byte to the current position in the AMF stream.
/// </summary>
/// <param name="value">A byte to write to the stream.</param>
public void WriteByte(byte value)
{
this.BaseStream.WriteByte(value);
}
/// <summary>
/// Writes a stream of bytes to the current position in the AMF stream.
/// </summary>
/// <param name="buffer">The memory buffer containing the bytes to write to the AMF stream</param>
public void WriteBytes(byte[] buffer)
{
for(int i = 0; buffer != null && i < buffer.Length; i++)
this.BaseStream.WriteByte(buffer[i]);
}
/// <summary>
/// Writes a 16-bit unsigned integer to the current position in the AMF stream.
/// </summary>
/// <param name="value">A 16-bit unsigned integer.</param>
public void WriteShort(int value)
{
byte[] bytes = BitConverter.GetBytes((ushort)value);
WriteBigEndian(bytes);
}
/// <summary>
/// Writes an UTF-8 string to the current position in the AMF stream.
/// </summary>
/// <param name="value">The UTF-8 string.</param>
/// <remarks>Standard or long string header is written depending on the string length.</remarks>
public void WriteString(string value)
{
UTF8Encoding utf8Encoding = new UTF8Encoding(true, true);
int byteCount = utf8Encoding.GetByteCount(value);
if( byteCount < 65536 )
{
WriteByte(AMF0TypeCode.String);
WriteUTF(value);
}
else
{
WriteByte(AMF0TypeCode.LongString);
WriteLongUTF(value);
}
}
/// <summary>
/// Writes a UTF-8 string to the current position in the AMF stream.
/// The length of the UTF-8 string in bytes is written first, as a 16-bit integer, followed by the bytes representing the characters of the string.
/// </summary>
/// <param name="value">The UTF-8 string.</param>
/// <remarks>Standard or long string header is not written.</remarks>
public void WriteUTF(string value)
{
//null string is not accepted
//in case of custom serialization leads to TypeError: Error #2007: Parameter value must be non-null. at flash.utils::ObjectOutput/writeUTF()
//Length - max 65536.
UTF8Encoding utf8Encoding = new UTF8Encoding();
int byteCount = utf8Encoding.GetByteCount(value);
byte[] buffer = utf8Encoding.GetBytes(value);
this.WriteShort(byteCount);
if (buffer.Length > 0)
base.Write(buffer);
}
/// <summary>
/// Writes a UTF-8 string to the current position in the AMF stream.
/// Similar to WriteUTF, but does not prefix the string with a 16-bit length word.
/// </summary>
/// <param name="value">The UTF-8 string.</param>
/// <remarks>Standard or long string header is not written.</remarks>
public void WriteUTFBytes(string value)
{
//Length - max 65536.
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] buffer = utf8Encoding.GetBytes(value);
if (buffer.Length > 0)
base.Write(buffer);
}
private void WriteLongUTF(string value)
{
UTF8Encoding utf8Encoding = new UTF8Encoding(true, true);
uint byteCount = (uint)utf8Encoding.GetByteCount(value);
byte[] buffer = new Byte[byteCount+4];
//unsigned long (always 32 bit, big endian byte order)
buffer[0] = (byte)((byteCount >> 0x18) & 0xff);
buffer[1] = (byte)((byteCount >> 0x10) & 0xff);
buffer[2] = (byte)((byteCount >> 8) & 0xff);
buffer[3] = (byte)((byteCount & 0xff));
int bytesEncodedCount = utf8Encoding.GetBytes(value, 0, value.Length, buffer, 4);
if (buffer.Length > 0)
base.BaseStream.Write(buffer, 0, buffer.Length);
}
/// <summary>
/// Serializes object graphs in Action Message Format (AMF).
/// </summary>
/// <param name="objectEncoding">AMF version to use.</param>
/// <param name="data">The Object to serialize in the AMF stream.</param>
public void WriteData(ObjectEncoding objectEncoding, object data)
{
//If we have ObjectEncoding.AMF3 anything that serializes to String, Number, Boolean, Date will use AMF0 encoding
//For other types we have to switch the encoding to AMF3
if( data == null )
{
WriteNull();
return;
}
Type type = data.GetType();
if (FluorineConfiguration.Instance.AcceptNullValueTypes && FluorineConfiguration.Instance.NullableValues != null)
{
if( FluorineConfiguration.Instance.NullableValues.ContainsKey(type) && data.Equals(FluorineConfiguration.Instance.NullableValues[type]) )
{
WriteNull();
return;
}
}
if( _amf0ObjectReferences.ContainsKey( data ) )
{
WriteReference( data );
return;
}
IAMFWriter amfWriter = null;
if( AmfWriterTable[0].ContainsKey(type) )
amfWriter = AmfWriterTable[0][type] as IAMFWriter;
//Second try with basetype (enums and arrays for example)
if (amfWriter == null && type.BaseType != null && AmfWriterTable[0].ContainsKey(type.BaseType))
amfWriter = AmfWriterTable[0][type.BaseType] as IAMFWriter;
if( amfWriter == null )
{
lock(AmfWriterTable)
{
if (!AmfWriterTable[0].ContainsKey(type))
{
amfWriter = new AMF0ObjectWriter();
AmfWriterTable[0].Add(type, amfWriter);
}
else
amfWriter = AmfWriterTable[0][type] as IAMFWriter;
}
}
if( amfWriter != null )
{
if( objectEncoding == ObjectEncoding.AMF0 )
amfWriter.WriteData(this, data);
else
{
if( amfWriter.IsPrimitive )
amfWriter.WriteData(this, data);
else
{
WriteByte(AMF0TypeCode.AMF3Tag);
WriteAMF3Data(data);
}
}
}
else
{
string msg = __Res.GetString(__Res.TypeSerializer_NotFound, type.FullName);
throw new FluorineException(msg);
}
}
internal void AddReference(object value)
{
_amf0ObjectReferences.Add( value, _amf0ObjectReferences.Count);
}
internal void WriteReference(object value)
{
//Circular references
WriteByte(AMF0TypeCode.Reference);
WriteShort((int)_amf0ObjectReferences[value]);
}
/// <summary>
/// Writes a null type marker to the current position in the AMF stream.
/// </summary>
public void WriteNull()
{
WriteByte(AMF0TypeCode.Null);
}
/// <summary>
/// Writes a double-precision floating point number to the current position in the AMF stream.
/// </summary>
/// <param name="value">A double-precision floating point number.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteDouble(double value)
{
byte[] bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
/// <summary>
/// Writes a single-precision floating point number to the current position in the AMF stream.
/// </summary>
/// <param name="value">A double-precision floating point number.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteFloat(float value)
{
byte[] bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
/// <summary>
/// Writes a 32-bit signed integer to the current position in the AMF stream.
/// </summary>
/// <param name="value">A 32-bit signed integer.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteInt32(int value)
{
byte[] bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
/// <summary>
/// Writes a 32-bit signed integer to the current position in the AMF stream using variable length unsigned 29-bit integer encoding.
/// </summary>
/// <param name="value">A 32-bit signed integer.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteUInt24(int value)
{
byte[] bytes = new byte[3];
bytes[0] = (byte)(0xFF & (value >> 16));
bytes[1] = (byte)(0xFF & (value >> 8));
bytes[2] = (byte)(0xFF & (value >> 0));
this.BaseStream.Write(bytes, 0, bytes.Length);
}
/// <summary>
/// Writes a Boolean value to the current position in the AMF stream.
/// </summary>
/// <param name="value">A Boolean value.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteBoolean(bool value)
{
this.BaseStream.WriteByte(value ? ((byte)1) : ((byte)0));
}
/// <summary>
/// Writes a 64-bit signed integer to the current position in the AMF stream.
/// </summary>
/// <param name="value">A 64-bit signed integer.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteLong(long value)
{
byte[] bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
private void WriteBigEndian(byte[] bytes)
{
if( bytes == null )
return;
for(int i = bytes.Length-1; i >= 0; i--)
{
base.BaseStream.WriteByte( bytes[i] );
}
}
/// <summary>
/// Writes a DateTime value to the current position in the AMF stream.
/// An ActionScript Date is serialized as the number of milliseconds elapsed since the epoch of midnight on 1st Jan 1970 in the UTC time zone.
/// </summary>
/// <param name="value">A DateTime value.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteDateTime(DateTime value)
{
/*
#if !SILVERLIGHT
if( FluorineConfiguration.Instance.TimezoneCompensation == TimezoneCompensation.Auto )
date = date.Subtract( DateWrapper.ClientTimeZone );
#endif
*/
#if !(NET_1_1)
switch (FluorineConfiguration.Instance.TimezoneCompensation)
{
case TimezoneCompensation.IgnoreUTCKind:
//Do not convert to UTC, consider we have it in universal time
break;
default:
#if !(NET_1_1)
value = value.ToUniversalTime();
#endif
break;
}
#else
if( FluorineConfiguration.Instance.TimezoneCompensation == TimezoneCompensation.Auto )
value = value.Subtract( DateWrapper.ClientTimeZone );
#endif
// Write date (milliseconds from 1970).
DateTime timeStart = new DateTime(1970, 1, 1);
TimeSpan span = value.Subtract(timeStart);
long milliSeconds = (long)span.TotalMilliseconds;
WriteDouble((double)milliSeconds);
#if !SILVERLIGHT
span = TimeZone.CurrentTimeZone.GetUtcOffset(value);
//whatever we write back, it is ignored
//this.WriteLong(span.TotalMinutes);
//this.WriteShort((int)span.TotalHours);
//this.WriteShort(65236);
if( FluorineConfiguration.Instance.TimezoneCompensation == TimezoneCompensation.None )
this.WriteShort(0);
else
this.WriteShort((int)(span.TotalMilliseconds/60000));
#else
this.WriteShort(0);
#endif
}
#if !SILVERLIGHT
/// <summary>
/// Writes an XmlDocument object to the current position in the AMF stream.
/// </summary>
/// <param name="value">An XmlDocument object.</param>
/// <remarks>Xml type marker is written in the AMF stream.</remarks>
public void WriteXmlDocument(XmlDocument value)
{
if (value != null)
{
AddReference(value);
this.BaseStream.WriteByte(AMF0TypeCode.Xml);
string xml = value.DocumentElement.OuterXml;
this.WriteLongUTF(xml);
}
else
this.WriteNull();
}
#endif
#if !(NET_1_1) && !(NET_2_0)
public void WriteXDocument(XDocument xDocument)
{
if (xDocument != null)
{
AddReference(xDocument);
this.BaseStream.WriteByte((byte)15);//xml code (0x0F)
string xml = xDocument.ToString();
this.WriteLongUTF(xml);
}
else
this.WriteNull();
}
public void WriteXElement(XElement xElement)
{
if (xElement != null)
{
AddReference(xElement);
this.BaseStream.WriteByte((byte)15);//xml code (0x0F)
string xml = xElement.ToString();
this.WriteLongUTF(xml);
}
else
this.WriteNull();
}
#endif
/// <summary>
/// Writes an Array value to the current position in the AMF stream.
/// </summary>
/// <param name="objectEcoding">Object encoding used.</param>
/// <param name="value">An Array object.</param>
public void WriteArray(ObjectEncoding objectEcoding, Array value)
{
if (value == null)
this.WriteNull();
else
{
AddReference(value);
WriteByte(AMF0TypeCode.Array);
WriteInt32(value.Length);
for (int i = 0; i < value.Length; i++)
{
WriteData(objectEcoding, value.GetValue(i));
}
}
}
/// <summary>
/// Writes an associative array to the current position in the AMF stream.
/// </summary>
/// <param name="objectEncoding">Object encoding used.</param>
/// <param name="value">An Dictionary object.</param>
public void WriteAssociativeArray(ObjectEncoding objectEncoding, IDictionary value)
{
if (value == null)
this.WriteNull();
else
{
AddReference(value);
WriteByte(AMF0TypeCode.AssociativeArray);
WriteInt32(value.Count);
foreach (DictionaryEntry entry in value)
{
this.WriteUTF(entry.Key.ToString());
this.WriteData(objectEncoding, entry.Value);
}
this.WriteEndMarkup();
}
}
/// <summary>
/// Writes an object to the current position in the AMF stream.
/// </summary>
/// <param name="objectEncoding">Object encoding used.</param>
/// <param name="obj">The object to serialize.</param>
public void WriteObject(ObjectEncoding objectEncoding, object obj)
{
if( obj == null )
{
WriteNull();
return;
}
AddReference(obj);
Type type = obj.GetType();
WriteByte(16);
string customClass = type.FullName;
customClass = FluorineConfiguration.Instance.GetCustomClass(customClass);
#if !SILVERLIGHT
if( log.IsDebugEnabled )
log.Debug(__Res.GetString(__Res.TypeMapping_Write, type.FullName, customClass));
#endif
WriteUTF( customClass );
ClassDefinition classDefinition = GetClassDefinition(obj);
if (classDefinition == null)
{
//Something went wrong in our reflection?
string msg = __Res.GetString(__Res.Fluorine_Fatal, "serializing " + obj.GetType().FullName);
#if !SILVERLIGHT
if (log.IsFatalEnabled)
log.Fatal(msg);
#endif
System.Diagnostics.Debug.Assert(false, msg);
return;
}
IObjectProxy proxy = ObjectProxyRegistry.Instance.GetObjectProxy(type);
for (int i = 0; i < classDefinition.MemberCount; i++)
{
ClassMember cm = classDefinition.Members[i];
WriteUTF(cm.Name);
object memberValue = proxy.GetValue(obj, cm);
WriteData(objectEncoding, memberValue);
}
WriteEndMarkup();
}
internal void WriteEndMarkup()
{
//Write the end object flag 0x00, 0x00, 0x09
base.BaseStream.WriteByte(0);
base.BaseStream.WriteByte(0);
base.BaseStream.WriteByte(AMF0TypeCode.EndOfObject);
}
/// <summary>
/// Writes an anonymous ActionScript object to the current position in the AMF stream.
/// </summary>
/// <param name="objectEncoding">Object encoding to use.</param>
/// <param name="asObject">The ActionScript object.</param>
public void WriteASO(ObjectEncoding objectEncoding, ASObject asObject)
{
if( asObject != null )
{
AddReference(asObject);
if(asObject.TypeName == null)
{
// Object "Object"
this.BaseStream.WriteByte(3);
}
else
{
this.BaseStream.WriteByte(16);
this.WriteUTF(asObject.TypeName);
}
#if !(NET_1_1)
foreach (KeyValuePair<string, object> entry in asObject)
#else
foreach(DictionaryEntry entry in asObject)
#endif
{
this.WriteUTF(entry.Key.ToString());
this.WriteData(objectEncoding, entry.Value);
}
WriteEndMarkup();
}
else
WriteNull();
}
#region AMF3
/// <summary>
/// Serializes object graphs in Action Message Format (AMF).
/// </summary>
/// <param name="data">The Object to serialize in the AMF stream.</param>
public void WriteAMF3Data(object data)
{
if( data == null )
{
WriteAMF3Null();
return;
}
if(data is DBNull )
{
WriteAMF3Null();
return;
}
Type type = data.GetType();
if (FluorineConfiguration.Instance.AcceptNullValueTypes && FluorineConfiguration.Instance.NullableValues != null)
{
if( FluorineConfiguration.Instance.NullableValues.ContainsKey(type) && data.Equals(FluorineConfiguration.Instance.NullableValues[type]) )
{
WriteAMF3Null();
return;
}
}
IAMFWriter amfWriter = null;
if (AmfWriterTable[3].ContainsKey(type))
amfWriter = AmfWriterTable[3][type] as IAMFWriter;
//Second try with basetype (Enums for example)
if (amfWriter == null && type.BaseType != null && AmfWriterTable[3].ContainsKey(type.BaseType))
amfWriter = AmfWriterTable[3][type.BaseType] as IAMFWriter;
if( amfWriter == null )
{
lock(AmfWriterTable)
{
if (!AmfWriterTable[3].ContainsKey(type))
{
amfWriter = new AMF3ObjectWriter();
AmfWriterTable[3].Add(type, amfWriter);
}
else
amfWriter = AmfWriterTable[3][type] as IAMFWriter;
}
}
if( amfWriter != null )
{
amfWriter.WriteData(this, data);
}
else
{
string msg = string.Format("Could not find serializer for type {0}", type.FullName);
throw new FluorineException(msg);
}
//WriteByte(AMF3TypeCode.Object);
//WriteAMF3Object(data);
}
/// <summary>
/// Writes a null type marker to the current position in the AMF stream.
/// </summary>
public void WriteAMF3Null()
{
//Write the null code (0x1) to the output stream.
WriteByte(AMF3TypeCode.Null);
}
/// <summary>
/// Writes a Boolean value to the current position in the AMF stream.
/// </summary>
/// <param name="value">A Boolean value.</param>
public void WriteAMF3Bool(bool value)
{
WriteByte( (byte)(value ? AMF3TypeCode.BooleanTrue : AMF3TypeCode.BooleanFalse));
}
/// <summary>
/// Writes an Array value to the current position in the AMF stream.
/// </summary>
/// <param name="value">An Array object.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteAMF3Array(Array value)
{
if (_amf0ObjectReferences.ContainsKey(value))
{
WriteReference(value);
return;
}
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
int handle = value.Length;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
WriteAMF3UTF(string.Empty);//hash name
for (int i = 0; i < value.Length; i++)
{
WriteAMF3Data(value.GetValue(i));
}
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
/// <summary>
/// Writes an Array value to the current position in the AMF stream.
/// </summary>
/// <param name="value">An Array object.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteAMF3Array(IList value)
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
int handle = value.Count;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
WriteAMF3UTF(string.Empty);//hash name
for(int i = 0; i < value.Count; i++)
{
WriteAMF3Data(value[i]);
}
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
/// <summary>
/// Writes an associative array to the current position in the AMF stream.
/// </summary>
/// <param name="value">An Dictionary object.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteAMF3AssociativeArray(IDictionary value)
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
WriteAMF3IntegerData(1);
foreach(DictionaryEntry entry in value)
{
WriteAMF3UTF(entry.Key.ToString());
WriteAMF3Data(entry.Value);
}
WriteAMF3UTF(string.Empty);
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
internal void WriteByteArray(ByteArray byteArray)
{
_objectReferences.Add(byteArray, _objectReferences.Count);
WriteByte(AMF3TypeCode.ByteArray);
int handle = (int)byteArray.Length;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
WriteBytes( byteArray.MemoryStream.ToArray() );
}
[CLSCompliant(false)]
public void WriteAMF3IntVector(IList<int> value)
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
int handle = value.Count;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
WriteAMF3IntegerData(value.IsReadOnly ? 1 : 0);
for (int i = 0; i < value.Count; i++)
{
WriteInt32(value[i]);
}
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
[CLSCompliant(false)]
public void WriteAMF3UIntVector(IList<uint> value)
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
int handle = value.Count;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
WriteAMF3IntegerData(value.IsReadOnly ? 1 : 0);
for (int i = 0; i < value.Count; i++)
{
WriteInt32((int)value[i]);
}
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
[CLSCompliant(false)]
public void WriteAMF3DoubleVector(IList<double> value)
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
int handle = value.Count;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
WriteAMF3IntegerData(value.IsReadOnly ? 1 : 0);
for (int i = 0; i < value.Count; i++)
{
WriteDouble(value[i]);
}
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
[CLSCompliant(false)]
public void WriteAMF3ObjectVector(IList<string> value)
{
WriteAMF3ObjectVector(string.Empty, value as IList);
}
[CLSCompliant(false)]
public void WriteAMF3ObjectVector(IList<Boolean> value)
{
WriteAMF3ObjectVector(string.Empty, value as IList);
}
[CLSCompliant(false)]
public void WriteAMF3ObjectVector(IList value)
{
Type listItemType = ReflectionUtils.GetListItemType(value.GetType());
WriteAMF3ObjectVector(listItemType.FullName, value);
}
private void WriteAMF3ObjectVector(string typeIdentifier, IList value)
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
int handle = value.Count;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
WriteAMF3IntegerData(value.IsReadOnly ? 1 : 0);
WriteAMF3String(typeIdentifier);
for (int i = 0; i < value.Count; i++)
{
WriteAMF3Data(value[i]);
}
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
/// <summary>
/// Writes a UTF-8 string to the current position in the AMF stream.
/// </summary>
/// <param name="value">The UTF-8 string.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteAMF3UTF(string value)
{
if( value == string.Empty )
{
WriteAMF3IntegerData(1);
}
else
{
if (!_stringReferences.ContainsKey(value))
{
_stringReferences.Add(value, _stringReferences.Count);
UTF8Encoding utf8Encoding = new UTF8Encoding();
int byteCount = utf8Encoding.GetByteCount(value);
int handle = byteCount;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
byte[] buffer = utf8Encoding.GetBytes(value);
if (buffer.Length > 0)
Write(buffer);
}
else
{
int handle = (int)_stringReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
}
/// <summary>
/// Writes an UTF-8 string to the current position in the AMF stream.
/// </summary>
/// <param name="value">The UTF-8 string.</param>
public void WriteAMF3String(string value)
{
WriteByte(AMF3TypeCode.String);
WriteAMF3UTF(value);
}
/// <summary>
/// Writes a DateTime value to the current position in the AMF stream.
/// An ActionScript Date is serialized as the number of milliseconds elapsed since the epoch of midnight on 1st Jan 1970 in the UTC time zone.
/// Local time zone information is not sent.
/// </summary>
/// <param name="value">A DateTime value.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteAMF3DateTime(DateTime value)
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
int handle = 1;
WriteAMF3IntegerData(handle);
// Write date (milliseconds from 1970).
DateTime timeStart = new DateTime(1970, 1, 1, 0, 0, 0);
switch (FluorineConfiguration.Instance.TimezoneCompensation)
{
case TimezoneCompensation.IgnoreUTCKind:
//Do not convert to UTC, consider we have it in universal time
break;
default:
#if !(NET_1_1)
value = value.ToUniversalTime();
#endif
break;
}
TimeSpan span = value.Subtract(timeStart);
long milliSeconds = (long)span.TotalMilliseconds;
//long date = BitConverter.DoubleToInt64Bits((double)milliSeconds);
//this.WriteLong(date);
WriteDouble((double)milliSeconds);
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
private void WriteAMF3IntegerData(int value)
{
//Sign contraction - the high order bit of the resulting value must match every bit removed from the number
//Clear 3 bits
value &= 0x1fffffff;
if(value < 0x80)
this.WriteByte((byte)value);
else
if(value < 0x4000)
{
this.WriteByte((byte)(value >> 7 & 0x7f | 0x80));
this.WriteByte((byte)(value & 0x7f));
}
else
if(value < 0x200000)
{
this.WriteByte((byte)(value >> 14 & 0x7f | 0x80));
this.WriteByte((byte)(value >> 7 & 0x7f | 0x80));
this.WriteByte((byte)(value & 0x7f));
}
else
{
this.WriteByte((byte)(value >> 22 & 0x7f | 0x80));
this.WriteByte((byte)(value >> 15 & 0x7f | 0x80));
this.WriteByte((byte)(value >> 8 & 0x7f | 0x80));
this.WriteByte((byte)(value & 0xff));
}
}
/// <summary>
/// Writes a 32-bit signed integer to the current position in the AMF stream.
/// </summary>
/// <param name="value">A 32-bit signed integer.</param>
/// <remarks>Type marker is written in the AMF stream.</remarks>
public void WriteAMF3Int(int value)
{
if(value >= -268435456 && value <= 268435455)//check valid range for 29bits
{
WriteByte(AMF3TypeCode.Integer);
WriteAMF3IntegerData(value);
}
else
{
//overflow condition would occur upon int conversion
WriteAMF3Double((double)value);
}
}
/// <summary>
/// Writes a double-precision floating point number to the current position in the AMF stream.
/// </summary>
/// <param name="value">A double-precision floating point number.</param>
/// <remarks>Type marker is written in the AMF stream.</remarks>
public void WriteAMF3Double(double value)
{
WriteByte(AMF3TypeCode.Number);
//long tmp = BitConverter.DoubleToInt64Bits( double.Parse(value.ToString()) );
WriteDouble(value);
}
#if !SILVERLIGHT
/// <summary>
/// Writes an XmlDocument object to the current position in the AMF stream.
/// </summary>
/// <param name="value">An XmlDocument object.</param>
/// <remarks>Xml type marker is written in the AMF stream.</remarks>
public void WriteAMF3XmlDocument(XmlDocument value)
{
WriteByte(AMF3TypeCode.Xml);
string xml = string.Empty;
if (value.DocumentElement != null && value.DocumentElement.OuterXml != null)
xml = value.DocumentElement.OuterXml;
if (xml == string.Empty)
{
WriteAMF3IntegerData(1);
}
else
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
UTF8Encoding utf8Encoding = new UTF8Encoding();
int byteCount = utf8Encoding.GetByteCount(xml);
int handle = byteCount;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
byte[] buffer = utf8Encoding.GetBytes(xml);
if (buffer.Length > 0)
Write(buffer);
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
}
#endif
#if !(NET_1_1) && !(NET_2_0)
public void WriteAMF3XDocument(XDocument xDocument)
{
WriteByte(AMF3TypeCode.Xml);
string value = string.Empty;
if (xDocument != null)
value = xDocument.ToString();
if (value == string.Empty)
{
WriteAMF3IntegerData(1);
}
else
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
UTF8Encoding utf8Encoding = new UTF8Encoding();
int byteCount = utf8Encoding.GetByteCount(value);
int handle = byteCount;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
byte[] buffer = utf8Encoding.GetBytes(value);
if (buffer.Length > 0)
Write(buffer);
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
}
public void WriteAMF3XElement(XElement xElement)
{
WriteByte(AMF3TypeCode.Xml);
string value = string.Empty;
if (xElement != null)
value = xElement.ToString();
if (value == string.Empty)
{
WriteAMF3IntegerData(1);
}
else
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
UTF8Encoding utf8Encoding = new UTF8Encoding();
int byteCount = utf8Encoding.GetByteCount(value);
int handle = byteCount;
handle = handle << 1;
handle = handle | 1;
WriteAMF3IntegerData(handle);
byte[] buffer = utf8Encoding.GetBytes(value);
if (buffer.Length > 0)
Write(buffer);
}
else
{
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
}
#endif
/// <summary>
/// Writes an object to the current position in the AMF stream.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <remarks>No type marker is written in the AMF stream.</remarks>
public void WriteAMF3Object(object value)
{
if (!_objectReferences.ContainsKey(value))
{
_objectReferences.Add(value, _objectReferences.Count);
ClassDefinition classDefinition = GetClassDefinition(value);
if (classDefinition == null)
{
//Something went wrong in our reflection?
string msg = __Res.GetString(__Res.Fluorine_Fatal, "serializing " + value.GetType().FullName);
#if !SILVERLIGHT
if (log.IsFatalEnabled)
log.Fatal(msg);
#endif
System.Diagnostics.Debug.Assert(false, msg);
return;
}
if (_classDefinitionReferences.ContainsKey(classDefinition))
{
//Existing class-def
int handle = (int)_classDefinitionReferences[classDefinition];//handle = classRef 0 1
handle = handle << 2;
handle = handle | 1;
WriteAMF3IntegerData(handle);
}
else
{//inline class-def
//classDefinition = CreateClassDefinition(value);
_classDefinitionReferences.Add(classDefinition, _classDefinitionReferences.Count);
//handle = memberCount dynamic externalizable 1 1
int handle = classDefinition.MemberCount;
handle = handle << 1;
handle = handle | (classDefinition.IsDynamic ? 1 : 0);
handle = handle << 1;
handle = handle | (classDefinition.IsExternalizable ? 1 : 0);
handle = handle << 2;
handle = handle | 3;
WriteAMF3IntegerData(handle);
WriteAMF3UTF(classDefinition.ClassName);
for(int i = 0; i < classDefinition.MemberCount; i++)
{
string key = classDefinition.Members[i].Name;
WriteAMF3UTF(key);
}
}
//write inline object
if( classDefinition.IsExternalizable )
{
if( value is IExternalizable )
{
IExternalizable externalizable = value as IExternalizable;
DataOutput dataOutput = new DataOutput(this);
externalizable.WriteExternal(dataOutput);
}
else
throw new FluorineException(__Res.GetString(__Res.Externalizable_CastFail,classDefinition.ClassName));
}
else
{
Type type = value.GetType();
IObjectProxy proxy = ObjectProxyRegistry.Instance.GetObjectProxy(type);
for(int i = 0; i < classDefinition.MemberCount; i++)
{
//object memberValue = GetMember(value, classDefinition.Members[i]);
object memberValue = proxy.GetValue(value, classDefinition.Members[i]);
WriteAMF3Data(memberValue);
}
if(classDefinition.IsDynamic)
{
IDictionary dictionary = value as IDictionary;
foreach(DictionaryEntry entry in dictionary)
{
WriteAMF3UTF(entry.Key.ToString());
WriteAMF3Data(entry.Value);
}
WriteAMF3UTF(string.Empty);
}
}
}
else
{
//handle = objectRef 0
int handle = (int)_objectReferences[value];
handle = handle << 1;
WriteAMF3IntegerData(handle);
}
}
private ClassDefinition GetClassDefinition(object obj)
{
ClassDefinition classDefinition = null;
if (obj is ASObject)
{
ASObject asObject = obj as ASObject;
if (asObject.IsTypedObject)
classDefinitions.TryGetValue(asObject.TypeName, out classDefinition);
if (classDefinition != null)
return classDefinition;
IObjectProxy proxy = ObjectProxyRegistry.Instance.GetObjectProxy(typeof(ASObject));
classDefinition = proxy.GetClassDefinition(obj);
if (asObject.IsTypedObject)
{
//Only typed ASObject class definitions are cached.
classDefinitions[asObject.TypeName] = classDefinition;
}
return classDefinition;
}
else
{
string typeName = obj.GetType().FullName;
if( !classDefinitions.TryGetValue(typeName, out classDefinition))
{
IObjectProxy proxy = ObjectProxyRegistry.Instance.GetObjectProxy(obj.GetType());
classDefinition = proxy.GetClassDefinition(obj);
classDefinitions[typeName] = classDefinition;
}
return classDefinition;
}
}
#endregion AMF3
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using SimpleJSON;
using UnityEngine;
[Serializable]
public class DCity : ITurnUpdatable
{
[NonSerialized]
private DGame dGame;
private CityController cityController;
private Dictionary<int, DBuilding> buildings = new Dictionary<int, DBuilding>();
private Dictionary<int, DResource> resources = new Dictionary<int, DResource>();
private Dictionary<int, DResource> prevResources = new Dictionary<int, DResource>();
private Dictionary<int, DResource> resourceRates = new Dictionary<int, DResource>();
private Dictionary<int, DPerson> people = new Dictionary<int, DPerson>();
private List<string> linkedCityKeys = new List<string>();
private int age;
private string name;
private int shelterTier;
private int fuelToShelterConversion;
private DResource shelterResource;
private DResource fuelResource;
private float explorationLevel;
public DBuilding townHall;
private DSeasons._season season;
private DateTime[] seasonStartDates = new DateTime[4];
private DateTime[] deadOfWinterStartEnd = new DateTime[2];
private bool isDeadOfWinter = false;
private int turnsOfFoodSurplus = 0;
public static float health = 0.5f;
public static int foodConsumption = 1;
public static float notEnoughFoodHealthDecay = 0.8f;
#region Constructors and Init
public DCity(string cityName, CityController cityController)
{
Init(cityName, cityController, DSeasons.DefaultStartDates(), new DateTime(2017,1,1), DSeasons.DefaultDeadOfWinterDates(), null);
}
public DCity(string cityName, CityController cityController, DateTime currentDate)
{
Init(cityName, cityController, DSeasons.DefaultStartDates(), currentDate, DSeasons.DefaultDeadOfWinterDates(), null);
}
public DCity(string cityName, CityController cityController, DateTime[] seasonDates, DateTime currentDate, List<string> linkedCityKeys = null)
{
Init(cityName, cityController, seasonDates, currentDate, DSeasons.DefaultDeadOfWinterDates(), linkedCityKeys);
}
private void Init(string cityName, CityController cityController, DateTime[] seasonDates, DateTime currentDate,
DateTime[] deadWinterDates, List<string> linkedCityKeys)
{
name = cityName;
this.cityController = cityController;
age = 0;
townHall = null;
explorationLevel = 0.0f;
shelterTier = 1;
fuelToShelterConversion = 0;
InitialLinkedCities(linkedCityKeys);
deadOfWinterStartEnd = deadWinterDates;
seasonStartDates = DSeasons.InitialSeasonSetup(seasonDates, currentDate, ref season, ref deadOfWinterStartEnd);
}
private void InitialLinkedCities(List<string> linkedCityKeys)
{
this.linkedCityKeys = new List<string>();
if (linkedCityKeys != null)
foreach (string cityKey in linkedCityKeys)
this.linkedCityKeys.Add(cityKey);
}
private void InitialDeadOfWinter(DateTime currentDate, DateTime[] deadWinterDates)
{
deadOfWinterStartEnd = deadWinterDates;
if (currentDate < deadOfWinterStartEnd[1] && currentDate >= deadOfWinterStartEnd[0])
isDeadOfWinter = true;
else
isDeadOfWinter = false;
}
#endregion
#region Update Calls
// TurnUpdate is called once per Turn
public void TurnUpdate(int numDaysPassed)
{
// Set shelter resource to zero, cannot accumulate shelter
if(resourceRates.ContainsKey(DResource.NameToID("Food")))
turnsOfFoodSurplus = resourceRates[DResource.NameToID("Food")].Amount >= 1 ? turnsOfFoodSurplus + 1 : 0;
if (turnsOfFoodSurplus == 7)
{
NewPerson();
// DPerson newP = new DPerson(this,null);
// MeepleController meepleController = cityController.gameController.CreateMeepleController(townHall.getIdleTask().GetTaskSlot(townHall.getIdleTask().NumPeople).taskTraySlot, newP);
// newP.SetMeepleController(meepleController);
// people.Add(newP.ID,newP);
turnsOfFoodSurplus = 0;
}
prevResources.Clear();
foreach(var entry in resources)
{
prevResources.Add(entry.Key, DResource.Create(entry.Value));
prevResources[entry.Key].Amount = entry.Value.Amount;
}
if (shelterResource != null)
shelterResource.Amount = 0;
UpdateBuildings(numDaysPassed);
UpdateResources(numDaysPassed);
UpdatePeople(numDaysPassed);
UpdateCity();
if (shelterResource != null)
{
// Shelter calculations
int shelterResourceAmt = shelterResource.Amount;
shelterResourceAmt = shelterResourceAmt - ShelterConsumedPerTurn();
// TODO: Deal with negative shelter amounts
}
if (fuelResource != null)
{
// Check if our fuel consumption is exceeding our current fuel stores
fuelToShelterConversion = fuelToShelterConversion < fuelResource.Amount ? fuelToShelterConversion : fuelResource.Amount;
}
age += numDaysPassed;
}
public void NewPerson()
{
DPerson newP = new DPerson(this, null);
townHall.getIdleTask().AddPerson(newP);
Game.GameController.CreateMeepleController(newP.TaskSlot.TaskTraySlot, newP);
}
// TODO: Account for infection in people
public int ShelterConsumedPerTurn()
{
int amountShelterPerPerson = Mathf.RoundToInt(Mathf.Pow(2.0f, shelterTier - 1));
return amountShelterPerPerson * people.Count;
}
public int ShelterNetTier()
{
return Mathf.Clamp(shelterTier + fuelToShelterConversion, 1, 5);
}
public void UpdateSeason(DateTime currentDate)
{
seasonStartDates = DSeasons.UpdateSeasonStatus(seasonStartDates, currentDate, ref season);
UpdateDeadOfWinter(currentDate);
}
public void UpdateDeadOfWinter(DateTime currentDate)
{
if (!isDeadOfWinter)
isDeadOfWinter = DSeasons.StartDeadOfWinter(ref deadOfWinterStartEnd, currentDate);
else
isDeadOfWinter = !DSeasons.EndDeadOfWinter(ref deadOfWinterStartEnd, currentDate);
}
#region Update Other Elements
private void UpdateBuildings(int numDaysPassed)
{
foreach (var entry in buildings)
{
entry.Value.TurnUpdate(numDaysPassed);
BuildingSeasonalEffects(entry.Value, numDaysPassed);
}
}
private void BuildingSeasonalEffects(DBuilding building, int numDaysPassed)
{
switch (season)
{
case DSeasons._season.SPRING:
building.SpringEffects();
break;
case DSeasons._season.SUMMER:
building.SummerEffects();
break;
case DSeasons._season.FALL:
building.FallEffects();
break;
case DSeasons._season.WINTER:
building.WinterEffects();
break;
}
}
private void UpdateResources(int numDaysPassed)
{
foreach (var entry in resources)
{
entry.Value.TurnUpdate(numDaysPassed);
// Remove fuel due to shelter conversion
if (entry.Value.Name.Equals("Fuel"))
{
entry.Value.Amount -= fuelToShelterConversion;
}
}
CalculateResourceRates();
}
private void UpdatePeople(int numDaysPassed)
{
int exploringInWinter = 0;
List<DPerson> listOfDeadPeople = new List<DPerson>();
foreach (var entry in people.Keys)
{
people[entry].TurnUpdate(numDaysPassed);
UpdatePeopleWinter(people[entry], ref exploringInWinter);
if (people[entry].IsDead)
listOfDeadPeople.Add(people[entry]);
}
// Remove dead people
foreach (var person in listOfDeadPeople)
{
people.Remove(person.ID);
}
if (exploringInWinter > 1)
health = Mathf.Clamp(health - DSeasons.reduceHealthExploringWinter, 0f, 1f);
}
private void UpdatePeopleWinter(DPerson person, ref int exploringInWinter)
{
if (person.Task != null && person.Task.GetType() == typeof(DTask_Explore) && season == DSeasons._season.WINTER)
{
exploringInWinter++;
DeadOfWinterCulling(person);
}
}
public void DeadOfWinterCulling(DPerson person)
{
if (isDeadOfWinter)
{
person.Dies();
}
}
#endregion
public void UpdateCity()
{
UpdateCityFood();
UpdateCityHealth();
}
public void UpdateCityFood()
{
DResource resource = GetResource(Constants.FOOD_RESOURCE_NAME);
// int consumeAmount = (int)(foodConsumption * DSeasons.modFoodConsumption[(int)season]);
//TODO: why is this always 1?!
int consumeAmount = foodConsumption * people.Count;
if (resource.Amount >= consumeAmount)
ConsumeResource(resource, consumeAmount);
else
{
ConsumeResource(resource);
NotEnoughFood(consumeAmount - resource.Amount);
}
}
public void NotEnoughFood(int deficit)
{
health *= notEnoughFoodHealthDecay;
}
public void UpdateCityHealth()
{
}
#endregion
#region Basics
public void AddBuilding(DBuilding dBuilding)
{
if (buildings.ContainsKey(dBuilding.ID))
{
throw new BuildingAlreadyAddedException(string.Format("City '{0}' already has building '{1}'", name, dBuilding.Name));
}
else
{
buildings.Add(dBuilding.ID, dBuilding);
if (dBuilding.Name.Equals("Town Hall"))
townHall = dBuilding;
}
}
public void AddPerson(DPerson dPerson)
{
if (people.ContainsKey(dPerson.ID))
{
throw new PersonAlreadyAddedException(string.Format("Person already added to city"));
}
people.Add(dPerson.ID, dPerson);
}
public void AddResource(DResource resource)
{
int amount = (int)(resource.Amount * SeasonResourceProduceMod(resource));
AddResource(resource, amount);
if (resource.Name.Equals("Shelter"))
shelterResource = resources[resource.ID];
else if (resource.Name.Equals("Fuel"))
fuelResource = resources[resource.ID];
}
public void AddResource(DResource resource, int amount)
{
if (resources.ContainsKey(resource.ID))
{
resources[resource.ID].Amount += (int)(amount * SeasonResourceProduceMod(resource));
}
else
{
resources.Add(resource.ID, DResource.Create(resource, amount));
}
if (resource.Name.Equals("Shelter"))
shelterResource = resources[resource.ID];
else if (resource.Name.Equals("Fuel"))
fuelResource = resources[resource.ID];
}
public void TakeResource(DResource resource)
{
if (resources.ContainsKey(resource.ID))
{
resources[resource.ID].Amount -= resource.Amount;
}
else
{
throw new ResourceNameNotFoundException(resource.Name);
}
}
// todo - as resources are defined with constant names, include if checks here
public float SeasonResourceProduceMod(DResource resource)
{
if (resource.Name == Constants.FOOD_RESOURCE_NAME)
return DSeasons.modFoodProduction[(int)season];
return 1f;
}
public void ConsumeResource(DResource resource, int amount)
{
if (resources.ContainsKey(resource.ID) && resources[resource.ID].Amount >= amount)
{
resources[resource.ID].Amount -= (int)(amount * SeasonResourceConsumedMod(resource));
}
else
{
throw new InsufficientResourceException(resource.ID.ToString());
}
}
// todo - as resources are defined with constant names, include if checks here
public float SeasonResourceConsumedMod(DResource resource)
{
if (resource.Name == Constants.FOOD_RESOURCE_NAME)
return DSeasons.modFoodProduction[(int)season];
return 1f;
}
public void ConsumeResource(DResource resource)
{
ConsumeResource(resource, resource.Amount);
}
public float CalculateExploration()
{
float countDiscovered = 0.0f;
foreach(DBuilding dBuilding in buildings.Values)
{
if (dBuilding != townHall)
{
if (dBuilding.Status != DBuilding.DBuildingStatus.UNDISCOVERED)
{
countDiscovered++;
}
}
}
if(countDiscovered > 0)
return countDiscovered / (float)(buildings.Count - 1);
else
return countDiscovered;
}
public void CalculateResourceRates()
{
foreach (var entry in resources)
{
foreach (var entry0 in prevResources)
{
if (entry.Key == entry0.Key)
{
int change = entry.Value.Amount - entry0.Value.Amount;
// Debug.Log(entry0.Value.Name +"[prev]: "+ entry0.Value.Amount);
resourceRates[entry.Key] = DResource.Create(entry.Value, change);
break;
}
}
}
// foreach (var entry in resourceRates)
// Debug.Log(entry.Value.Name +": "+ entry.Value.Amount);
}
public DResource GetResource(string name)
{
int resourceID = DResource.NameToID(name);
if (resources.ContainsKey(resourceID))
{
return resources[resourceID];
}
else
{
AddResource(DResource.Create(name));
return resources[resourceID];
}
}
public float PercentPopulationInfected()
{
float result = 0;
foreach (KeyValuePair<int, DPerson> entry in people)
if (entry.Value.Infection > 0)
result++;
result /= people.Count;
return result;
}
public float DevelopedValue()
{
float explored = CalculateExploration();
float assessed = PercentAssessed();
float repaired = PercentRepaired();
return (explored * Constants.CITY_DEVELOPMENT_PERCENT_FROM_EXPLORE) +
(assessed * Constants.CITY_DEVELOPMENT_PERCENT_FROM_ASSESS) +
(repaired * Constants.CITY_DEVELOPMENT_PERCENT_FROM_REPAIR);
}
public float PercentAssessed()
{
float result = 0f;
foreach (KeyValuePair<int, DBuilding> entry in buildings)
result += entry.Value.LevelAssessed;
result /= buildings.Count;
return result;
}
public float PercentRepaired()
{
float result = 0f;
foreach (KeyValuePair<int, DBuilding> entry in buildings)
result += (entry.Value.LevelDamaged + entry.Value.LevelInfectedRaw) / 2f;
result /= buildings.Count;
return result;
}
#endregion
#region Map of Canada
public void setEdges(List<string> s)
{
linkedCityKeys = s;
}
public void linkToCity(string cityKey)
{
if (!linkedCityKeys.Contains(cityKey))
linkedCityKeys.Add(cityKey);
}
public IEnumerable<string> getAllLinkedCityKeys()
{
foreach (string key in linkedCityKeys)
yield return key;
}
public bool isLinkedTo(string cityKey)
{
return linkedCityKeys.Contains(cityKey);
}
#endregion
public void Explore(float exploreAmount)
{
explorationLevel = explorationLevel + exploreAmount;
float explorableBuildings = buildings.Count - 1.0f;
float offsetPercentage = 1.0f / explorableBuildings;
List<DBuilding> UnExploredBuildings = new List<DBuilding>();
foreach(DBuilding dBuilding in buildings.Values)
{
if (dBuilding != townHall)
if ((dBuilding.Status == DBuilding.DBuildingStatus.UNDISCOVERED))
{
UnExploredBuildings.Add(dBuilding);
}
}
if (explorationLevel - offsetPercentage * (explorableBuildings - UnExploredBuildings.Count) >= offsetPercentage)
{
int index = UnityEngine.Random.Range(0, UnExploredBuildings.Count - 1);
UnExploredBuildings[index].Discover();
}
}
public bool HasPeopleInTask(Type taskType)
{
if (taskType != typeof(DTask) && !taskType.IsSubclassOf(typeof(DTask)))
return false;
foreach (var entry in people)
if (entry.Value.Task != null && entry.Value.Task.GetType() == typeof(DTask_Explore))
return true;
return false;
}
public int PeopleInTask(Type taskType)
{
if (taskType != typeof(DTask) && taskType.IsSubclassOf(typeof(DTask)))
return 0;
int result = 0;
foreach (var entry in people)
if (entry.Value.Task != null && entry.Value.Task.GetType() == typeof(DTask_Explore))
result ++;
return result;
}
#region Properties
public Dictionary<int, DBuilding> Buildings
{
get { return buildings; }
}
public float Health
{
get { return health; }
set { health = value; }
}
public Dictionary<int, DResource> ResourceRates
{
get { return resourceRates; }
set { resourceRates = value; }
}
public Dictionary<int, DResource> Resources
{
get { return resources; }
set { resources = value; }
}
public Dictionary<int, DPerson> People
{
get { return people; }
}
public List<string> LinkedCityKeys
{
get { return linkedCityKeys; }
set { linkedCityKeys = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public float ExplorationLevel
{
get { return explorationLevel;}
}
public int Age
{
get { return age; }
}
public CityController CityController
{
get { return cityController; }
}
public DSeasons._season Season
{
get { return season; }
set { season = value; }
}
public DateTime[] SeasonStartDates
{
get { return seasonStartDates; }
set { seasonStartDates = value; }
}
public DateTime[] DeadOfWinterDates
{
get { return deadOfWinterStartEnd; }
set { deadOfWinterStartEnd = value; }
}
public bool IsDeadOfWinter
{
get { return isDeadOfWinter; }
set { isDeadOfWinter = value; }
}
public int ShelterTier
{
get { return shelterTier; }
}
public void RaiseShelterTier()
{
shelterTier = Mathf.Clamp(shelterTier + 1, 1, 5);
}
public void LowerShelterTier()
{
shelterTier = Mathf.Clamp(shelterTier - 1, 1, 5);
}
public int FuelToShelterConversion
{
get { return fuelToShelterConversion; }
}
public void RaiseFuelConversion()
{
int cap = 4 < fuelResource.Amount ? 4 : fuelResource.Amount;
fuelToShelterConversion = Mathf.Clamp(fuelToShelterConversion + 1, 0, cap);
}
public void LowerFuelConversion()
{
int cap = 4 < fuelResource.Amount ? 4 : fuelResource.Amount;
fuelToShelterConversion = Mathf.Clamp(fuelToShelterConversion - 1, 0, cap);
}
public DGame Game
{
get { return dGame; }
}
#endregion
public JSONNode SaveToJSON()
{
JSONNode returnNode = new JSONObject();
// Save general info about city
returnNode.Add("name", new JSONString(name));
returnNode.Add("age", new JSONNumber(age));
returnNode.Add("explorationLevel", new JSONNumber(explorationLevel));
// Save resource info
returnNode.Add("shelterTier", new JSONNumber(shelterTier));
returnNode.Add("fuelToShelterConversion", new JSONNumber(fuelToShelterConversion));
// Save health and food stuff
returnNode.Add("health", new JSONNumber(health));
returnNode.Add("foodConsumption", new JSONNumber(foodConsumption));
returnNode.Add("notEnoughFoodHealthDecay", new JSONNumber(notEnoughFoodHealthDecay));
// Save season
returnNode.Add("season", new JSONNumber((int)season));
returnNode.Add("isDeadOfWinter", new JSONBool(isDeadOfWinter));
#region Lists of Stuff
// Save people
JSONArray peopleList = new JSONArray();
foreach (var person in people)
{
peopleList.Add(person.Value.SaveToJSON());
}
returnNode.Add("people", peopleList);
// Save buildings
JSONArray buildingList = new JSONArray();
foreach (var building in buildings)
{
buildingList.Add(building.Value.SaveToJSON());
}
returnNode.Add("buildings", buildingList);
// Save resources
JSONArray resourceList = new JSONArray();
foreach (var resource in resources)
{
resourceList.Add(resource.Value.SaveToJSON());
}
returnNode.Add("resources", resourceList);
// Save linked cities
JSONArray linkedCityList = new JSONArray();
foreach (var city in linkedCityKeys)
{
linkedCityList.Add(new JSONString(city));
}
returnNode.Add("linked_cities", linkedCityList);
#endregion
return returnNode;
}
public static DCity LoadFromJSON(JSONNode jsonNode, DGame dGame, bool randomBuildingPlacement=false)
{
string _name = jsonNode["name"];
// TODO: Store season start and end dates
// Create city object
DCity dCity = new DCity(_name, null, dGame.CurrentDate);
dCity.cityController = dGame.GameController.CreateCityController(dCity);
dCity.dGame = dGame;
// Load general info about city
dCity.age = RandJSON.JSONInt(jsonNode["age"]);
dCity.explorationLevel = RandJSON.JSONFloat(jsonNode["explorationLevel"]);
// Load resource info
dCity.shelterTier = RandJSON.JSONInt(jsonNode["shelterTier"]);
dCity.fuelToShelterConversion = RandJSON.JSONInt(jsonNode["fuelToShelterConversion"]);
// TODO: Why are these variables static?
// Load health and food stuff
//dCity.health = RandJSON.JSONFloat(jsonNode["health"]);
//dCity.foodConsumption = RandJSON.JSONInt(jsonNode["foodConsumption"]);
//dCity.notEnoughFoodHealthDecay = RandJSON.JSONFloat(jsonNode["notEnoughFoodHealthDecay"]);
// Load season
DSeasons._season _season = (DSeasons._season)(RandJSON.JSONInt(jsonNode["season"]));
bool _isDeadOfWinter = jsonNode["isDeadOfWinter"].AsBool;
#region Lists of Stuff
// Load people
foreach (JSONNode person in jsonNode["people"].AsArray)
DPerson.LoadFromJSON(person, dCity);
// Load in all the possible locations for buildings
List<Vector2> possibleBuildingLocations = null;
if (randomBuildingPlacement)
{
possibleBuildingLocations = new List<Vector2>();
foreach (JSONNode buildingLoc in jsonNode["building_locations"].AsArray)
{
// Get the random positions available
float xPos = RandJSON.JSONFloat(buildingLoc["x"]);
float yPos = RandJSON.JSONFloat(buildingLoc["y"]);
possibleBuildingLocations.Add(new Vector2(xPos, yPos));
}
}
// Load buildings
foreach (JSONNode building in jsonNode["buildings"].AsArray)
{
DBuilding loadedBuilding = DBuilding.LoadFromJSON(building, dCity, randomBuildingPlacement);
if (loadedBuilding.Name.Equals("Town Hall"))
{
dCity.townHall = loadedBuilding;
}
else if (randomBuildingPlacement)
{
// Pull a random building location from the list
int randIndex = Mathf.RoundToInt(UnityEngine.Random.Range(0, possibleBuildingLocations.Count - 1));
loadedBuilding.SetBuildingPosition(possibleBuildingLocations[randIndex]);
possibleBuildingLocations.RemoveAt(randIndex);
}
}
// Load resources
foreach (JSONNode resource in jsonNode["resources"].AsArray)
dCity.AddResource(DResource.LoadFromJSON(resource));
// Load linked cities
foreach (JSONNode linkedCity in jsonNode["linked_cities"].AsArray)
dCity.linkToCity(linkedCity.Value);
#endregion
return dCity;
}
}
#region Exceptions
public class InsufficientResourceException : Exception
{
public InsufficientResourceException()
{
}
public InsufficientResourceException(string message)
: base(message)
{
}
public InsufficientResourceException(string message, Exception inner)
: base(message, inner)
{
}
}
public class BuildingNotFoundException : Exception
{
public BuildingNotFoundException()
{
}
public BuildingNotFoundException(string message)
: base(message)
{
}
public BuildingNotFoundException(string message, Exception inner)
: base(message, inner)
{
}
}
public class BuildingAlreadyAddedException : Exception
{
public BuildingAlreadyAddedException()
{
}
public BuildingAlreadyAddedException(string message) : base(message)
{
}
public BuildingAlreadyAddedException(string message, Exception innerException) : base(message, innerException)
{
}
protected BuildingAlreadyAddedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
public class PersonNotFoundException : Exception
{
public PersonNotFoundException()
{
}
public PersonNotFoundException(string message)
: base(message)
{
}
public PersonNotFoundException(string message, Exception inner)
: base(message, inner)
{
}
}
public class PersonAlreadyAddedException : Exception
{
public PersonAlreadyAddedException()
{
}
public PersonAlreadyAddedException(string message) : base(message)
{
}
public PersonAlreadyAddedException(string message, Exception innerException) : base(message, innerException)
{
}
protected PersonAlreadyAddedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
#endregion
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Lucene.Net.QueryParsers.Classic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Records;
using OrchardCore.DisplayManagement;
using OrchardCore.Entities;
using OrchardCore.Lucene.Model;
using OrchardCore.Lucene.Services;
using OrchardCore.Mvc.Utilities;
using OrchardCore.Navigation;
using OrchardCore.Search.Abstractions.ViewModels;
using OrchardCore.Security.Permissions;
using OrchardCore.Settings;
using YesSql;
using YesSql.Services;
namespace OrchardCore.Lucene.Controllers
{
public class SearchController : Controller
{
private readonly IAuthorizationService _authorizationService;
private readonly ISiteService _siteService;
private readonly LuceneIndexManager _luceneIndexProvider;
private readonly LuceneIndexingService _luceneIndexingService;
private readonly LuceneIndexSettingsService _luceneIndexSettingsService;
private readonly LuceneAnalyzerManager _luceneAnalyzerManager;
private readonly ISearchQueryService _searchQueryService;
private readonly ISession _session;
private readonly IStringLocalizer S;
private readonly IEnumerable<IPermissionProvider> _permissionProviders;
private readonly dynamic New;
private readonly ILogger _logger;
public SearchController(
IAuthorizationService authorizationService,
ISiteService siteService,
LuceneIndexManager luceneIndexProvider,
LuceneIndexingService luceneIndexingService,
LuceneIndexSettingsService luceneIndexSettingsService,
LuceneAnalyzerManager luceneAnalyzerManager,
ISearchQueryService searchQueryService,
ISession session,
IStringLocalizer<SearchController> stringLocalizer,
IEnumerable<IPermissionProvider> permissionProviders,
IShapeFactory shapeFactory,
ILogger<SearchController> logger
)
{
_authorizationService = authorizationService;
_siteService = siteService;
_luceneIndexProvider = luceneIndexProvider;
_luceneIndexingService = luceneIndexingService;
_luceneIndexSettingsService = luceneIndexSettingsService;
_luceneAnalyzerManager = luceneAnalyzerManager;
_searchQueryService = searchQueryService;
_session = session;
S = stringLocalizer;
_permissionProviders = permissionProviders;
New = shapeFactory;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> Search(SearchIndexViewModel viewModel, PagerSlimParameters pagerParameters)
{
var permissionsProvider = _permissionProviders.FirstOrDefault(x => x.GetType().FullName == "OrchardCore.Lucene.Permissions");
var permissions = await permissionsProvider.GetPermissionsAsync();
var siteSettings = await _siteService.GetSiteSettingsAsync();
var searchSettings = siteSettings.As<LuceneSettings>();
if (permissions.FirstOrDefault(x => x.Name == "QueryLucene" + searchSettings.SearchIndex + "Index") != null)
{
if (!await _authorizationService.AuthorizeAsync(User, permissions.FirstOrDefault(x => x.Name == "QueryLucene" + searchSettings.SearchIndex + "Index")))
{
return this.ChallengeOrForbid();
}
}
else
{
_logger.LogInformation("Couldn't execute search. The search index doesn't exist.");
return BadRequest("Search is not configured.");
}
if (searchSettings.SearchIndex != null && !_luceneIndexProvider.Exists(searchSettings.SearchIndex))
{
_logger.LogInformation("Couldn't execute search. The search index doesn't exist.");
return BadRequest("Search is not configured.");
}
var luceneSettings = await _luceneIndexingService.GetLuceneSettingsAsync();
if (luceneSettings == null || luceneSettings?.DefaultSearchFields == null)
{
_logger.LogInformation("Couldn't execute search. No Lucene settings was defined.");
return BadRequest("Search is not configured.");
}
var luceneIndexSettings = await _luceneIndexSettingsService.GetSettingsAsync(searchSettings.SearchIndex);
if (luceneIndexSettings == null)
{
_logger.LogInformation($"Couldn't execute search. No Lucene index settings was defined for ({searchSettings.SearchIndex}) index.");
return BadRequest($"Search index ({searchSettings.SearchIndex}) is not configured.");
}
if (string.IsNullOrWhiteSpace(viewModel.Terms))
{
return View(new SearchIndexViewModel
{
SearchForm = new SearchFormViewModel("Search__Form") { },
});
}
var pager = new PagerSlim(pagerParameters, siteSettings.PageSize);
// We Query Lucene index
var analyzer = _luceneAnalyzerManager.CreateAnalyzer(await _luceneIndexSettingsService.GetIndexAnalyzerAsync(luceneIndexSettings.IndexName));
var queryParser = new MultiFieldQueryParser(LuceneSettings.DefaultVersion, luceneSettings.DefaultSearchFields, analyzer);
// Fetch one more result than PageSize to generate "More" links
var start = 0;
var end = pager.PageSize + 1;
if (pagerParameters.Before != null)
{
start = Convert.ToInt32(pagerParameters.Before) - pager.PageSize - 1;
end = Convert.ToInt32(pagerParameters.Before);
}
else if (pagerParameters.After != null)
{
start = Convert.ToInt32(pagerParameters.After);
end = Convert.ToInt32(pagerParameters.After) + pager.PageSize + 1;
}
var terms = viewModel.Terms;
if (!searchSettings.AllowLuceneQueriesInSearch)
{
terms = QueryParser.Escape(terms);
}
IList<string> contentItemIds;
try
{
var query = queryParser.Parse(terms);
contentItemIds = (await _searchQueryService.ExecuteQueryAsync(query, searchSettings.SearchIndex, start, end))
.ToList();
}
catch (ParseException e)
{
ModelState.AddModelError("Terms", S["Incorrect query syntax."]);
_logger.LogError(e, "Incorrect Lucene search query syntax provided in search:");
// Return a SearchIndexViewModel without SearchResults or Pager shapes since there is an error.
return View(new SearchIndexViewModel
{
Terms = viewModel.Terms,
SearchForm = new SearchFormViewModel("Search__Form") { Terms = viewModel.Terms },
});
}
// We Query database to retrieve content items.
IQuery<ContentItem> queryDb;
if (luceneIndexSettings.IndexLatest)
{
queryDb = _session.Query<ContentItem, ContentItemIndex>()
.Where(x => x.ContentItemId.IsIn(contentItemIds) && x.Latest == true)
.Take(pager.PageSize + 1);
}
else
{
queryDb = _session.Query<ContentItem, ContentItemIndex>()
.Where(x => x.ContentItemId.IsIn(contentItemIds) && x.Published == true)
.Take(pager.PageSize + 1);
}
// Sort the content items by their rank in the search results returned by Lucene.
var containedItems = (await queryDb.ListAsync()).OrderBy(x => contentItemIds.IndexOf(x.ContentItemId));
// We set the PagerSlim before and after links
if (pagerParameters.After != null || pagerParameters.Before != null)
{
if (start + 1 > 1)
{
pager.Before = (start + 1).ToString();
}
else
{
pager.Before = null;
}
}
if (containedItems.Count() == pager.PageSize + 1)
{
pager.After = (end - 1).ToString();
}
else
{
pager.After = null;
}
var model = new SearchIndexViewModel
{
Terms = viewModel.Terms,
SearchForm = new SearchFormViewModel("Search__Form") { Terms = viewModel.Terms },
SearchResults = new SearchResultsViewModel("Search__Results") { ContentItems = containedItems.Take(pager.PageSize) },
Pager = (await New.PagerSlim(pager)).UrlParams(new Dictionary<string, string>() { { "Terms", viewModel.Terms } })
};
return View(model);
}
}
}
| |
/*
* IdSharp - A tagging library for .NET
* Copyright (C) 2007 Jud White
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using IdSharp.Tagging.ID3v1;
using IdSharp.Tagging.ID3v2;
using IdSharp.Tagging.ID3v2.Frames;
namespace IdSharpHarness
{
public partial class ID3v2UserControl : UserControl
{
#region <<< Private Fields >>>
private IID3v2 m_ID3v2;
#endregion <<< Private Fields >>>
#region <<< Constructor >>>
public ID3v2UserControl()
{
InitializeComponent();
cmbGenre.Sorted = true;
cmbGenre.Items.AddRange(GenreHelper.GenreByIndex);
cmbImageType.Items.AddRange(PictureTypeHelper.PictureTypes);
}
#endregion <<< Constructor >>>
#region <<< Event Handlers >>>
private void bindingSource_CurrentChanged(object sender, EventArgs e)
{
IAttachedPicture attachedPicture = GetCurrentPictureFrame();
if (attachedPicture != null)
LoadImageData(attachedPicture);
else
ClearImageData();
}
private void imageContextMenu_Opening(object sender, CancelEventArgs e)
{
miSaveImage.Enabled = (this.pictureBox1.Image != null);
miLoadImage.Enabled = (GetCurrentPictureFrame() != null);
}
private void miSaveImage_Click(object sender, EventArgs e)
{
IAttachedPicture attachedPicture = GetCurrentPictureFrame();
SaveImageToFile(attachedPicture);
}
private void miLoadImage_Click(object sender, EventArgs e)
{
IAttachedPicture attachedPicture = GetCurrentPictureFrame();
LoadImageFromFile(attachedPicture);
}
private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
{
IAttachedPicture attachedPicture = GetCurrentPictureFrame();
LoadImageFromFile(attachedPicture);
}
private void cmbImageType_SelectedIndexChanged(object sender, EventArgs e)
{
IAttachedPicture attachedPicture = GetCurrentPictureFrame();
if (attachedPicture != null)
attachedPicture.PictureType = PictureTypeHelper.GetPictureTypeFromString(cmbImageType.Text);
}
private void txtImageDescription_Validated(object sender, EventArgs e)
{
IAttachedPicture attachedPicture = GetCurrentPictureFrame();
if (attachedPicture != null)
attachedPicture.Description = txtImageDescription.Text;
}
#endregion <<< Event Handlers >>>
#region <<< Private Methods >>>
private void LoadImageData(IAttachedPicture attachedPicture)
{
pictureBox1.Image = attachedPicture.Picture;
txtImageDescription.Text = attachedPicture.Description;
cmbImageType.SelectedIndex = cmbImageType.Items.IndexOf(PictureTypeHelper.GetStringFromPictureType(attachedPicture.PictureType));
txtImageDescription.Enabled = true;
cmbImageType.Enabled = true;
}
private void ClearImageData()
{
pictureBox1.Image = null;
txtImageDescription.Text = "";
cmbImageType.SelectedIndex = -1;
txtImageDescription.Enabled = false;
cmbImageType.Enabled = false;
}
private void SaveImageToFile(IAttachedPicture attachedPicture)
{
String extension = attachedPicture.PictureExtension;
imageSaveFileDialog.FileName = "image." + extension;
DialogResult dialogResult = imageSaveFileDialog.ShowDialog();
if (dialogResult == DialogResult.OK)
{
using (FileStream fs = File.Open(imageSaveFileDialog.FileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
fs.Write(attachedPicture.PictureData, 0, attachedPicture.PictureData.Length);
}
}
}
private void LoadImageFromFile(IAttachedPicture attachedPicture)
{
DialogResult dialogResult = imageOpenFileDialog.ShowDialog();
if (dialogResult == DialogResult.OK)
{
attachedPicture.Picture = Image.FromFile(imageOpenFileDialog.FileName);
pictureBox1.Image = attachedPicture.Picture;
}
}
private IAttachedPicture GetCurrentPictureFrame()
{
if (imageBindingNavigator.BindingSource == null)
return null;
return imageBindingNavigator.BindingSource.Current as IAttachedPicture;
}
#endregion <<< Private Methods >>>
#region <<< Public Methods >>>
public void LoadFile(String path)
{
ClearImageData();
m_ID3v2 = ID3v2Helper.CreateID3v2(path);
txtFilename.Text = Path.GetFileName(path);
txtArtist.Text = m_ID3v2.Artist;
txtTitle.Text = m_ID3v2.Title;
txtAlbum.Text = m_ID3v2.Album;
cmbGenre.Text = m_ID3v2.Genre;
txtYear.Text = m_ID3v2.Year;
txtTrackNumber.Text = m_ID3v2.TrackNumber;
pictureBox1.Image = m_ID3v2.PictureList[0].Picture;
/*
BindingSource bindingSource = new BindingSource();
imageBindingNavigator.BindingSource = bindingSource;
bindingSource.CurrentChanged += new EventHandler(bindingSource_CurrentChanged);
bindingSource.DataSource = m_ID3v2.PictureList; */
switch (m_ID3v2.Header.TagVersion)
{
case ID3v2TagVersion.ID3v22:
cmbID3v2.SelectedIndex = cmbID3v2.Items.IndexOf("ID3v2.2");
break;
case ID3v2TagVersion.ID3v23:
cmbID3v2.SelectedIndex = cmbID3v2.Items.IndexOf("ID3v2.3");
break;
case ID3v2TagVersion.ID3v24:
cmbID3v2.SelectedIndex = cmbID3v2.Items.IndexOf("ID3v2.4");
break;
}
}
public void SaveFile(String path)
{
if (m_ID3v2 == null)
{
MessageBox.Show("Nothing to save!");
return;
}
if (cmbID3v2.SelectedIndex == cmbID3v2.Items.IndexOf("ID3v2.2"))
m_ID3v2.Header.TagVersion = ID3v2TagVersion.ID3v22;
else if (cmbID3v2.SelectedIndex == cmbID3v2.Items.IndexOf("ID3v2.3"))
m_ID3v2.Header.TagVersion = ID3v2TagVersion.ID3v23;
else if (cmbID3v2.SelectedIndex == cmbID3v2.Items.IndexOf("ID3v2.4"))
m_ID3v2.Header.TagVersion = ID3v2TagVersion.ID3v24;
else
throw new Exception("Unknown tag version");
m_ID3v2.Artist = txtArtist.Text;
m_ID3v2.Title = txtTitle.Text;
m_ID3v2.Album = txtAlbum.Text;
m_ID3v2.Genre = cmbGenre.Text;
m_ID3v2.Year = txtYear.Text;
m_ID3v2.TrackNumber = txtTrackNumber.Text;
m_ID3v2.Save(path);
}
#endregion <<< Public Methods >>>
private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
{
Console.WriteLine(m_ID3v2.PictureList.Count);
}
}
}
| |
// 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.Globalization;
using System.Reflection;
using System.Xml;
using System.Security;
namespace System.Runtime.Serialization
{
#if NET_NATIVE
public abstract class PrimitiveDataContract : DataContract
#else
internal abstract class PrimitiveDataContract : DataContract
#endif
{
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private PrimitiveDataContractCriticalHelper _helper;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
protected PrimitiveDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new PrimitiveDataContractCriticalHelper(type, name, ns))
{
_helper = base.Helper as PrimitiveDataContractCriticalHelper;
}
static internal PrimitiveDataContract GetPrimitiveDataContract(Type type)
{
return DataContract.GetBuiltInDataContract(type) as PrimitiveDataContract;
}
static internal PrimitiveDataContract GetPrimitiveDataContract(string name, string ns)
{
return DataContract.GetBuiltInDataContract(name, ns) as PrimitiveDataContract;
}
internal abstract string WriteMethodName { get; }
internal abstract string ReadMethodName { get; }
public override XmlDictionaryString TopLevelElementNamespace
{
/// <SecurityNote>
/// Critical - for consistency with base class
/// Safe - for consistency with base class
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return DictionaryGlobals.SerializationNamespace; }
/// <SecurityNote>
/// Critical - for consistency with base class
/// </SecurityNote>
[SecurityCritical]
set
{ }
}
internal override bool CanContainReferences
{
get { return false; }
}
internal override bool IsPrimitive
{
get { return true; }
}
public override bool IsBuiltInDataContract
{
get
{
return true;
}
}
internal MethodInfo XmlFormatWriterMethod
{
/// <SecurityNote>
/// Critical - fetches the critical XmlFormatWriterMethod property
/// Safe - XmlFormatWriterMethod only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatWriterMethod == null)
{
if (UnderlyingType.GetTypeInfo().IsValueType)
_helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
else
_helper.XmlFormatWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
}
return _helper.XmlFormatWriterMethod;
}
}
internal MethodInfo XmlFormatContentWriterMethod
{
/// <SecurityNote>
/// Critical - fetches the critical XmlFormatContentWriterMethod property
/// Safe - XmlFormatContentWriterMethod only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatContentWriterMethod == null)
{
if (UnderlyingType.GetTypeInfo().IsValueType)
_helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType });
else
_helper.XmlFormatContentWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType });
}
return _helper.XmlFormatContentWriterMethod;
}
}
internal MethodInfo XmlFormatReaderMethod
{
/// <SecurityNote>
/// Critical - fetches the critical XmlFormatReaderMethod property
/// Safe - XmlFormatReaderMethod only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatReaderMethod == null)
{
_helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers);
}
return _helper.XmlFormatReaderMethod;
}
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
xmlWriter.WriteAnyType(obj);
}
protected object HandleReadValue(object obj, XmlObjectSerializerReadContext context)
{
context.AddNewObject(obj);
return obj;
}
protected bool TryReadNullAtTopLevel(XmlReaderDelegator reader)
{
Attributes attributes = new Attributes();
attributes.Read(reader);
if (attributes.Ref != Globals.NewObjectId)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotDeserializeRefAtTopLevel, attributes.Ref)));
if (attributes.XsiNil)
{
reader.Skip();
return true;
}
return false;
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds all state used for for (de)serializing primitives.
/// since the data is cached statically, we lock down access to it.
/// </SecurityNote>
private class PrimitiveDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private MethodInfo _xmlFormatWriterMethod;
private MethodInfo _xmlFormatContentWriterMethod;
private MethodInfo _xmlFormatReaderMethod;
internal PrimitiveDataContractCriticalHelper(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(type)
{
SetDataContractName(name, ns);
}
internal MethodInfo XmlFormatWriterMethod
{
get { return _xmlFormatWriterMethod; }
set { _xmlFormatWriterMethod = value; }
}
internal MethodInfo XmlFormatContentWriterMethod
{
get { return _xmlFormatContentWriterMethod; }
set { _xmlFormatContentWriterMethod = value; }
}
internal MethodInfo XmlFormatReaderMethod
{
get { return _xmlFormatReaderMethod; }
set { _xmlFormatReaderMethod = value; }
}
}
}
#if NET_NATIVE
public class CharDataContract : PrimitiveDataContract
#else
internal class CharDataContract : PrimitiveDataContract
#endif
{
public CharDataContract() : this(DictionaryGlobals.CharLocalName, DictionaryGlobals.SerializationNamespace)
{
}
internal CharDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(char), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteChar"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsChar"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteChar((char)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsChar()
: HandleReadValue(reader.ReadElementContentAsChar(), context);
}
}
#if NET_NATIVE
public class BooleanDataContract : PrimitiveDataContract
#else
internal class BooleanDataContract : PrimitiveDataContract
#endif
{
public BooleanDataContract() : base(typeof(bool), DictionaryGlobals.BooleanLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteBoolean"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsBoolean"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteBoolean((bool)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsBoolean()
: HandleReadValue(reader.ReadElementContentAsBoolean(), context);
}
}
#if NET_NATIVE
public class SignedByteDataContract : PrimitiveDataContract
#else
internal class SignedByteDataContract : PrimitiveDataContract
#endif
{
public SignedByteDataContract() : base(typeof(sbyte), DictionaryGlobals.SignedByteLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteSignedByte"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsSignedByte"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteSignedByte((sbyte)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsSignedByte()
: HandleReadValue(reader.ReadElementContentAsSignedByte(), context);
}
}
#if NET_NATIVE
public class UnsignedByteDataContract : PrimitiveDataContract
#else
internal class UnsignedByteDataContract : PrimitiveDataContract
#endif
{
public UnsignedByteDataContract() : base(typeof(byte), DictionaryGlobals.UnsignedByteLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedByte"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedByte"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedByte((byte)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedByte()
: HandleReadValue(reader.ReadElementContentAsUnsignedByte(), context);
}
}
#if NET_NATIVE
public class ShortDataContract : PrimitiveDataContract
#else
internal class ShortDataContract : PrimitiveDataContract
#endif
{
public ShortDataContract() : base(typeof(short), DictionaryGlobals.ShortLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteShort"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsShort"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteShort((short)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsShort()
: HandleReadValue(reader.ReadElementContentAsShort(), context);
}
}
#if NET_NATIVE
public class UnsignedShortDataContract : PrimitiveDataContract
#else
internal class UnsignedShortDataContract : PrimitiveDataContract
#endif
{
public UnsignedShortDataContract() : base(typeof(ushort), DictionaryGlobals.UnsignedShortLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedShort"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedShort"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedShort((ushort)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedShort()
: HandleReadValue(reader.ReadElementContentAsUnsignedShort(), context);
}
}
#if NET_NATIVE
public class IntDataContract : PrimitiveDataContract
#else
internal class IntDataContract : PrimitiveDataContract
#endif
{
public IntDataContract() : base(typeof(int), DictionaryGlobals.IntLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteInt"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsInt"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteInt((int)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsInt()
: HandleReadValue(reader.ReadElementContentAsInt(), context);
}
}
#if NET_NATIVE
public class UnsignedIntDataContract : PrimitiveDataContract
#else
internal class UnsignedIntDataContract : PrimitiveDataContract
#endif
{
public UnsignedIntDataContract() : base(typeof(uint), DictionaryGlobals.UnsignedIntLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedInt"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedInt"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedInt((uint)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedInt()
: HandleReadValue(reader.ReadElementContentAsUnsignedInt(), context);
}
}
#if NET_NATIVE
public class LongDataContract : PrimitiveDataContract
#else
internal class LongDataContract : PrimitiveDataContract
#endif
{
public LongDataContract() : this(DictionaryGlobals.LongLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal LongDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(long), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteLong"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsLong"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteLong((long)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsLong()
: HandleReadValue(reader.ReadElementContentAsLong(), context);
}
}
#if NET_NATIVE
public class UnsignedLongDataContract : PrimitiveDataContract
#else
internal class UnsignedLongDataContract : PrimitiveDataContract
#endif
{
public UnsignedLongDataContract() : base(typeof(ulong), DictionaryGlobals.UnsignedLongLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUnsignedLong"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedLong"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUnsignedLong((ulong)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsUnsignedLong()
: HandleReadValue(reader.ReadElementContentAsUnsignedLong(), context);
}
}
#if NET_NATIVE
public class FloatDataContract : PrimitiveDataContract
#else
internal class FloatDataContract : PrimitiveDataContract
#endif
{
public FloatDataContract() : base(typeof(float), DictionaryGlobals.FloatLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteFloat"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsFloat"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteFloat((float)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsFloat()
: HandleReadValue(reader.ReadElementContentAsFloat(), context);
}
}
#if NET_NATIVE
public class DoubleDataContract : PrimitiveDataContract
#else
internal class DoubleDataContract : PrimitiveDataContract
#endif
{
public DoubleDataContract() : base(typeof(double), DictionaryGlobals.DoubleLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteDouble"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsDouble"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteDouble((double)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsDouble()
: HandleReadValue(reader.ReadElementContentAsDouble(), context);
}
}
#if NET_NATIVE
public class DecimalDataContract : PrimitiveDataContract
#else
internal class DecimalDataContract : PrimitiveDataContract
#endif
{
public DecimalDataContract() : base(typeof(decimal), DictionaryGlobals.DecimalLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteDecimal"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsDecimal"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteDecimal((decimal)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsDecimal()
: HandleReadValue(reader.ReadElementContentAsDecimal(), context);
}
}
#if NET_NATIVE
public class DateTimeDataContract : PrimitiveDataContract
#else
internal class DateTimeDataContract : PrimitiveDataContract
#endif
{
public DateTimeDataContract() : base(typeof(DateTime), DictionaryGlobals.DateTimeLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteDateTime"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsDateTime"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteDateTime((DateTime)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsDateTime()
: HandleReadValue(reader.ReadElementContentAsDateTime(), context);
}
}
#if NET_NATIVE
public class StringDataContract : PrimitiveDataContract
#else
internal class StringDataContract : PrimitiveDataContract
#endif
{
public StringDataContract() : this(DictionaryGlobals.StringLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal StringDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(string), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteString"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsString"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteString((string)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsString();
}
else
{
return HandleReadValue(reader.ReadElementContentAsString(), context);
}
}
}
internal class HexBinaryDataContract : StringDataContract
{
internal HexBinaryDataContract() : base(DictionaryGlobals.hexBinaryLocalName, DictionaryGlobals.SchemaNamespace) { }
}
#if NET_NATIVE
public class ByteArrayDataContract : PrimitiveDataContract
#else
internal class ByteArrayDataContract : PrimitiveDataContract
#endif
{
public ByteArrayDataContract() : base(typeof(byte[]), DictionaryGlobals.ByteArrayLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteBase64"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsBase64"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteBase64((byte[])obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsBase64();
}
else
{
return HandleReadValue(reader.ReadElementContentAsBase64(), context);
}
}
}
#if NET_NATIVE
public class ObjectDataContract : PrimitiveDataContract
#else
internal class ObjectDataContract : PrimitiveDataContract
#endif
{
public ObjectDataContract() : base(typeof(object), DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteAnyType"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsAnyType"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
// write nothing
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
object obj;
if (reader.IsEmptyElement)
{
reader.Skip();
obj = new object();
}
else
{
string localName = reader.LocalName;
string ns = reader.NamespaceURI;
reader.Read();
try
{
reader.ReadEndElement();
obj = new object();
}
catch (XmlException xes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlForObjectCannotHaveContent, localName, ns), xes));
}
}
return (context == null) ? obj : HandleReadValue(obj, context);
}
internal override bool CanContainReferences
{
get { return true; }
}
internal override bool IsPrimitive
{
get { return false; }
}
}
#if NET_NATIVE
public class TimeSpanDataContract : PrimitiveDataContract
#else
internal class TimeSpanDataContract : PrimitiveDataContract
#endif
{
public TimeSpanDataContract() : this(DictionaryGlobals.TimeSpanLocalName, DictionaryGlobals.SerializationNamespace)
{
}
internal TimeSpanDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(TimeSpan), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteTimeSpan"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsTimeSpan"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteTimeSpan((TimeSpan)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsTimeSpan()
: HandleReadValue(reader.ReadElementContentAsTimeSpan(), context);
}
}
#if NET_NATIVE
public class GuidDataContract : PrimitiveDataContract
#else
internal class GuidDataContract : PrimitiveDataContract
#endif
{
public GuidDataContract() : this(DictionaryGlobals.GuidLocalName, DictionaryGlobals.SerializationNamespace)
{
}
internal GuidDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(Guid), name, ns)
{
}
internal override string WriteMethodName { get { return "WriteGuid"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsGuid"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteGuid((Guid)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
return (context == null) ? reader.ReadElementContentAsGuid()
: HandleReadValue(reader.ReadElementContentAsGuid(), context);
}
}
#if NET_NATIVE
public class UriDataContract : PrimitiveDataContract
#else
internal class UriDataContract : PrimitiveDataContract
#endif
{
public UriDataContract() : base(typeof(Uri), DictionaryGlobals.UriLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteUri"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsUri"; } }
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteUri((Uri)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsUri();
}
else
{
return HandleReadValue(reader.ReadElementContentAsUri(), context);
}
}
}
#if NET_NATIVE
public class QNameDataContract : PrimitiveDataContract
#else
internal class QNameDataContract : PrimitiveDataContract
#endif
{
public QNameDataContract() : base(typeof(XmlQualifiedName), DictionaryGlobals.QNameLocalName, DictionaryGlobals.SchemaNamespace)
{
}
internal override string WriteMethodName { get { return "WriteQName"; } }
internal override string ReadMethodName { get { return "ReadElementContentAsQName"; } }
internal override bool IsPrimitive
{
get { return false; }
}
public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
{
writer.WriteQName((XmlQualifiedName)obj);
}
public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
{
if (context == null)
{
return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsQName();
}
else
{
return HandleReadValue(reader.ReadElementContentAsQName(), context);
}
}
internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns)
{
if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace))
writer.WriteStartElement(Globals.SerPrefix, name, ns);
else if (ns != null && ns.Value != null && ns.Value.Length > 0)
writer.WriteStartElement(Globals.ElementPrefix, name, ns);
else
writer.WriteStartElement(name, ns);
}
}
}
| |
//BSD, 2014-present, WinterDev
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// The Stack Blur Algorithm was invented by Mario Klingemann,
// mario@quasimondo.com and described here:
// http://incubator.quasimondo.com/processing/fast_blur_deluxe.php
// (search phrase "Stackblur: Fast But Goodlooking").
// The major improvement is that there's no more division table
// that was very expensive to create for large blur radii. Instead,
// for 8-bit per channel and radius not exceeding 254 the division is
// replaced by multiplication and shift.
//
//----------------------------------------------------------------------------
using System;
using PixelFarm.Drawing;
using PixelFarm.CpuBlit.PixelProcessing;
namespace PixelFarm.CpuBlit.Imaging
{
//==============================================================stack_blur
public class StackBlur
{
public void Blur(BitmapBlenderBase img, int rx, int ry)
{
switch (img.BitDepth)
{
case 24:
StackBlurRGB24(img, rx, ry);
break;
case 32:
StackBlurRGBA32(img, rx, ry);
break;
default:
throw new NotImplementedException();
}
}
void StackBlurRGB24(BitmapBlenderBase img, int rx, int ry)
{
throw new NotImplementedException();
#if false
//typedef typename Img::color_type color_type;
//typedef typename Img::order_type order_type;
int x, y, xp, yp, i;
int stack_ptr;
int stack_start;
byte* src_pix_ptr;
byte* dst_pix_ptr;
color_type* stack_pix_ptr;
int sum_r;
int sum_g;
int sum_b;
int sum_in_r;
int sum_in_g;
int sum_in_b;
int sum_out_r;
int sum_out_g;
int sum_out_b;
int w = img.width();
int h = img.height();
int wm = w - 1;
int hm = h - 1;
int div;
int mul_sum;
int shr_sum;
pod_vector<color_type> stack;
if(rx > 0)
{
if(rx > 254) rx = 254;
div = rx * 2 + 1;
mul_sum = stack_blur_tables.g_stack_blur8_mul[rx];
shr_sum = stack_blur_tables.g_stack_blur8_shr[rx];
stack.allocate(div);
for(y = 0; y < h; y++)
{
sum_r =
sum_g =
sum_b =
sum_in_r =
sum_in_g =
sum_in_b =
sum_out_r =
sum_out_g =
sum_out_b = 0;
src_pix_ptr = img.pix_ptr(0, y);
for(i = 0; i <= rx; i++)
{
stack_pix_ptr = &stack[i];
stack_pix_ptr->r = src_pix_ptr[R];
stack_pix_ptr->g = src_pix_ptr[G];
stack_pix_ptr->b = src_pix_ptr[B];
sum_r += src_pix_ptr[R] * (i + 1);
sum_g += src_pix_ptr[G] * (i + 1);
sum_b += src_pix_ptr[B] * (i + 1);
sum_out_r += src_pix_ptr[R];
sum_out_g += src_pix_ptr[G];
sum_out_b += src_pix_ptr[B];
}
for(i = 1; i <= rx; i++)
{
if(i <= wm) src_pix_ptr += Img::pix_width;
stack_pix_ptr = &stack[i + rx];
stack_pix_ptr->r = src_pix_ptr[R];
stack_pix_ptr->g = src_pix_ptr[G];
stack_pix_ptr->b = src_pix_ptr[B];
sum_r += src_pix_ptr[R] * (rx + 1 - i);
sum_g += src_pix_ptr[G] * (rx + 1 - i);
sum_b += src_pix_ptr[B] * (rx + 1 - i);
sum_in_r += src_pix_ptr[R];
sum_in_g += src_pix_ptr[G];
sum_in_b += src_pix_ptr[B];
}
stack_ptr = rx;
xp = rx;
if(xp > wm) xp = wm;
src_pix_ptr = img.pix_ptr(xp, y);
dst_pix_ptr = img.pix_ptr(0, y);
for(x = 0; x < w; x++)
{
dst_pix_ptr[R] = (sum_r * mul_sum) >> shr_sum;
dst_pix_ptr[G] = (sum_g * mul_sum) >> shr_sum;
dst_pix_ptr[B] = (sum_b * mul_sum) >> shr_sum;
dst_pix_ptr += Img::pix_width;
sum_r -= sum_out_r;
sum_g -= sum_out_g;
sum_b -= sum_out_b;
stack_start = stack_ptr + div - rx;
if(stack_start >= div) stack_start -= div;
stack_pix_ptr = &stack[stack_start];
sum_out_r -= stack_pix_ptr->r;
sum_out_g -= stack_pix_ptr->g;
sum_out_b -= stack_pix_ptr->b;
if(xp < wm)
{
src_pix_ptr += Img::pix_width;
++xp;
}
stack_pix_ptr->r = src_pix_ptr[R];
stack_pix_ptr->g = src_pix_ptr[G];
stack_pix_ptr->b = src_pix_ptr[B];
sum_in_r += src_pix_ptr[R];
sum_in_g += src_pix_ptr[G];
sum_in_b += src_pix_ptr[B];
sum_r += sum_in_r;
sum_g += sum_in_g;
sum_b += sum_in_b;
++stack_ptr;
if(stack_ptr >= div) stack_ptr = 0;
stack_pix_ptr = &stack[stack_ptr];
sum_out_r += stack_pix_ptr->r;
sum_out_g += stack_pix_ptr->g;
sum_out_b += stack_pix_ptr->b;
sum_in_r -= stack_pix_ptr->r;
sum_in_g -= stack_pix_ptr->g;
sum_in_b -= stack_pix_ptr->b;
}
}
}
if(ry > 0)
{
if(ry > 254) ry = 254;
div = ry * 2 + 1;
mul_sum = stack_blur_tables.g_stack_blur8_mul[ry];
shr_sum = stack_blur_tables.g_stack_blur8_shr[ry];
stack.allocate(div);
int stride = img.stride();
for(x = 0; x < w; x++)
{
sum_r =
sum_g =
sum_b =
sum_in_r =
sum_in_g =
sum_in_b =
sum_out_r =
sum_out_g =
sum_out_b = 0;
src_pix_ptr = img.pix_ptr(x, 0);
for(i = 0; i <= ry; i++)
{
stack_pix_ptr = &stack[i];
stack_pix_ptr->r = src_pix_ptr[R];
stack_pix_ptr->g = src_pix_ptr[G];
stack_pix_ptr->b = src_pix_ptr[B];
sum_r += src_pix_ptr[R] * (i + 1);
sum_g += src_pix_ptr[G] * (i + 1);
sum_b += src_pix_ptr[B] * (i + 1);
sum_out_r += src_pix_ptr[R];
sum_out_g += src_pix_ptr[G];
sum_out_b += src_pix_ptr[B];
}
for(i = 1; i <= ry; i++)
{
if(i <= hm) src_pix_ptr += stride;
stack_pix_ptr = &stack[i + ry];
stack_pix_ptr->r = src_pix_ptr[R];
stack_pix_ptr->g = src_pix_ptr[G];
stack_pix_ptr->b = src_pix_ptr[B];
sum_r += src_pix_ptr[R] * (ry + 1 - i);
sum_g += src_pix_ptr[G] * (ry + 1 - i);
sum_b += src_pix_ptr[B] * (ry + 1 - i);
sum_in_r += src_pix_ptr[R];
sum_in_g += src_pix_ptr[G];
sum_in_b += src_pix_ptr[B];
}
stack_ptr = ry;
yp = ry;
if(yp > hm) yp = hm;
src_pix_ptr = img.pix_ptr(x, yp);
dst_pix_ptr = img.pix_ptr(x, 0);
for(y = 0; y < h; y++)
{
dst_pix_ptr[R] = (sum_r * mul_sum) >> shr_sum;
dst_pix_ptr[G] = (sum_g * mul_sum) >> shr_sum;
dst_pix_ptr[B] = (sum_b * mul_sum) >> shr_sum;
dst_pix_ptr += stride;
sum_r -= sum_out_r;
sum_g -= sum_out_g;
sum_b -= sum_out_b;
stack_start = stack_ptr + div - ry;
if(stack_start >= div) stack_start -= div;
stack_pix_ptr = &stack[stack_start];
sum_out_r -= stack_pix_ptr->r;
sum_out_g -= stack_pix_ptr->g;
sum_out_b -= stack_pix_ptr->b;
if(yp < hm)
{
src_pix_ptr += stride;
++yp;
}
stack_pix_ptr->r = src_pix_ptr[R];
stack_pix_ptr->g = src_pix_ptr[G];
stack_pix_ptr->b = src_pix_ptr[B];
sum_in_r += src_pix_ptr[R];
sum_in_g += src_pix_ptr[G];
sum_in_b += src_pix_ptr[B];
sum_r += sum_in_r;
sum_g += sum_in_g;
sum_b += sum_in_b;
++stack_ptr;
if(stack_ptr >= div) stack_ptr = 0;
stack_pix_ptr = &stack[stack_ptr];
sum_out_r += stack_pix_ptr->r;
sum_out_g += stack_pix_ptr->g;
sum_out_b += stack_pix_ptr->b;
sum_in_r -= stack_pix_ptr->r;
sum_in_g -= stack_pix_ptr->g;
sum_in_b -= stack_pix_ptr->b;
}
}
}
#endif
}
class BlurStack
{
public int r;
public int g;
public int b;
public int a;
public BlurStack() { }
public BlurStack(byte r, byte g, byte b, byte a)
{
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
}
class CircularBlurStack
{
int _currentHeadIndex;
int _currentTailIndex;
int _size;
BlurStack[] _blurValues;
public CircularBlurStack(int size)
{
_size = size;
_blurValues = new BlurStack[size];
_currentHeadIndex = 0;
_currentTailIndex = size - 1;
for (int i = size - 1; i >= 0; --i)
{
_blurValues[i] = new BlurStack();
}
}
public void Prepare(int count, int r, int g, int b, int a)
{
_currentHeadIndex = 0;
_currentTailIndex = _size - 1;
for (int i = 0; i < count; ++i)
{
_blurValues[i] = new BlurStack((byte)r, (byte)g, (byte)b, (byte)a);
this.Next();
}
}
public void ResetHeadTailPosition()
{
_currentHeadIndex = 0;
_currentTailIndex = _size - 1;
}
public void Next()
{
//--------------------------
if (_currentHeadIndex + 1 < _size)
{
_currentHeadIndex++;
}
else
{
_currentHeadIndex = 0;
}
//--------------------------
if (_currentTailIndex + 1 < _size)
{
_currentTailIndex++;
}
else
{
_currentTailIndex = 0;
}
}
public BlurStack CurrentHeadColor => _blurValues[_currentHeadIndex];
public BlurStack CurrentTailColor => _blurValues[_currentTailIndex];
}
void StackBlurRGBA32(BitmapBlenderBase img, int radius, int ry)
{
int width = img.Width;
int height = img.Height;
//TODO: review here again
//need to copy ?
int[] srcBuffer = new int[width * height];
BitmapBlenderBase.CopySubBufferToInt32Array(img, 0, 0, width, height, srcBuffer);
StackBlurARGB.FastBlur32ARGB(srcBuffer, srcBuffer, img.Width, img.Height, radius);
int i = 0;
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
//TODO: review here again=>
//find a better way to set pixel...
int dest = srcBuffer[i];
img.SetPixel(x, y,
Color.FromArgb(
(byte)((dest >> 16) & 0xff),
(byte)((dest >> 8) & 0xff),
(byte)((dest) & 0xff)));
i++;
}
}
}
}
public abstract class RecursizeBlurCalculator
{
public double r, g, b, a;
public abstract RecursizeBlurCalculator CreateNew();
public abstract void FromPix(Color c);
public abstract void Calc(double b1, double b2, double b3, double b4,
RecursizeBlurCalculator c1, RecursizeBlurCalculator c2, RecursizeBlurCalculator c3, RecursizeBlurCalculator c4);
public abstract void ToPix(ref Color c);
}
//===========================================================recursive_blur
public sealed class RecursiveBlur
{
ArrayList<RecursizeBlurCalculator> m_sum1;
ArrayList<RecursizeBlurCalculator> m_sum2;
ArrayList<Color> m_buf;
RecursizeBlurCalculator m_RecursizeBlurCalculatorFactory;
public RecursiveBlur(RecursizeBlurCalculator recursizeBluerCalculatorFactory)
{
m_sum1 = new ArrayList<RecursizeBlurCalculator>();
m_sum2 = new ArrayList<RecursizeBlurCalculator>();
m_buf = new ArrayList<Color>();
m_RecursizeBlurCalculatorFactory = recursizeBluerCalculatorFactory;
}
public void BlurX(IBitmapBlender img, double radius)
{
if (radius < 0.62) return;
if (img.Width < 3) return;
double s = (double)(radius * 0.5);
double q = (double)((s < 2.5) ?
3.97156 - 4.14554 * Math.Sqrt(1 - 0.26891 * s) :
0.98711 * s - 0.96330);
double q2 = (double)(q * q);
double q3 = (double)(q2 * q);
double b0 = (double)(1.0 / (1.578250 +
2.444130 * q +
1.428100 * q2 +
0.422205 * q3));
double b1 = (double)(2.44413 * q +
2.85619 * q2 +
1.26661 * q3);
double b2 = (double)(-1.42810 * q2 +
-1.26661 * q3);
double b3 = (double)(0.422205 * q3);
double b = (double)(1 - (b1 + b2 + b3) * b0);
b1 *= b0;
b2 *= b0;
b3 *= b0;
int w = img.Width;
int h = img.Height;
int wm = (int)w - 1;
int x, y;
int startCreatingAt = (int)m_sum1.Count;
m_sum1.AdjustSize(w);
m_sum2.AdjustSize(w);
m_buf.Allocate(w);
RecursizeBlurCalculator[] Sum1Array = m_sum1.UnsafeInternalArray;
RecursizeBlurCalculator[] Sum2Array = m_sum2.UnsafeInternalArray;
Color[] BufferArray = m_buf.UnsafeInternalArray;
for (int i = startCreatingAt; i < w; i++)
{
Sum1Array[i] = m_RecursizeBlurCalculatorFactory.CreateNew();
Sum2Array[i] = m_RecursizeBlurCalculatorFactory.CreateNew();
}
for (y = 0; y < h; y++)
{
//TODO: review get pixel here...
RecursizeBlurCalculator c = m_RecursizeBlurCalculatorFactory;
c.FromPix(img.GetPixel(0, y));
Sum1Array[0].Calc(b, b1, b2, b3, c, c, c, c);
c.FromPix(img.GetPixel(1, y));
Sum1Array[1].Calc(b, b1, b2, b3, c, Sum1Array[0], Sum1Array[0], Sum1Array[0]);
c.FromPix(img.GetPixel(2, y));
Sum1Array[2].Calc(b, b1, b2, b3, c, Sum1Array[1], Sum1Array[0], Sum1Array[0]);
for (x = 3; x < w; ++x)
{
c.FromPix(img.GetPixel(x, y));
Sum1Array[x].Calc(b, b1, b2, b3, c, Sum1Array[x - 1], Sum1Array[x - 2], Sum1Array[x - 3]);
}
Sum2Array[wm].Calc(b, b1, b2, b3, Sum1Array[wm], Sum1Array[wm], Sum1Array[wm], Sum1Array[wm]);
Sum2Array[wm - 1].Calc(b, b1, b2, b3, Sum1Array[wm - 1], Sum2Array[wm], Sum2Array[wm], Sum2Array[wm]);
Sum2Array[wm - 2].Calc(b, b1, b2, b3, Sum1Array[wm - 2], Sum2Array[wm - 1], Sum2Array[wm], Sum2Array[wm]);
Sum2Array[wm].ToPix(ref BufferArray[wm]);
Sum2Array[wm - 1].ToPix(ref BufferArray[wm - 1]);
Sum2Array[wm - 2].ToPix(ref BufferArray[wm - 2]);
for (x = wm - 3; x >= 0; --x)
{
Sum2Array[x].Calc(b, b1, b2, b3, Sum1Array[x], Sum2Array[x + 1], Sum2Array[x + 2], Sum2Array[x + 3]);
Sum2Array[x].ToPix(ref BufferArray[x]);
}
img.CopyColorHSpan(0, y, w, BufferArray, 0);
}
}
public void BlurY(IBitmapBlender img, double radius)
{
FormatTransposer img2 = new FormatTransposer(img);
BlurX(img2, radius);
}
public void Blur(IBitmapBlender img, double radius)
{
BlurX(img, radius);
BlurY(img, radius);
}
}
//=================================================recursive_blur_calc_rgb
public sealed class RecursiveBlurCalcRGB : RecursizeBlurCalculator
{
public override RecursizeBlurCalculator CreateNew()
{
return new RecursiveBlurCalcRGB();
}
public override void FromPix(Color c)
{
r = c.R;
g = c.G;
b = c.B;
}
public override void Calc(double b1, double b2, double b3, double b4,
RecursizeBlurCalculator c1, RecursizeBlurCalculator c2, RecursizeBlurCalculator c3, RecursizeBlurCalculator c4)
{
r = b1 * c1.r + b2 * c2.r + b3 * c3.r + b4 * c4.r;
g = b1 * c1.g + b2 * c2.g + b3 * c3.g + b4 * c4.g;
b = b1 * c1.b + b2 * c2.b + b3 * c3.b + b4 * c4.b;
}
public override void ToPix(ref Color c)
{
//c.red = (byte)AggMath.uround(r);
//c.green = (byte)AggMath.uround(g);
//c.blue = (byte)AggMath.uround(b);
c = new Color(c.A,
(byte)AggMath.uround(r),
(byte)AggMath.uround(g),
(byte)AggMath.uround(b)
);
}
}
//=================================================recursive_blur_calc_rgba
public sealed class RecursiveBlurCalcRGBA : RecursizeBlurCalculator
{
public override RecursizeBlurCalculator CreateNew()
{
return new RecursiveBlurCalcRGBA();
}
public override void FromPix(Color c)
{
r = c.R;
g = c.G;
b = c.B;
a = c.A;
}
public override void Calc(double b1, double b2, double b3, double b4,
RecursizeBlurCalculator c1, RecursizeBlurCalculator c2, RecursizeBlurCalculator c3, RecursizeBlurCalculator c4)
{
r = b1 * c1.r + b2 * c2.r + b3 * c3.r + b4 * c4.r;
g = b1 * c1.g + b2 * c2.g + b3 * c3.g + b4 * c4.g;
b = b1 * c1.b + b2 * c2.b + b3 * c3.b + b4 * c4.b;
a = b1 * c1.a + b2 * c2.a + b3 * c3.a + b4 * c4.a;
}
public override void ToPix(ref Color c)
{
c = new Color(
(byte)AggMath.uround(a),
(byte)AggMath.uround(r),
(byte)AggMath.uround(g),
(byte)AggMath.uround(b)
);
}
}
//================================================recursive_blur_calc_gray
public sealed class RecursiveBlurCalcGray : RecursizeBlurCalculator
{
public override RecursizeBlurCalculator CreateNew()
{
return new RecursiveBlurCalcGray();
}
public override void FromPix(Color c)
{
r = c.R;
}
public override void Calc(double b1, double b2, double b3, double b4,
RecursizeBlurCalculator c1, RecursizeBlurCalculator c2, RecursizeBlurCalculator c3, RecursizeBlurCalculator c4)
{
r = b1 * c1.r + b2 * c2.r + b3 * c3.r + b4 * c4.r;
}
public override void ToPix(ref Color c)
{
c = new Color(c.A,
(byte)AggMath.uround(r),
c.G,
c.B
);
}
}
}
| |
using System;
using System.IO;
using System.Dynamic;
using System.Reflection;
using System.Globalization;
using System.Xml;
using System.Linq;
using System.Collections.Generic;
using GTANetworkServer;
using GTANetworkShared;
class ModelDimensions
{
public int Model;
public Vector3 Max, Min;
}
class TrunkInfo
{
public int Model;
public Vector3 Offset, Size;
}
public class TrunkPlacer : Script
{
public TrunkPlacer()
{
API.onClientEventTrigger += ServerEvent;
API.onResourceStart += resStart;
API.onResourceStop += resStop;
}
private const string TRUNK_KEY = "VEHICLE_TRUNK_CONTENTS"; // List<NetHandle>
private Dictionary<int, ModelDimensions> _cachedDims = new Dictionary<int, ModelDimensions>();
private Dictionary<int, List<Action<ModelDimensions>>> _callbacks = new Dictionary<int, List<Action<ModelDimensions>>>();
private Dictionary<int, TrunkInfo> _trunks = new Dictionary<int, TrunkInfo>();
private void resStart()
{
var config = API.loadConfig("trunks.xml");
foreach (var element in config.getElementsByType("TrunkInfo"))
{
var model = element.getElementData<int>("model");
var offset = new Vector3(element.getElementData<float>("offsetX"), element.getElementData<float>("offsetY"),
element.getElementData<float>("offsetZ"));
var size = new Vector3(element.getElementData<float>("sizeX"), element.getElementData<float>("sizeY"),
element.getElementData<float>("sizeZ"));
_trunks.Add(model, new TrunkInfo()
{
Model = model,
Offset = offset,
Size = size,
});
}
}
private void resStop()
{
foreach (var veh in API.getAllVehicles())
{
API.resetEntityData(veh, TRUNK_KEY);
}
}
private TrunkInfo GetTrunkInfo(int model)
{
if (_trunks.ContainsKey(model))
return _trunks[model];
return null;
}
private Vector3 getModelSize(Vector3 max, Vector3 min)
{
return new Vector3((float) Math.Abs(max.X - min.X),
(float) Math.Abs(max.Y - min.Y),
(float) Math.Abs(max.Z - min.Z));
}
private void ServerEvent(Client sender, string ev, object[] args)
{
if (ev == "QUERY_MODEL_RESPONSE")
{
int model = (int) args[0];
Vector3 max = (Vector3) args[1];
Vector3 min = (Vector3) args[2];
var mdims = new ModelDimensions()
{
Model = model,
Max = max,
Min = min
};
if (_callbacks.ContainsKey(model) && _callbacks[model] != null && _callbacks[model].Count > 0)
{
foreach (var callback in _callbacks[model])
callback(mdims);
}
_callbacks.Remove(model);
if (!_cachedDims.ContainsKey(model))
_cachedDims.Add(model, mdims);
}
}
private ModelDimensions RequestModelDimensions(int model)
{
if (_cachedDims.ContainsKey(model))
{
return _cachedDims[model];
}
var players = API.getAllPlayers();
if (players.Count == 0)
return null;
ModelDimensions dims = null;
Action<ModelDimensions> callback = new Action<ModelDimensions>((m) =>
{
dims = m;
});
if (!_callbacks.ContainsKey(model))
_callbacks.Add(model, new List<Action<ModelDimensions>>());
_callbacks[model].Add(callback);
players[0].triggerEvent("QUERY_MODEL_SIZE", model);
DateTime start = DateTime.Now;
while (dims == null && DateTime.Now.Subtract(start).TotalMilliseconds < 1000)
API.sleep(0);
return dims;
}
private bool canModelFitInsideTrunk(int objectModel, int vehicleModel)
{
TrunkInfo info = GetTrunkInfo(vehicleModel);
if (info == null)
return false;
var m = RequestModelDimensions(objectModel);
if (m == null) return false;
var objectSize = m.Max - m.Min;
if (Math.Abs(objectSize.X) < info.Size.X &&
Math.Abs(objectSize.Y) < info.Size.Y &&
Math.Abs(objectSize.Z) < info.Size.Z)
return true;
else return false;
}
// TODO: Don't assume everything is square
private bool isThereEnoughPlaceInTrunk(int objectModel, NetHandle vehicle)
{
int vehModel = API.getEntityModel(vehicle);
if (!canModelFitInsideTrunk(objectModel, vehModel))
return false;
if (!API.hasEntityData(vehicle, TRUNK_KEY))
return true;
TrunkInfo info = GetTrunkInfo(vehModel);
var m = RequestModelDimensions(objectModel);
List<NetHandle> contents = API.getEntityData(vehicle, TRUNK_KEY);
float area = info.Size.X * info.Size.Y;
foreach (var obj in contents)
{
var om = RequestModelDimensions(API.getEntityModel(obj));
var osize = om.Max - om.Min;
area -= (float) Math.Abs(osize.X * osize.Y);
}
var msize = m.Max - m.Min;
return area > Math.Abs(msize.X * msize.Y);
}
private bool placeEntityInTrunkCentered(NetHandle target, NetHandle entity)
{
var info = GetTrunkInfo(API.getEntityModel(target));
if (info == null) return false;
if (!canModelFitInsideTrunk(API.getEntityModel(entity), API.getEntityModel(target)))
return false;
var m = RequestModelDimensions(API.getEntityModel(entity));
// Place in the center
API.attachEntityToEntity(entity, target, null, new Vector3(
info.Offset.X,
info.Offset.Y,
info.Offset.Z - m.Min.Z
), new Vector3(0, 0, 0));
if (!API.hasEntityData(target, TRUNK_KEY))
API.setEntityData(target, TRUNK_KEY, new List<NetHandle>());
List<NetHandle> contents = API.getEntityData(target, TRUNK_KEY);
contents.Add(entity);
API.setEntityData(target, TRUNK_KEY, contents);
return true;
}
private bool repackEntitiesInTrunk(NetHandle target)
{
var info = GetTrunkInfo(API.getEntityModel(target));
if (info == null) return false;
if (!API.hasEntityData(target, TRUNK_KEY))
return false;
List<NetHandle> contents = API.getEntityData(target, TRUNK_KEY);
if (contents.Count <= 1) return true;
float maxWidth = info.Size.X;
float maxHeight = info.Size.Y;
float currentHeight = 0;
float currentOffsetY = 0;
float currentOffsetX = 0;
// Order by height
foreach (var obj in contents.OrderByDescending(o =>
{
var model = API.getEntityModel(o);
var m = RequestModelDimensions(model);
var size = getModelSize(m.Max, m.Min);
return size.Y;
}))
{
var objModel = RequestModelDimensions(API.getEntityModel(obj));
var objSize = getModelSize(objModel.Max, objModel.Min);
if (objSize.X > maxWidth - currentOffsetX) // Too large to fit, place next level
{
currentOffsetY += currentHeight;
currentOffsetX = 0;
currentHeight = objSize.Y;
if (currentOffsetY + objSize.Y > maxHeight)
return false;
}
if (objSize.Y > currentHeight)
currentHeight = objSize.Y;
API.attachEntityToEntity(obj, target, null, new Vector3(
info.Offset.X - info.Size.X/2f + objModel.Max.X + currentOffsetX,
info.Offset.Y + info.Size.Y/2f - objModel.Max.Y - currentOffsetY,
info.Offset.Z - objModel.Min.Z
), new Vector3(0, 0, 0));
currentOffsetX += objSize.X;
}
return true;
}
// EXPORTED
public bool canPlaceStuff()
{
return API.getAllPlayers().Count > 0;
}
public void refreshTrunkEntities(NetHandle veh)
{
if (!API.hasEntityData(veh, TRUNK_KEY))
return;
List<NetHandle> contents = API.getEntityData(veh, TRUNK_KEY);
for (int i = contents.Count - 1; i >= 0; i--)
{
if (!API.doesEntityExist(contents[i]))
contents.RemoveAt(i);
}
API.setEntityData(veh, TRUNK_KEY, contents);
}
// DEBUG
[Command]
public void canfit(Client sender, string objname)
{
if (!sender.isInVehicle) return;
int modelHash = API.getHashKey(objname);
sender.sendChatMessage("Object " + objname + " can fit: " + canModelFitInsideTrunk(modelHash, API.getEntityModel(sender.vehicle)));
}
[Command]
public void clearTrunk(Client sender)
{
if (!sender.isInVehicle) return;
API.resetEntityData(sender.vehicle, TRUNK_KEY);
}
[Command]
public void place(Client sender, string objname)
{
if (!sender.isInVehicle) return;
int modelHash = API.getHashKey(objname);
var obj = API.createObject(modelHash, sender.position, new Vector3());
if (!placeEntityInTrunkCentered(sender.vehicle, obj) ||
!repackEntitiesInTrunk(sender.vehicle))
{
sender.sendChatMessage("Placement failed");
API.deleteEntity(obj);
}
refreshTrunkEntities(sender.vehicle);
}
[Command]
public void extra(Client sender, int n, bool state = false)
{
if (!sender.isInVehicle) return;
API.setVehicleExtra(sender.vehicle, n, state);
}
[Command]
public void placecar(Client sender, VehicleHash model)
{
if (!sender.isInVehicle) return;
var obj = API.createVehicle(model, sender.position, new Vector3(), 0, 0);
API.setEntityCollisionless(obj, true);
if (!placeEntityInTrunkCentered(sender.vehicle, obj) ||
!repackEntitiesInTrunk(sender.vehicle))
{
sender.sendChatMessage("Placement failed");
API.deleteEntity(obj);
}
refreshTrunkEntities(sender.vehicle);
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//==========================================================================
// File: MessageSmuggler.cs
//
// Summary: Implements objects necessary to smuggle messages across
// AppDomains and determine when it's possible.
//
//==========================================================================
using System;
using System.Collections;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
namespace System.Runtime.Remoting.Messaging
{
internal class MessageSmuggler
{
private static bool CanSmuggleObjectDirectly(Object obj)
{
if ((obj is String) ||
(obj.GetType() == typeof(void)) ||
obj.GetType().IsPrimitive)
{
return true;
}
return false;
} // CanSmuggleObjectDirectly
[System.Security.SecurityCritical] // auto-generated
protected static Object[] FixupArgs(Object[] args, ref ArrayList argsToSerialize)
{
Object[] newArgs = new Object[args.Length];
int total = args.Length;
for (int co = 0; co < total; co++)
{
newArgs[co] = FixupArg(args[co], ref argsToSerialize);
}
return newArgs;
} // FixupArgs
[System.Security.SecurityCritical] // auto-generated
protected static Object FixupArg(Object arg, ref ArrayList argsToSerialize)
{
// This method examines an argument and sees if it can be smuggled in some form.
// If it can directly be smuggled (i.e. it is a primitive or string), we
// just return the same object. If it's a marshal by ref object, we
// see if we can smuggle the obj ref. If it's a primitive or string array,
// we can smuggle a cloned copy of the array. In all other cases,
// we add it to the list of args we want serialized, and return a
// placeholder element (SerializedArg).
if (arg == null)
return null;
int index;
// IMPORTANT!!! This should be done first because CanSmuggleObjectDirectly
// calls GetType() and that would slow this down.
MarshalByRefObject mbo = arg as MarshalByRefObject;
if (mbo != null)
{
// We can only try to smuggle objref's for actual CLR objects
// or for RemotingProxy's.
if (!RemotingServices.IsTransparentProxy(mbo) ||
RemotingServices.GetRealProxy(mbo) is RemotingProxy)
{
ObjRef objRef = RemotingServices.MarshalInternal(mbo, null, null);
if (objRef.CanSmuggle())
{
if (!RemotingServices.IsTransparentProxy(mbo))
{
ServerIdentity srvId = (ServerIdentity)MarshalByRefObject.GetIdentity(mbo);
srvId.SetHandle();
objRef.SetServerIdentity(srvId.GetHandle());
objRef.SetDomainID(AppDomain.CurrentDomain.GetId());
}
ObjRef smugObjRef = objRef.CreateSmuggleableCopy();
smugObjRef.SetMarshaledObject();
return new SmuggledObjRef(smugObjRef);
}
}
// Add this arg to list of one's to serialize and return a placeholder
// since we couldn't smuggle the objref.
if (argsToSerialize == null)
argsToSerialize = new ArrayList();
index = argsToSerialize.Count;
argsToSerialize.Add(arg);
return new SerializedArg(index);
}
if (CanSmuggleObjectDirectly(arg))
return arg;
// if this is a primitive array, we can just make a copy.
// (IMPORTANT: We can directly use this copy from the
// other app domain, there is no reason to make another
// copy once we are on the other side)
Array array = arg as Array;
if (array != null)
{
Type elementType = array.GetType().GetElementType();
if (elementType.IsPrimitive || (elementType == typeof(String)))
return array.Clone();
}
// Add this arg to list of one's to serialize and return a placeholder.
if (argsToSerialize == null)
argsToSerialize = new ArrayList();
index = argsToSerialize.Count;
argsToSerialize.Add(arg);
return new SerializedArg(index);
} // FixupArg
[System.Security.SecurityCritical] // auto-generated
protected static Object[] UndoFixupArgs(Object[] args, ArrayList deserializedArgs)
{
Object[] newArgs = new Object[args.Length];
int total = args.Length;
for (int co = 0; co < total; co++)
{
newArgs[co] = UndoFixupArg(args[co], deserializedArgs);
}
return newArgs;
} // UndoFixupArgs
[System.Security.SecurityCritical] // auto-generated
protected static Object UndoFixupArg(Object arg, ArrayList deserializedArgs)
{
SmuggledObjRef smuggledObjRef = arg as SmuggledObjRef;
if (smuggledObjRef != null)
{
// We call GetRealObject here ... that covers any
// special unmarshaling we need to do for _ComObject
return smuggledObjRef.ObjRef.GetRealObjectHelper();
}
SerializedArg serializedArg = arg as SerializedArg;
if (serializedArg != null)
{
return deserializedArgs[serializedArg.Index];
}
return arg;
} // UndoFixupArg
// returns number of entries added to argsToSerialize
[System.Security.SecurityCritical] // auto-generated
protected static int StoreUserPropertiesForMethodMessage(
IMethodMessage msg,
ref ArrayList argsToSerialize)
{
IDictionary properties = msg.Properties;
MessageDictionary dict = properties as MessageDictionary;
if (dict != null)
{
if (dict.HasUserData())
{
int co = 0;
foreach (DictionaryEntry entry in dict.InternalDictionary)
{
if (argsToSerialize == null)
argsToSerialize = new ArrayList();
argsToSerialize.Add(entry);
co++;
}
return co;
}
else
{
return 0;
}
}
else
{
// <
int co = 0;
foreach (DictionaryEntry entry in properties)
{
if (argsToSerialize == null)
argsToSerialize = new ArrayList();
argsToSerialize.Add(entry);
co++;
}
return co;
}
} // StoreUserPropertiesForMethodMessage
//
// Helper classes used to smuggle transformed arguments
//
protected class SerializedArg
{
private int _index;
public SerializedArg(int index)
{
_index = index;
}
public int Index { get { return _index; } }
}
//
// end of Helper classes used to smuggle transformed arguments
//
} // class MessageSmuggler
// stores an object reference
internal class SmuggledObjRef
{
[System.Security.SecurityCritical] // auto-generated
ObjRef _objRef;
[System.Security.SecurityCritical] // auto-generated
public SmuggledObjRef(ObjRef objRef)
{
_objRef = objRef;
}
public ObjRef ObjRef
{
[System.Security.SecurityCritical] // auto-generated
get { return _objRef; }
}
} // SmuggledObjRef
internal class SmuggledMethodCallMessage : MessageSmuggler
{
private String _uri;
private String _methodName;
private String _typeName;
private Object[] _args;
private byte[] _serializedArgs = null;
#if false // This field isn't currently used
private Object[] _serializerSmuggledArgs = null;
#endif
// other things that might need to go through serializer
private SerializedArg _methodSignature = null;
private SerializedArg _instantiation = null;
private Object _callContext = null; // either a call id string or a SerializedArg pointing to CallContext object
private int _propertyCount = 0; // <n> = # of user properties in dictionary
// note: first <n> entries in _deserializedArgs will be the property entries
// always use this helper method to create
[System.Security.SecurityCritical] // auto-generated
internal static SmuggledMethodCallMessage SmuggleIfPossible(IMessage msg)
{
IMethodCallMessage mcm = msg as IMethodCallMessage;
if (mcm == null)
return null;
return new SmuggledMethodCallMessage(mcm);
}
// hide default constructor
private SmuggledMethodCallMessage(){}
[System.Security.SecurityCritical] // auto-generated
private SmuggledMethodCallMessage(IMethodCallMessage mcm)
{
_uri = mcm.Uri;
_methodName = mcm.MethodName;
_typeName = mcm.TypeName;
ArrayList argsToSerialize = null;
IInternalMessage iim = mcm as IInternalMessage;
// user properties (everything but special entries)
if ((iim == null) || iim.HasProperties())
_propertyCount = StoreUserPropertiesForMethodMessage(mcm, ref argsToSerialize);
// generic instantiation information
if (mcm.MethodBase.IsGenericMethod)
{
Type[] inst = mcm.MethodBase.GetGenericArguments();
if (inst != null && inst.Length > 0)
{
if (argsToSerialize == null)
argsToSerialize = new ArrayList();
_instantiation = new SerializedArg(argsToSerialize.Count);
argsToSerialize.Add(inst);
}
}
// handle method signature
if (RemotingServices.IsMethodOverloaded(mcm))
{
if (argsToSerialize == null)
argsToSerialize = new ArrayList();
_methodSignature = new SerializedArg(argsToSerialize.Count);
argsToSerialize.Add(mcm.MethodSignature);
}
// handle call context
LogicalCallContext lcc = mcm.LogicalCallContext;
if (lcc == null)
{
_callContext = null;
}
else
if (lcc.HasInfo)
{
if (argsToSerialize == null)
argsToSerialize = new ArrayList();
_callContext = new SerializedArg(argsToSerialize.Count);
argsToSerialize.Add(lcc);
}
else
{
// just smuggle the call id string
_callContext = lcc.RemotingData.LogicalCallID;
}
_args = FixupArgs(mcm.Args, ref argsToSerialize);
if (argsToSerialize != null)
{
//MemoryStream argStm = CrossAppDomainSerializer.SerializeMessageParts(argsToSerialize, out _serializerSmuggledArgs);
MemoryStream argStm = CrossAppDomainSerializer.SerializeMessageParts(argsToSerialize);
_serializedArgs = argStm.GetBuffer();
}
} // SmuggledMethodCallMessage
// returns a list of the deserialized arguments
[System.Security.SecurityCritical] // auto-generated
internal ArrayList FixupForNewAppDomain()
{
ArrayList deserializedArgs = null;
if (_serializedArgs != null)
{
deserializedArgs =
CrossAppDomainSerializer.DeserializeMessageParts(
new MemoryStream(_serializedArgs));
//deserializedArgs =
// CrossAppDomainSerializer.DeserializeMessageParts(
// new MemoryStream(_serializedArgs), _serializerSmuggledArgs);
_serializedArgs = null;
}
return deserializedArgs;
} // FixupForNewAppDomain
internal String Uri { get { return _uri; } }
internal String MethodName { get { return _methodName; } }
internal String TypeName { get { return _typeName; } }
internal Type[] GetInstantiation(ArrayList deserializedArgs)
{
if (_instantiation != null)
return (Type[])deserializedArgs[_instantiation.Index];
else
return null;
}
internal Object[] GetMethodSignature(ArrayList deserializedArgs)
{
if (_methodSignature != null)
return (Object[])deserializedArgs[_methodSignature.Index];
else
return null;
}
[System.Security.SecurityCritical] // auto-generated
internal Object[] GetArgs(ArrayList deserializedArgs)
{
return UndoFixupArgs(_args, deserializedArgs);
} // GetArgs
[System.Security.SecurityCritical] // auto-generated
internal LogicalCallContext GetCallContext(ArrayList deserializedArgs)
{
if (_callContext == null)
{
return null;
}
if (_callContext is String)
{
LogicalCallContext callContext = new LogicalCallContext();
callContext.RemotingData.LogicalCallID = (String)_callContext;
return callContext;
}
else
return (LogicalCallContext)deserializedArgs[((SerializedArg)_callContext).Index];
}
internal int MessagePropertyCount
{
get { return _propertyCount; }
}
internal void PopulateMessageProperties(IDictionary dict, ArrayList deserializedArgs)
{
for (int co = 0; co < _propertyCount; co++)
{
DictionaryEntry de = (DictionaryEntry)deserializedArgs[co];
dict[de.Key] = de.Value;
}
}
} // class SmuggledMethodCallMessage
internal class SmuggledMethodReturnMessage : MessageSmuggler
{
private Object[] _args;
private Object _returnValue;
private byte[] _serializedArgs = null;
#if false // This field isn't currently used
private Object[] _serializerSmuggledArgs = null;
#endif
// other things that might need to go through serializer
private SerializedArg _exception = null;
private Object _callContext = null; // either a call id string or a SerializedArg pointing to CallContext object
private int _propertyCount; // <n> = # of user properties in dictionary
// note: first <n> entries in _deserializedArgs will be the property entries
// always use this helper method to create
[System.Security.SecurityCritical] // auto-generated
internal static SmuggledMethodReturnMessage SmuggleIfPossible(IMessage msg)
{
IMethodReturnMessage mrm = msg as IMethodReturnMessage;
if (mrm == null)
return null;
return new SmuggledMethodReturnMessage(mrm);
}
// hide default constructor
private SmuggledMethodReturnMessage(){}
[System.Security.SecurityCritical] // auto-generated
private SmuggledMethodReturnMessage(IMethodReturnMessage mrm)
{
ArrayList argsToSerialize = null;
ReturnMessage retMsg = mrm as ReturnMessage;
// user properties (everything but special entries)
if ((retMsg == null) || retMsg.HasProperties())
_propertyCount = StoreUserPropertiesForMethodMessage(mrm, ref argsToSerialize);
// handle exception
Exception excep = mrm.Exception;
if (excep != null)
{
if (argsToSerialize == null)
argsToSerialize = new ArrayList();
_exception = new SerializedArg(argsToSerialize.Count);
argsToSerialize.Add(excep);
}
// handle call context
LogicalCallContext lcc = mrm.LogicalCallContext;
if (lcc == null)
{
_callContext = null;
}
else
if (lcc.HasInfo)
{
if (lcc.Principal != null)
lcc.Principal = null;
if (argsToSerialize == null)
argsToSerialize = new ArrayList();
_callContext = new SerializedArg(argsToSerialize.Count);
argsToSerialize.Add(lcc);
}
else
{
// just smuggle the call id string
_callContext = lcc.RemotingData.LogicalCallID;
}
_returnValue = FixupArg(mrm.ReturnValue, ref argsToSerialize);
_args = FixupArgs(mrm.Args, ref argsToSerialize);
if (argsToSerialize != null)
{
MemoryStream argStm = CrossAppDomainSerializer.SerializeMessageParts(argsToSerialize);
//MemoryStream argStm = CrossAppDomainSerializer.SerializeMessageParts(argsToSerialize, out _serializerSmuggledArgs);
_serializedArgs = argStm.GetBuffer();
}
} // SmuggledMethodReturnMessage
[System.Security.SecurityCritical] // auto-generated
internal ArrayList FixupForNewAppDomain()
{
ArrayList deserializedArgs = null;
if (_serializedArgs != null)
{
deserializedArgs =
CrossAppDomainSerializer.DeserializeMessageParts(
new MemoryStream(_serializedArgs));
//deserializedArgs =
// CrossAppDomainSerializer.DeserializeMessageParts(
// new MemoryStream(_serializedArgs), _serializerSmuggledArgs);
_serializedArgs = null;
}
return deserializedArgs;
} // FixupForNewAppDomain
[System.Security.SecurityCritical] // auto-generated
internal Object GetReturnValue(ArrayList deserializedArgs)
{
return UndoFixupArg(_returnValue, deserializedArgs);
} // GetReturnValue
[System.Security.SecurityCritical] // auto-generated
internal Object[] GetArgs(ArrayList deserializedArgs)
{
Object[] obj = UndoFixupArgs(_args, deserializedArgs);
return obj;
} // GetArgs
internal Exception GetException(ArrayList deserializedArgs)
{
if (_exception != null)
return (Exception)deserializedArgs[_exception.Index];
else
return null;
} // Exception
[System.Security.SecurityCritical] // auto-generated
internal LogicalCallContext GetCallContext(ArrayList deserializedArgs)
{
if (_callContext == null)
{
return null;
}
if (_callContext is String)
{
LogicalCallContext callContext = new LogicalCallContext();
callContext.RemotingData.LogicalCallID = (String)_callContext;
return callContext;
}
else
return (LogicalCallContext)deserializedArgs[((SerializedArg)_callContext).Index];
}
internal int MessagePropertyCount
{
get { return _propertyCount; }
}
internal void PopulateMessageProperties(IDictionary dict, ArrayList deserializedArgs)
{
for (int co = 0; co < _propertyCount; co++)
{
DictionaryEntry de = (DictionaryEntry)deserializedArgs[co];
dict[de.Key] = de.Value;
}
}
} // class SmuggledMethodReturnMessage
} // namespace System.Runtime.Remoting.Messaging
| |
#region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using NodaTime.Utility;
namespace NodaTime.Fields
{
/// <summary>
/// Defines the calculation engine for date and time fields.
/// The interface defines a set of methods that manipulate a LocalInstant
/// with regards to a single field, such as monthOfYear or secondOfMinute.
/// </summary>
[Serializable]
internal abstract class DateTimeField
{
private readonly DateTimeFieldType fieldType;
private readonly DurationField durationField;
private readonly bool isSupported;
private readonly bool isLenient;
protected DateTimeField(DateTimeFieldType fieldType, DurationField durationField)
: this(fieldType, durationField, false, true)
{
}
protected DateTimeField(DateTimeFieldType fieldType, DurationField durationField,
bool isLenient, bool isSupported)
{
this.fieldType = Preconditions.CheckNotNull(fieldType, "fieldType");
this.durationField = Preconditions.CheckNotNull(durationField, "durationField");
this.isLenient = isLenient;
this.isSupported = isSupported;
}
/// <summary>
/// Get the type of the field.
/// </summary>
internal DateTimeFieldType FieldType { get { return fieldType; } }
/// <summary>
/// Get the name of the field.
/// </summary>
/// <remarks>
/// By convention, names follow a pattern of "dddOfRrr", where "ddd" represents
/// the (singular) duration unit field name and "Rrr" represents the (singular)
/// duration range field name. If the range field is not applicable, then
/// the name of the field is simply the (singular) duration field name.
/// </remarks>
internal virtual string Name { get { return FieldType.ToString(); } }
/// <summary>
/// Gets the duration per unit value of this field, or UnsupportedDurationField if field has no duration.
/// For example, if this
/// field represents "hour of day", then the duration is an hour.
/// </summary>
internal DurationField DurationField { get { return durationField; } }
/// <summary>
/// Returns the range duration of this field. For example, if this field
/// represents "hour of day", then the range duration is a day.
/// </summary>
internal abstract DurationField RangeDurationField { get; }
/// <summary>
/// Whether or not this is a supported field.
/// </summary>
internal bool IsSupported { get { return isSupported; } }
/// <summary>
/// Returns true if the set method is lenient. If so, it accepts values that
/// are out of bounds. For example, a lenient day of month field accepts 32
/// for January, converting it to February 1.
/// </summary>
internal bool IsLenient { get { return isLenient; } }
#region Values
/// <summary>
/// Get the value of this field from the local instant.
/// </summary>
/// <param name="localInstant">The local instant to query</param>
/// <returns>The value of the field, in the units of the field</returns>
internal virtual int GetValue(LocalInstant localInstant)
{
return (int)GetInt64Value(localInstant);
}
/// <summary>
/// Get the value of this field from the local instant.
/// </summary>
/// <param name="localInstant">The local instant to query</param>
/// <returns>The value of the field, in the units of the field</returns>
internal abstract long GetInt64Value(LocalInstant localInstant);
/// <summary>
/// Adds a value (which may be negative) to the local instant,
/// wrapping within this field.
/// </summary>
/// <param name="localInstant">The local instant to add to</param>
/// <param name="value">The value to add, in the units of the field</param>
/// <returns>The updated local instant</returns>
/// <remarks>
/// <para>
/// The value will be added to this field. If the value is too large to be
/// added solely to this field then it wraps. Larger fields are always
/// unaffected. Smaller fields should be unaffected, except where the
/// result would be an invalid value for a smaller field. In this case the
/// smaller field is adjusted to be in range. For example, in the ISO chronology:
/// </para>
/// <list type="bullet">
/// <item>2000-08-20 AddWrapField six months is 2000-02-20</item>
/// <item>2000-08-20 AddWrapField twenty months is 2000-04-20</item>
/// <item>2000-08-20 AddWrapField minus nine months is 2000-11-20</item>
/// <item>2001-01-31 AddWrapField one month is 2001-02-28</item>
/// <item>2001-01-31 AddWrapField two months is 2001-03-31</item>
/// </list>
/// </remarks>
internal virtual LocalInstant AddWrapField(LocalInstant localInstant, int value)
{
int current = GetValue(localInstant);
int wrapped = FieldUtils.GetWrappedValue(current, value, (int)GetMinimumValue(localInstant), (int)GetMaximumValue(localInstant));
return SetValue(localInstant, wrapped);
}
/// <summary>
/// Sets a value in the local instant supplied.
/// <para>
/// The value of this field will be set.
/// If the value is invalid, an exception if thrown.
/// </para>
/// <para>
/// If setting this field would make other fields invalid, then those fields
/// may be changed. For example if the current date is the 31st January, and
/// the month is set to February, the day would be invalid. Instead, the day
/// would be changed to the closest value - the 28th/29th February as appropriate.
/// </para>
/// </summary>
/// <param name="localInstant">The local instant to set in</param>
/// <param name="value">The value to set, in the units of the field</param>
/// <returns>The updated local instant</returns>
internal abstract LocalInstant SetValue(LocalInstant localInstant, long value);
#endregion
#region Leap
/// <summary>
/// Defaults to non-leap.
/// </summary>
internal virtual bool IsLeap(LocalInstant localInstant)
{
return false;
}
/// <summary>
/// Defaults to 0.
/// </summary>
internal virtual int GetLeapAmount(LocalInstant localInstant)
{
return 0;
}
/// <summary>
/// Defaults to null, i.e. no leap duration field.
/// </summary>
internal virtual DurationField LeapDurationField { get { return null; } }
#endregion
#region Ranges
/// <summary>
/// Defaults to the absolute maximum for the field.
/// </summary>
internal virtual long GetMaximumValue(LocalInstant localInstant)
{
return GetMaximumValue();
}
/// <summary>
/// Get the maximum allowable value for this field.
/// </summary>
/// <returns>The maximum valid value for this field, in the units of the field</returns>
internal abstract long GetMaximumValue();
/// <summary>
/// Defaults to the absolute minimum for the field.
/// </summary>
internal virtual long GetMinimumValue(LocalInstant localInstant)
{
return GetMinimumValue();
}
/// <summary>
/// Get the minimum allowable value for this field.
/// </summary>
/// <returns>The minimum valid value for this field, in the units of the field</returns>
internal abstract long GetMinimumValue();
#endregion
#region Rounding
/// <summary>
/// Round to the lowest whole unit of this field. After rounding, the value
/// of this field and all fields of a higher magnitude are retained. The
/// fractional ticks that cannot be expressed in whole increments of this
/// field are set to minimum.
/// <para>
/// For example, a datetime of 2002-11-02T23:34:56.789, rounded to the
/// lowest whole hour is 2002-11-02T23:00:00.000.
/// </para>
/// </summary>
/// <param name="localInstant">The local instant to round</param>
/// <returns>Rounded local instant</returns>
internal abstract LocalInstant RoundFloor(LocalInstant localInstant);
/// <summary>
/// Round to the highest whole unit of this field. The value of this field
/// and all fields of a higher magnitude may be incremented in order to
/// achieve this result. The fractional ticks that cannot be expressed in
/// whole increments of this field are set to minimum.
/// <para>
/// For example, a datetime of 2002-11-02T23:34:56.789, rounded to the
/// highest whole hour is 2002-11-03T00:00:00.000.
/// </para>
/// </summary>
/// <param name="localInstant">The local instant to round</param>
/// <returns>Rounded local instant</returns>
internal virtual LocalInstant RoundCeiling(LocalInstant localInstant)
{
LocalInstant newInstant = RoundFloor(localInstant);
if (newInstant != localInstant)
{
newInstant = DurationField.Add(newInstant, 1);
}
return newInstant;
}
/// <summary>
/// Round to the nearest whole unit of this field. If the given local instant
/// is closer to the floor or is exactly halfway, this function
/// behaves like RoundFloor. If the local instant is closer to the
/// ceiling, this function behaves like RoundCeiling.
/// </summary>
/// <param name="localInstant">The local instant to round</param>
/// <returns>Rounded local instant</returns>
internal virtual LocalInstant RoundHalfFloor(LocalInstant localInstant)
{
LocalInstant floor = RoundFloor(localInstant);
LocalInstant ceiling = RoundCeiling(localInstant);
Duration diffFromFloor = localInstant - floor;
Duration diffToCeiling = ceiling - localInstant;
// Closer to the floor, or halfway - round floor
return diffFromFloor <= diffToCeiling ? floor : ceiling;
}
/// <summary>
/// Round to the nearest whole unit of this field. If the given local instant
/// is closer to the floor, this function behaves like RoundFloor. If
/// the local instant is closer to the ceiling or is exactly halfway,
/// this function behaves like RoundCeiling.
/// </summary>
/// <param name="localInstant">The local instant to round</param>
/// <returns>Rounded local instant</returns>
internal virtual LocalInstant RoundHalfCeiling(LocalInstant localInstant)
{
LocalInstant floor = RoundFloor(localInstant);
LocalInstant ceiling = RoundCeiling(localInstant);
long diffFromFloor = localInstant.Ticks - floor.Ticks;
long diffToCeiling = ceiling.Ticks - localInstant.Ticks;
// Closer to the ceiling, or halfway - round ceiling
return diffToCeiling <= diffFromFloor ? ceiling : floor;
}
/// <summary>
/// Round to the nearest whole unit of this field. If the given local instant
/// is closer to the floor, this function behaves like RoundFloor. If
/// the local instant is closer to the ceiling, this function behaves
/// like RoundCeiling.
/// </summary>
/// <param name="localInstant">The local instant to round</param>
/// <returns>Rounded local instant</returns>
internal virtual LocalInstant RoundHalfEven(LocalInstant localInstant)
{
LocalInstant floor = RoundFloor(localInstant);
LocalInstant ceiling = RoundCeiling(localInstant);
Duration diffFromFloor = localInstant - floor;
Duration diffToCeiling = ceiling - localInstant;
// Closer to the floor - round floor
if (diffFromFloor < diffToCeiling)
{
return floor;
}
// Closer to the ceiling - round ceiling
else if (diffToCeiling < diffFromFloor)
{
return ceiling;
}
else
{
// Round to the instant that makes this field even. If both values
// make this field even (unlikely), favor the ceiling.
return (GetInt64Value(ceiling) & 1) == 0 ? ceiling : floor;
}
}
/// <summary>
/// Returns the fractional duration of this field. In other words,
/// calling Remainder returns the duration that RoundFloor would subtract.
/// <para>
/// For example, on a datetime of 2002-11-02T23:34:56.789, the remainder by
/// hour is 34 minutes and 56.789 seconds.
/// </para>
/// </summary>
/// <param name="localInstant">The local instant to get the remainder</param>
/// <returns>Remainder duration</returns>
internal virtual Duration Remainder(LocalInstant localInstant)
{
return localInstant - RoundFloor(localInstant);
}
#endregion
public override string ToString()
{
return fieldType.ToString();
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace EA4S.Assessment
{
internal class SortingDragManager : IDragManager, ITickable
{
private IAudioManager audioManager;
private ICheckmarkWidget widget;
public SortingDragManager( IAudioManager audioManager, ICheckmarkWidget widget)
{
this.audioManager = audioManager;
this.widget = widget;
ResetRound();
}
private bool dragOnly = false;
public void EnableDragOnly()
{
dragOnly = true;
ticking = true;
TimeEngine.AddTickable(this);
foreach (var a in answers)
a.Enable();
}
List< SortableBehaviour> answers = null;
// This should be called onlye once
public void AddElements(
List< PlaceholderBehaviour> placeholders,
List< AnswerBehaviour> answers,
List< IQuestion> questions)
{
this.answers = BehaviourFromAnswers( answers);
}
private bool searchForBuckets = false;
private bool objectFlying = false;
private bool returnedAllAnswered = false;
private void FindBuckets()
{
// Sorted array by position
// Ascending => X--->
var positions = UnityEngine.Object.FindObjectsOfType< SortingTicket>()
.OrderByDescending( x => x.transform.position.x).ToArray();
this.positions = new Vector3[positions.Length];
for (int i = 0; i < positions.Length; i++)
this.positions[i] = positions[i].transform.localPosition;
sortables = new SortableBehaviour[ positions.Length];
for (int i = 0; i < sortables.Length; i++)
sortables[i] = null;
searchForBuckets = false;
}
private List< SortableBehaviour> BehaviourFromAnswers( List< AnswerBehaviour> answers)
{
var list = new List< SortableBehaviour>();
foreach (var a in answers)
{
var droppable = a.gameObject.AddComponent< SortableBehaviour>();
droppable.SetDragManager( this);
list.Add( droppable);
}
return list;
}
IEnumerator AllCorrectCoroutine()
{
audioManager.PlaySound( Sfx.StampOK);
yield return TimeEngine.Wait(0.4f);
widget.Show(true);
yield return TimeEngine.Wait(1.0f);
}
public bool AllAnswered()
{
if (dragOnly || objectFlying || returnedAllAnswered)
return false; // When antura is animating we should not complete the assessment
if (sortables == null)
return false;
IAnswer[] answer = new IAnswer[ answers.Count];
IAnswer[] answerSorted = new IAnswer[ answers.Count];
//Answers like are actually sorted
var sorted = sortables.OrderByDescending( x => x.transform.position.x).ToArray();
int index = 0;
foreach( var a in answers)
{
answerSorted[ index] = sorted[ index].gameObject.GetComponent< AnswerBehaviour>().GetAnswer();
index++;
}
// Answers sorted by ticket
answer = answerSorted.OrderBy( a => a.GetTicket()).ToArray();
for(int i=0; i<answer.Length; i++)
{
Debug.Log( " answer:" + answer[i].Data().Id +
" sorted:" + answerSorted[i].Data().Id);
}
for(int i=0; i < answer.Length; i++)
{
//If sorted version has letter shapes in wrong positions we know we didn't find solution
if (answer[i].Equals( answerSorted[i]) == false)
return false;
}
//Debug.Log("Return TRUE");
// two words identical!
returnedAllAnswered = true;
Coroutine.Start( AllCorrectCoroutine());
return true;
}
public void Enable()
{
dragOnly = false;
}
public void ResetRound()
{
answers = null;
}
IDroppable droppable = null;
// ALL NEEDED EVENTS ARE HERE
public void StartDragging( IDroppable droppable)
{
if (this.droppable != null)
return;
objectFlying = true;
audioManager.PlaySound( Sfx.UIPopup);
this.droppable = droppable;
droppable.StartDrag ( x => RemoveFromUpdate());
}
void RemoveFromUpdate()
{
droppable.StopDrag();
droppable = null;
}
public void StopDragging( IDroppable droppable)
{
objectFlying = false;
if (this.droppable == droppable && droppable != null)
{
audioManager.PlaySound( Sfx.UIPopup);
RemoveFromUpdate();
MoveStuffToPosition();
}
}
bool ticking = false;
Vector3[] positions;
SortableBehaviour[] sortables;
public bool Update(float deltaTime)
{
if (searchForBuckets)
FindBuckets();
if (droppable != null)
{
var pos = Camera.main.ScreenToWorldPoint( Input.mousePosition);
pos.z = 5;
droppable.GetTransform().localPosition = pos;
}
MoveStuffToPosition();
return !ticking;
}
private void MoveStuffToPosition()
{
if (sortables == null)
return;
if (returnedAllAnswered)
return;
sortables = answers.OrderByDescending(x => x.transform.position.x).ToArray();
for (int i = 0; i < sortables.Length; i++)
{
var s = sortables[i];
//DO NOT TWEEN THE OBJECT WE ARE DRAGGIN
if ((s as IDroppable) != droppable /*&& s.SetSortIndex(i)*/)
{
s.SetSortIndex(i);
s.Move( positions[i], 0.3f);
}
}
}
public void DisableInput()
{
foreach (var a in answers)
a.Disable();
}
public void EnableInput()
{
foreach (var a in answers)
a.Enable();
}
public void RemoveDraggables()
{
dragOnly = true;
if (droppable != null)
{
droppable.StopDrag();
droppable = null;
}
}
public void OnAnswerAdded()
{
searchForBuckets = true;
returnedAllAnswered = false;
sortables = null;
}
}
}
| |
#region Copyright (c) 2014-2016 DevCloud Solutions
/*
{********************************************************************************}
{ }
{ Copyright (c) 2014-2016 DevCloud Solutions }
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{********************************************************************************}
*/
#endregion
using System;
using System.Linq;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Updating;
using XAF_Bootstrap.BusinessObjects;
using System.IO;
using System.Reflection;
using System.Web;
namespace XAF_Bootstrap.DatabaseUpdate
{
public class Updater : ModuleUpdater
{
public static XAFBootstrapConfiguration Configuration(IObjectSpace ObjectSpace)
{
var configuration = ObjectSpace.FindObject<XAFBootstrapConfiguration>(null, true);
if (configuration == null)
{
configuration = ObjectSpace.CreateObject<XAFBootstrapConfiguration>();
configuration.Theme = "Paper";
}
return configuration;
}
private static void CopyResource(string resourceName, string file, Boolean copyOnlyIfNotExists = true, Assembly assembly = null)
{
if (assembly == null)
assembly = Assembly.GetExecutingAssembly();
using (Stream resource = assembly
.GetManifestResourceStream(resourceName))
{
if (resource == null)
{
throw new ArgumentException("No such resource", resourceName);
}
var dir = Path.GetDirectoryName(file);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
try
{
if (!copyOnlyIfNotExists || (copyOnlyIfNotExists && !File.Exists(file)))
using (Stream output = new FileStream(file, FileMode.Create, FileAccess.ReadWrite))
resource.CopyTo(output);
}
catch (Exception exc)
{
}
}
}
public static void CheckResource(string location, string resourceName, Boolean copyOnlyIfNotExists = true, String Path = "XAF_Bootstrap.Content", Assembly assembly = null, String CustomDirectory = "")
{
CopyResource(String.Format("{2}.{0}.{1}", location, resourceName, Path), (CustomDirectory != "" ? CustomDirectory : AssemblyDirectory + location.Replace(".", "\\")) + "\\" + resourceName, copyOnlyIfNotExists, assembly);
}
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
var path = Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path)).Split(new String[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
return String.Join("\\", path.Take(path.Length - 1)) + "\\";
}
}
public static void CheckResources()
{
Boolean versionIsNewer = false;
using (var resource = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("XAF_Bootstrap.Content.xaf_bootstrap_version.txt"))
{
using (var reader = new StreamReader(resource))
{
var version = int.Parse(reader.ReadToEnd());
if (!File.Exists(AssemblyDirectory + "xaf_bootstrap_version.txt"))
versionIsNewer = true;
else
{
try {
using (var fs = new FileStream(AssemblyDirectory + "xaf_bootstrap_version.txt", FileMode.Open, FileAccess.Read))
{
using (var data = new StreamReader(fs))
{
var current = 0;
if (int.TryParse(data.ReadToEnd(), out current))
versionIsNewer = version > current;
}
}
} catch { }
}
try {
using (Stream fs = new FileStream(AssemblyDirectory + "xaf_bootstrap_version.txt", FileMode.Create, FileAccess.ReadWrite))
{
using (var res = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("XAF_Bootstrap.Content.xaf_bootstrap_version.txt"))
{
res.CopyTo(fs);
}
}
} catch { }
}
}
if (versionIsNewer)
{
CheckResource("bootstrap_js", "jquery-1.11.2.min.js");
CheckResource("bootstrap_js", "bootstrap.min.js", false);
CheckResource("bootstrap_js", "bootstrap-datetimepicker.min.js");
CheckResource("bootstrap_js", "bootstrap-select.min.js");
CheckResource("bootstrap_js", "moment-with-locales.min.js");
CheckResource("bootstrap_js", "bootstrap-dx.js", false);
CheckResource("bootstrap_js", "jquery.floatThead.js");
CheckResource("bootstrap_css", "bootstrap.min.css");
CheckResource("bootstrap_css", "bootstrap-datetimepicker.css", false);
CheckResource("bootstrap_css", "bootstrap-select.min.css", false);
CheckResource("bootstrap_css", "bootstrap-dx.css", false);
CheckResource("bootstrap_css", "bootstrap-custom.css");
CheckResource("bootstrap_css", "xb-mega-menu.css", false);
CheckResource("bootstrap_css", "font-awesome.min.css", false);
CheckResource("bootstrap_images", "logon_bg.jpg");
CheckResource("fonts", "glyphicons-halflings-regular.eot", false);
CheckResource("fonts", "glyphicons-halflings-regular.svg", false);
CheckResource("fonts", "glyphicons-halflings-regular.ttf", false);
CheckResource("fonts", "glyphicons-halflings-regular.woff", false);
CheckResource("fonts", "glyphicons-halflings-regular.woff2", false);
CheckResource("fonts", "fontawesome-webfont.eot", false);
CheckResource("fonts", "fontawesome-webfont.svg", false);
CheckResource("fonts", "fontawesome-webfont.ttf", false);
CheckResource("fonts", "fontawesome-webfont.woff", false);
CheckResource("fonts", "fontawesome-webfont.woff2", false);
CheckResource("bootstrap_themes.Cerulean.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Cerulean", "preview.jpg");
CheckResource("bootstrap_themes.Cosmo.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Cosmo", "preview.jpg");
CheckResource("bootstrap_themes.Custom.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Custom", "preview.jpg");
CheckResource("bootstrap_themes.Cyborg.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Cyborg", "preview.jpg");
CheckResource("bootstrap_themes.Darkly.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Darkly", "preview.jpg");
CheckResource("bootstrap_themes.Flatly.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Flatly", "preview.jpg");
CheckResource("bootstrap_themes.Lumen.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Lumen", "preview.jpg");
CheckResource("bootstrap_themes.Paper.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Paper.bootstrap_css", "bootstrap-custom.css", false);
CheckResource("bootstrap_themes.Paper", "preview.jpg");
CheckResource("bootstrap_themes.Readable.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Readable", "preview.jpg");
CheckResource("bootstrap_themes.Simpex.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Simpex", "preview.jpg");
CheckResource("bootstrap_themes.Slate.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Slate", "preview.jpg");
CheckResource("bootstrap_themes.Spacelab.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Spacelab", "preview.jpg");
CheckResource("bootstrap_themes.Sandstone.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Sandstone", "preview.jpg");
CheckResource("bootstrap_themes.Sandstone.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Sandstone", "preview.jpg");
CheckResource("bootstrap_themes.United.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.United", "preview.jpg");
CheckResource("bootstrap_themes.Yeti.bootstrap_css", "bootstrap.min.css", false);
CheckResource("bootstrap_themes.Yeti", "preview.jpg");
}
}
public Updater(IObjectSpace objectSpace, Version currentDBVersion) :
base(objectSpace, currentDBVersion)
{
if (ObjectSpace.CanInstantiate(typeof(XAFBootstrapConfiguration)))
{
Configuration(ObjectSpace);
}
if (HttpContext.Current == null || HttpContext.Current.Server == null)
CheckResources();
}
public override void UpdateDatabaseAfterUpdateSchema()
{
base.UpdateDatabaseAfterUpdateSchema();
}
public override void UpdateDatabaseBeforeUpdateSchema()
{
base.UpdateDatabaseBeforeUpdateSchema();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.