context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
#if UNITY_EDITOR || !(UNITY_WEBPLAYER || UNITY_WEBGL)
#region License
/*
* AuthenticationResponse.cs
*
* ParseBasicCredentials is derived from System.Net.HttpListenerContext.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2013-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
namespace WebSocketSharp.Net
{
internal class AuthenticationResponse : AuthenticationBase
{
#region Private Fields
private uint _nonceCount;
#endregion
#region Private Constructors
private AuthenticationResponse (AuthenticationSchemes scheme, NameValueCollection parameters)
: base (scheme, parameters)
{
}
#endregion
#region Internal Constructors
internal AuthenticationResponse (NetworkCredential credentials)
: this (AuthenticationSchemes.Basic, new NameValueCollection (), credentials, 0)
{
}
internal AuthenticationResponse (
AuthenticationChallenge challenge, NetworkCredential credentials, uint nonceCount)
: this (challenge.Scheme, challenge.Parameters, credentials, nonceCount)
{
}
internal AuthenticationResponse (
AuthenticationSchemes scheme,
NameValueCollection parameters,
NetworkCredential credentials,
uint nonceCount)
: base (scheme, parameters)
{
Parameters["username"] = credentials.UserName;
Parameters["password"] = credentials.Password;
Parameters["uri"] = credentials.Domain;
_nonceCount = nonceCount;
if (scheme == AuthenticationSchemes.Digest)
initAsDigest ();
}
#endregion
#region Internal Properties
internal uint NonceCount {
get {
return _nonceCount < UInt32.MaxValue
? _nonceCount
: 0;
}
}
#endregion
#region Public Properties
public string Cnonce {
get {
return Parameters["cnonce"];
}
}
public string Nc {
get {
return Parameters["nc"];
}
}
public string Password {
get {
return Parameters["password"];
}
}
public string Response {
get {
return Parameters["response"];
}
}
public string Uri {
get {
return Parameters["uri"];
}
}
public string UserName {
get {
return Parameters["username"];
}
}
#endregion
#region Private Methods
private static string createA1 (string username, string password, string realm)
{
return String.Format ("{0}:{1}:{2}", username, realm, password);
}
private static string createA1 (
string username, string password, string realm, string nonce, string cnonce)
{
return String.Format (
"{0}:{1}:{2}", hash (createA1 (username, password, realm)), nonce, cnonce);
}
private static string createA2 (string method, string uri)
{
return String.Format ("{0}:{1}", method, uri);
}
private static string createA2 (string method, string uri, string entity)
{
return String.Format ("{0}:{1}:{2}", method, uri, hash (entity));
}
private static string hash (string value)
{
var src = Encoding.UTF8.GetBytes (value);
var md5 = MD5.Create ();
var hashed = md5.ComputeHash (src);
var res = new StringBuilder (64);
foreach (var b in hashed)
res.Append (b.ToString ("x2"));
return res.ToString ();
}
private void initAsDigest ()
{
var qops = Parameters["qop"];
if (qops != null) {
if (qops.Split (',').Contains (qop => qop.Trim ().ToLower () == "auth")) {
Parameters["qop"] = "auth";
Parameters["cnonce"] = CreateNonceValue ();
Parameters["nc"] = String.Format ("{0:x8}", ++_nonceCount);
}
else {
Parameters["qop"] = null;
}
}
Parameters["method"] = "GET";
Parameters["response"] = CreateRequestDigest (Parameters);
}
#endregion
#region Internal Methods
internal static string CreateRequestDigest (NameValueCollection parameters)
{
var user = parameters["username"];
var pass = parameters["password"];
var realm = parameters["realm"];
var nonce = parameters["nonce"];
var uri = parameters["uri"];
var algo = parameters["algorithm"];
var qop = parameters["qop"];
var cnonce = parameters["cnonce"];
var nc = parameters["nc"];
var method = parameters["method"];
var a1 = algo != null && algo.ToLower () == "md5-sess"
? createA1 (user, pass, realm, nonce, cnonce)
: createA1 (user, pass, realm);
var a2 = qop != null && qop.ToLower () == "auth-int"
? createA2 (method, uri, parameters["entity"])
: createA2 (method, uri);
var secret = hash (a1);
var data = qop != null
? String.Format ("{0}:{1}:{2}:{3}:{4}", nonce, nc, cnonce, qop, hash (a2))
: String.Format ("{0}:{1}", nonce, hash (a2));
return hash (String.Format ("{0}:{1}", secret, data));
}
internal static AuthenticationResponse Parse (string value)
{
try {
var cred = value.Split (new[] { ' ' }, 2);
if (cred.Length != 2)
return null;
var schm = cred[0].ToLower ();
return schm == "basic"
? new AuthenticationResponse (
AuthenticationSchemes.Basic, ParseBasicCredentials (cred[1]))
: schm == "digest"
? new AuthenticationResponse (
AuthenticationSchemes.Digest, ParseParameters (cred[1]))
: null;
}
catch {
}
return null;
}
internal static NameValueCollection ParseBasicCredentials (string value)
{
// Decode the basic-credentials (a Base64 encoded string).
var userPass = Encoding.Default.GetString (Convert.FromBase64String (value));
// The format is [<domain>\]<username>:<password>.
var i = userPass.IndexOf (':');
var user = userPass.Substring (0, i);
var pass = i < userPass.Length - 1 ? userPass.Substring (i + 1) : String.Empty;
// Check if 'domain' exists.
i = user.IndexOf ('\\');
if (i > -1)
user = user.Substring (i + 1);
var res = new NameValueCollection ();
res["username"] = user;
res["password"] = pass;
return res;
}
internal override string ToBasicString ()
{
var userPass = String.Format ("{0}:{1}", Parameters["username"], Parameters["password"]);
var cred = Convert.ToBase64String (Encoding.UTF8.GetBytes (userPass));
return "Basic " + cred;
}
internal override string ToDigestString ()
{
var output = new StringBuilder (256);
output.AppendFormat (
"Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", response=\"{4}\"",
Parameters["username"],
Parameters["realm"],
Parameters["nonce"],
Parameters["uri"],
Parameters["response"]);
var opaque = Parameters["opaque"];
if (opaque != null)
output.AppendFormat (", opaque=\"{0}\"", opaque);
var algo = Parameters["algorithm"];
if (algo != null)
output.AppendFormat (", algorithm={0}", algo);
var qop = Parameters["qop"];
if (qop != null)
output.AppendFormat (
", qop={0}, cnonce=\"{1}\", nc={2}", qop, Parameters["cnonce"], Parameters["nc"]);
return output.ToString ();
}
#endregion
#region Public Methods
public IIdentity ToIdentity ()
{
var schm = Scheme;
return schm == AuthenticationSchemes.Basic
? new HttpBasicIdentity (Parameters["username"], Parameters["password"]) as IIdentity
: schm == AuthenticationSchemes.Digest
? new HttpDigestIdentity (Parameters)
: null;
}
#endregion
}
}
#endif
| |
//---------------------------------------------------------------------------
//
// <copyright file="Rect.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.WindowsBase;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Windows.Markup;
using System.Windows.Converters;
using System.Windows;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows
{
[Serializable]
[TypeConverter(typeof(RectConverter))]
[ValueSerializer(typeof(RectValueSerializer))] // Used by MarkupWriter
partial struct Rect : IFormattable
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Compares two Rect instances for exact equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which are logically equal may fail.
/// Furthermore, using this equality operator, Double.NaN is not equal to itself.
/// </summary>
/// <returns>
/// bool - true if the two Rect instances are exactly equal, false otherwise
/// </returns>
/// <param name='rect1'>The first Rect to compare</param>
/// <param name='rect2'>The second Rect to compare</param>
public static bool operator == (Rect rect1, Rect rect2)
{
return rect1.X == rect2.X &&
rect1.Y == rect2.Y &&
rect1.Width == rect2.Width &&
rect1.Height == rect2.Height;
}
/// <summary>
/// Compares two Rect instances for exact inequality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which are logically equal may fail.
/// Furthermore, using this equality operator, Double.NaN is not equal to itself.
/// </summary>
/// <returns>
/// bool - true if the two Rect instances are exactly unequal, false otherwise
/// </returns>
/// <param name='rect1'>The first Rect to compare</param>
/// <param name='rect2'>The second Rect to compare</param>
public static bool operator != (Rect rect1, Rect rect2)
{
return !(rect1 == rect2);
}
/// <summary>
/// Compares two Rect instances for object equality. In this equality
/// Double.NaN is equal to itself, unlike in numeric equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which
/// are logically equal may fail.
/// </summary>
/// <returns>
/// bool - true if the two Rect instances are exactly equal, false otherwise
/// </returns>
/// <param name='rect1'>The first Rect to compare</param>
/// <param name='rect2'>The second Rect to compare</param>
public static bool Equals (Rect rect1, Rect rect2)
{
if (rect1.IsEmpty)
{
return rect2.IsEmpty;
}
else
{
return rect1.X.Equals(rect2.X) &&
rect1.Y.Equals(rect2.Y) &&
rect1.Width.Equals(rect2.Width) &&
rect1.Height.Equals(rect2.Height);
}
}
/// <summary>
/// Equals - compares this Rect with the passed in object. In this equality
/// Double.NaN is equal to itself, unlike in numeric equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which
/// are logically equal may fail.
/// </summary>
/// <returns>
/// bool - true if the object is an instance of Rect and if it's equal to "this".
/// </returns>
/// <param name='o'>The object to compare to "this"</param>
public override bool Equals(object o)
{
if ((null == o) || !(o is Rect))
{
return false;
}
Rect value = (Rect)o;
return Rect.Equals(this,value);
}
/// <summary>
/// Equals - compares this Rect with the passed in object. In this equality
/// Double.NaN is equal to itself, unlike in numeric equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which
/// are logically equal may fail.
/// </summary>
/// <returns>
/// bool - true if "value" is equal to "this".
/// </returns>
/// <param name='value'>The Rect to compare to "this"</param>
public bool Equals(Rect value)
{
return Rect.Equals(this, value);
}
/// <summary>
/// Returns the HashCode for this Rect
/// </summary>
/// <returns>
/// int - the HashCode for this Rect
/// </returns>
public override int GetHashCode()
{
if (IsEmpty)
{
return 0;
}
else
{
// Perform field-by-field XOR of HashCodes
return X.GetHashCode() ^
Y.GetHashCode() ^
Width.GetHashCode() ^
Height.GetHashCode();
}
}
/// <summary>
/// Parse - returns an instance converted from the provided string using
/// the culture "en-US"
/// <param name="source"> string with Rect data </param>
/// </summary>
public static Rect Parse(string source)
{
IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;
TokenizerHelper th = new TokenizerHelper(source, formatProvider);
Rect value;
String firstToken = th.NextTokenRequired();
// The token will already have had whitespace trimmed so we can do a
// simple string compare.
if (firstToken == "Empty")
{
value = Empty;
}
else
{
value = new Rect(
Convert.ToDouble(firstToken, formatProvider),
Convert.ToDouble(th.NextTokenRequired(), formatProvider),
Convert.ToDouble(th.NextTokenRequired(), formatProvider),
Convert.ToDouble(th.NextTokenRequired(), formatProvider));
}
// There should be no more tokens in this string.
th.LastTokenRequired();
return value;
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Creates a string representation of this object based on the current culture.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
public override string ToString()
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, null /* format provider */);
}
/// <summary>
/// Creates a string representation of this object based on the IFormatProvider
/// passed in. If the provider is null, the CurrentCulture is used.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
public string ToString(IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, provider);
}
/// <summary>
/// Creates a string representation of this object based on the format string
/// and IFormatProvider passed in.
/// If the provider is null, the CurrentCulture is used.
/// See the documentation for IFormattable for more information.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
string IFormattable.ToString(string format, IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
/// <summary>
/// Creates a string representation of this object based on the format string
/// and IFormatProvider passed in.
/// If the provider is null, the CurrentCulture is used.
/// See the documentation for IFormattable for more information.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
internal string ConvertToString(string format, IFormatProvider provider)
{
if (IsEmpty)
{
return "Empty";
}
// Helper to get the numeric list separator for a given culture.
char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider);
return String.Format(provider,
"{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}",
separator,
_x,
_y,
_width,
_height);
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal double _x;
internal double _y;
internal double _width;
internal double _height;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#endregion Constructors
}
}
| |
using System.Collections.Generic;
using System.Linq;
namespace IdSharp.Tagging.ID3v1
{
/// <summary>
/// Static helper class for ID3v1 Genres.
/// </summary>
public static class GenreHelper
{
#region <<< Genre by ID3v1 index >>>
private static readonly string[] _genreByIndex = new[] {
"Blues",
"Classic Rock",
"Country",
"Dance",
"Disco",
"Funk",
"Grunge",
"Hip-Hop",
"Jazz",
"Metal",
"New Age",
"Oldies",
"Other",
"Pop",
"R&B",
"Rap",
"Reggae",
"Rock",
"Techno",
"Industrial",
"Alternative",
"Ska",
"Death Metal",
"Pranks",
"Soundtrack",
"Euro-Techno",
"Ambient",
"Trip-Hop",
"Vocal",
"Jazz+Funk",
"Fusion",
"Trance",
"Classical",
"Instrumental",
"Acid",
"House",
"Game",
"Sound Clip",
"Gospel",
"Noise",
"Alt. Rock",
"Bass",
"Soul",
"Punk",
"Space",
"Meditative",
"Instrumental Pop",
"Instrumental Rock",
"Ethnic",
"Gothic",
"Darkwave",
"Techno-Industrial",
"Electronic",
"Pop-Folk",
"Eurodance",
"Dream",
"Southern Rock",
"Comedy",
"Cult",
"Gangsta Rap",
"Top 40",
"Christian Rap",
"Pop/Funk",
"Jungle",
"Native American",
"Cabaret",
"New Wave",
"Psychedelic",
"Rave",
"Showtunes",
"Trailer",
"Lo-Fi",
"Tribal",
"Acid Punk",
"Acid Jazz",
"Polka",
"Retro",
"Musical",
"Rock & Roll",
"Hard Rock",
"Folk",
"Folk/Rock",
"National Folk",
"Swing",
"Fast-Fusion",
"Bebob",
"Latin",
"Revival",
"Celtic",
"Bluegrass",
"Avantgarde",
"Gothic Rock",
"Progressive Rock",
"Psychedelic Rock",
"Symphonic Rock",
"Slow Rock",
"Big Band",
"Chorus",
"Easy Listening",
"Acoustic",
"Humour",
"Speech",
"Chanson",
"Opera",
"Chamber Music",
"Sonata",
"Symphony",
"Booty Bass",
"Primus",
"Porn Groove",
"Satire",
"Slow Jam",
"Club",
"Tango",
"Samba",
"Folklore",
"Ballad",
"Power Ballad",
"Rhythmic Soul",
"Freestyle",
"Duet",
"Punk Rock",
"Drum Solo",
"A Cappella",
"Euro-House",
"Dance Hall",
"Goa",
"Drum & Bass",
"Club-House",
"Hardcore",
"Terror",
"Indie",
"BritPop",
"Negerpunk",
"Polsk Punk",
"Beat",
"Christian Gangsta Rap",
"Heavy Metal",
"Black Metal",
"Crossover",
"Contemporary Christian",
"Christian Rock",
"Merengue",
"Salsa",
"Thrash Metal",
"Anime",
"Jpop",
"Synthpop"};
#endregion <<< Genre by index >>>
private static readonly string[] _sortedGenreList;
private static readonly int _genreCount;
/// <summary>
/// The genre index of 'Other' (12).
/// </summary>
public const int Other_GenreIndex = 12;
static GenreHelper()
{
_genreCount = _genreByIndex.Length;
_sortedGenreList = _genreByIndex.OrderBy(p => p).ToArray();
}
/// <summary>
/// Gets a string array of ID3v1 genres sorted by index.
/// </summary>
/// <value>A string array of ID3v1 genres sorted by index.</value>
public static string[] GenreByIndex
{
get { return _genreByIndex; }
}
/// <summary>
/// Gets a sorted list of ID3v1 genres.
/// </summary>
/// <returns>A sorted list of ID3v1 genres.</returns>
public static List<string> GetSortedGenreList()
{
return new List<string>(_sortedGenreList);
}
/// <summary>
/// Gets the index of the genre. If the genre is not found, 12 is returned to indicate 'Other'.
/// </summary>
/// <param name="genre">The genre.</param>
/// <returns>The index of the genre. If the genre is not found, 12 is returned to indicate 'Other'.</returns>
public static int GetGenreIndex(string genre)
{
for (int i = 0; i <= _genreCount; i++)
{
if (string.Compare(genre, _genreByIndex[i], true) == 0)
return i;
}
return Other_GenreIndex;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Text
{
using System.Runtime.Serialization;
using System.Text;
using System;
using System.Diagnostics.Contracts;
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// sequential blocks of characters are converted into blocks of bytes through
// calls to the GetBytes method. The encoder maintains state between the
// conversions, allowing it to correctly encode character sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Encoder abstract base
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public abstract class Encoder
{
internal EncoderFallback m_fallback = null;
[NonSerialized]
internal EncoderFallbackBuffer m_fallbackBuffer = null;
internal void SerializeEncoder(SerializationInfo info)
{
info.AddValue("m_fallback", this.m_fallback);
}
protected Encoder()
{
// We don't call default reset because default reset probably isn't good if we aren't initialized.
}
[System.Runtime.InteropServices.ComVisible(false)]
public EncoderFallback Fallback
{
get
{
return m_fallback;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
// Can't change fallback if buffer is wrong
if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0)
throw new ArgumentException(
Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), "value");
m_fallback = value;
m_fallbackBuffer = null;
}
}
// Note: we don't test for threading here because async access to Encoders and Decoders
// doesn't work anyway.
[System.Runtime.InteropServices.ComVisible(false)]
public EncoderFallbackBuffer FallbackBuffer
{
get
{
if (m_fallbackBuffer == null)
{
if (m_fallback != null)
m_fallbackBuffer = m_fallback.CreateFallbackBuffer();
else
m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer();
}
return m_fallbackBuffer;
}
}
internal bool InternalHasFallbackBuffer
{
get
{
return m_fallbackBuffer != null;
}
}
// Reset the Encoder
//
// Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This
// would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
//
// If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset().
//
// Virtual implimentation has to call GetBytes with flush and a big enough buffer to clear a 0 char string
// We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual void Reset()
{
char[] charTemp = {};
byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)];
GetBytes(charTemp, 0, 0, byteTemp, 0, true);
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Returns the number of bytes the next call to GetBytes will
// produce if presented with the given range of characters and the given
// value of the flush parameter. The returned value takes into
// account the state in which the encoder was left following the last call
// to GetBytes. The state of the encoder is not affected by a call
// to this method.
//
public abstract int GetByteCount(char[] chars, int index, int count, bool flush);
// We expect this to be the workhorse for NLS encodings
// unfortunately for existing overrides, it has to call the [] version,
// which is really slow, so avoid this method if you might be calling external encodings.
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException("chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException("count",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
char[] arrChar = new char[count];
int index;
for (index = 0; index < count; index++)
arrChar[index] = chars[index];
return GetByteCount(arrChar, 0, count, flush);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. The method encodes charCount characters from
// chars starting at index charIndex, storing the resulting
// bytes in bytes starting at index byteIndex. The encoding
// takes into account the state in which the encoder was left following the
// last call to this method. The flush parameter indicates whether
// the encoder should flush any shift-states and partial characters at the
// end of the conversion. To ensure correct termination of a sequence of
// blocks of encoded bytes, the last call to GetBytes should specify
// a value of true for the flush parameter.
//
// An exception occurs if the byte array is not large enough to hold the
// complete encoding of the characters. The GetByteCount method can
// be used to determine the exact number of bytes that will be produced for
// a given range of characters. Alternatively, the GetMaxByteCount
// method of the Encoding that produced this encoder can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
//
public abstract int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush);
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implimentation)
//
// WARNING WARNING WARNING
//
// WARNING: If this breaks it could be a security threat. Obviously we
// call this internally, so you need to make sure that your pointers, counts
// and indexes are correct when you call this method.
//
// In addition, we have internal code, which will be marked as "safe" calling
// this code. However this code is dependent upon the implimentation of an
// external GetBytes() method, which could be overridden by a third party and
// the results of which cannot be guaranteed. We use that result to copy
// the byte[] to our byte* output buffer. If the result count was wrong, we
// could easily overflow our output buffer. Therefore we do an extra test
// when we copy the buffer so that we don't overflow byteCount either.
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, bool flush)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Get the char array to convert
char[] arrChar = new char[charCount];
int index;
for (index = 0; index < charCount; index++)
arrChar[index] = chars[index];
// Get the byte array to fill
byte[] arrByte = new byte[byteCount];
// Do the work
int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush);
// The only way this could fail is a bug in GetBytes
Contract.Assert(result <= byteCount, "Returned more bytes than we have space for");
// Copy the byte array
// WARNING: We MUST make sure that we don't copy too many bytes. We can't
// rely on result because it could be a 3rd party implimentation. We need
// to make sure we never copy more than byteCount bytes no matter the value
// of result
if (result < byteCount)
byteCount = result;
// Don't copy too many bytes!
for (index = 0; index < byteCount; index++)
bytes[index] = arrByte[index];
return byteCount;
}
// This method is used to avoid running out of output buffer space.
// It will encode until it runs out of chars, and then it will return
// true if it the entire input was converted. In either case it
// will also return the number of converted chars and output bytes used.
// It will only throw a buffer overflow exception if the entire lenght of bytes[] is
// too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings)
// We're done processing this buffer only if completed returns true.
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input chars are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many chars as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
[System.Runtime.InteropServices.ComVisible(false)]
public virtual void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"),
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
charsUsed = charCount;
// Its easy to do if it won't overrun our buffer.
// Note: We don't want to call unsafe version because that might be an untrusted version
// which could be really unsafe and we don't want to mix it up.
while (charsUsed > 0)
{
if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount)
{
bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush);
completed = (charsUsed == charCount &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
charsUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow"));
}
// Same thing, but using pointers
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input chars are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many chars as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars",
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Get ready to do it
charsUsed = charCount;
// Its easy to do if it won't overrun our buffer.
while (charsUsed > 0)
{
if (GetByteCount(chars, charsUsed, flush) <= byteCount)
{
bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush);
completed = (charsUsed == charCount &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
charsUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow"));
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Tests
{
public class MetadataTest
{
[Test]
public void AsciiEntry()
{
var entry = new Metadata.Entry("ABC", "XYZ");
Assert.IsFalse(entry.IsBinary);
Assert.AreEqual("abc", entry.Key); // key is in lowercase.
Assert.AreEqual("XYZ", entry.Value);
CollectionAssert.AreEqual(new[] { (byte)'X', (byte)'Y', (byte)'Z' }, entry.ValueBytes);
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc-bin", "xyz"));
Assert.AreEqual("[Entry: key=abc, value=XYZ]", entry.ToString());
}
[Test]
public void BinaryEntry()
{
var bytes = new byte[] { 1, 2, 3 };
var entry = new Metadata.Entry("ABC-BIN", bytes);
Assert.IsTrue(entry.IsBinary);
Assert.AreEqual("abc-bin", entry.Key); // key is in lowercase.
Assert.Throws(typeof(InvalidOperationException), () => { var v = entry.Value; });
CollectionAssert.AreEqual(bytes, entry.ValueBytes);
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc", bytes));
Assert.AreEqual("[Entry: key=abc-bin, valueBytes=System.Byte[]]", entry.ToString());
}
[Test]
public void AsciiEntry_KeyValidity()
{
new Metadata.Entry("ABC", "XYZ");
new Metadata.Entry("0123456789abc", "XYZ");
new Metadata.Entry("-abc", "XYZ");
new Metadata.Entry("a_bc_", "XYZ");
new Metadata.Entry("abc.xyz", "XYZ");
new Metadata.Entry("abc.xyz-bin", new byte[] {1, 2, 3});
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc[", "xyz"));
Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc/", "xyz"));
}
[Test]
public void KeysAreNormalized_UppercaseKey()
{
var uppercaseKey = "ABC";
var entry = new Metadata.Entry(uppercaseKey, "XYZ");
Assert.AreEqual("abc", entry.Key);
}
[Test]
public void KeysAreNormalized_LowercaseKey()
{
var lowercaseKey = "abc";
var entry = new Metadata.Entry(lowercaseKey, "XYZ");
// no allocation if key already lowercase
Assert.AreSame(lowercaseKey, entry.Key);
}
[Test]
public void Entry_ConstructionPreconditions()
{
Assert.Throws(typeof(ArgumentNullException), () => new Metadata.Entry(null, "xyz"));
Assert.Throws(typeof(ArgumentNullException), () => new Metadata.Entry("abc", (string)null));
Assert.Throws(typeof(ArgumentNullException), () => new Metadata.Entry("abc-bin", (byte[])null));
}
[Test]
public void Entry_Immutable()
{
var origBytes = new byte[] { 1, 2, 3 };
var bytes = new byte[] { 1, 2, 3 };
var entry = new Metadata.Entry("ABC-BIN", bytes);
bytes[0] = 255; // changing the array passed to constructor should have any effect.
CollectionAssert.AreEqual(origBytes, entry.ValueBytes);
entry.ValueBytes[0] = 255;
CollectionAssert.AreEqual(origBytes, entry.ValueBytes);
}
[Test]
public unsafe void Entry_CreateUnsafe_Ascii()
{
var bytes = new byte[] { (byte)'X', (byte)'y' };
fixed (byte* ptr = bytes)
{
var entry = Metadata.Entry.CreateUnsafe("abc", new IntPtr(ptr), bytes.Length);
Assert.IsFalse(entry.IsBinary);
Assert.AreEqual("abc", entry.Key);
Assert.AreEqual("Xy", entry.Value);
CollectionAssert.AreEqual(bytes, entry.ValueBytes);
}
}
[Test]
public unsafe void Entry_CreateUnsafe_Binary()
{
var bytes = new byte[] { 1, 2, 3 };
fixed (byte* ptr = bytes)
{
var entry = Metadata.Entry.CreateUnsafe("abc-bin", new IntPtr(ptr), bytes.Length);
Assert.IsTrue(entry.IsBinary);
Assert.AreEqual("abc-bin", entry.Key);
Assert.Throws(typeof(InvalidOperationException), () => { var v = entry.Value; });
CollectionAssert.AreEqual(bytes, entry.ValueBytes);
}
}
[Test]
public void IndexOf()
{
var metadata = CreateMetadata();
Assert.AreEqual(0, metadata.IndexOf(metadata[0]));
Assert.AreEqual(1, metadata.IndexOf(metadata[1]));
}
[Test]
public void Insert()
{
var metadata = CreateMetadata();
metadata.Insert(0, new Metadata.Entry("new-key", "new-value"));
Assert.AreEqual(3, metadata.Count);
Assert.AreEqual("new-key", metadata[0].Key);
Assert.AreEqual("abc", metadata[1].Key);
}
[Test]
public void RemoveAt()
{
var metadata = CreateMetadata();
metadata.RemoveAt(0);
Assert.AreEqual(1, metadata.Count);
Assert.AreEqual("xyz", metadata[0].Key);
}
[Test]
public void Remove()
{
var metadata = CreateMetadata();
metadata.Remove(metadata[0]);
Assert.AreEqual(1, metadata.Count);
Assert.AreEqual("xyz", metadata[0].Key);
}
[Test]
public void Indexer_Set()
{
var metadata = CreateMetadata();
var entry = new Metadata.Entry("new-key", "new-value");
metadata[1] = entry;
Assert.AreEqual(entry, metadata[1]);
}
[Test]
public void Clear()
{
var metadata = CreateMetadata();
metadata.Clear();
Assert.AreEqual(0, metadata.Count);
}
[Test]
public void Contains()
{
var metadata = CreateMetadata();
Assert.IsTrue(metadata.Contains(metadata[0]));
Assert.IsFalse(metadata.Contains(new Metadata.Entry("new-key", "new-value")));
}
[Test]
public void CopyTo()
{
var metadata = CreateMetadata();
var array = new Metadata.Entry[metadata.Count + 1];
metadata.CopyTo(array, 1);
Assert.AreEqual(default(Metadata.Entry), array[0]);
Assert.AreEqual(metadata[0], array[1]);
}
[Test]
public void IEnumerableGetEnumerator()
{
var metadata = CreateMetadata();
var enumerator = (metadata as System.Collections.IEnumerable).GetEnumerator();
int i = 0;
while (enumerator.MoveNext())
{
Assert.AreEqual(metadata[i], enumerator.Current);
i++;
}
}
[Test]
public void FreezeMakesReadOnly()
{
var entry = new Metadata.Entry("new-key", "new-value");
var metadata = CreateMetadata().Freeze();
Assert.IsTrue(metadata.IsReadOnly);
Assert.Throws<InvalidOperationException>(() => metadata.Insert(0, entry));
Assert.Throws<InvalidOperationException>(() => metadata.RemoveAt(0));
Assert.Throws<InvalidOperationException>(() => metadata[0] = entry);
Assert.Throws<InvalidOperationException>(() => metadata.Add(entry));
Assert.Throws<InvalidOperationException>(() => metadata.Add("new-key", "new-value"));
Assert.Throws<InvalidOperationException>(() => metadata.Add("new-key-bin", new byte[] { 0xaa }));
Assert.Throws<InvalidOperationException>(() => metadata.Clear());
Assert.Throws<InvalidOperationException>(() => metadata.Remove(metadata[0]));
}
[Test]
public void GetAll()
{
var metadata = new Metadata
{
{ "abc", "abc-value1" },
{ "abc", "abc-value2" },
{ "xyz", "xyz-value1" },
};
var abcEntries = metadata.GetAll("abc").ToList();
Assert.AreEqual(2, abcEntries.Count);
Assert.AreEqual("abc-value1", abcEntries[0].Value);
Assert.AreEqual("abc-value2", abcEntries[1].Value);
var xyzEntries = metadata.GetAll("xyz").ToList();
Assert.AreEqual(1, xyzEntries.Count);
Assert.AreEqual("xyz-value1", xyzEntries[0].Value);
}
[Test]
public void Get()
{
var metadata = new Metadata
{
{ "abc", "abc-value1" },
{ "abc", "abc-value2" },
{ "xyz", "xyz-value1" },
};
var abcEntry = metadata.Get("abc");
Assert.AreEqual("abc-value2", abcEntry.Value);
var xyzEntry = metadata.Get("xyz");
Assert.AreEqual("xyz-value1", xyzEntry.Value);
var notFound = metadata.Get("not-found");
Assert.AreEqual(null, notFound);
}
[Test]
public void GetValue()
{
var metadata = new Metadata
{
{ "abc", "abc-value1" },
{ "abc", "abc-value2" },
{ "xyz", "xyz-value1" },
{ "xyz-bin", Encoding.ASCII.GetBytes("xyz-value1") },
};
var abcValue = metadata.GetValue("abc");
Assert.AreEqual("abc-value2", abcValue);
var xyzValue = metadata.GetValue("xyz");
Assert.AreEqual("xyz-value1", xyzValue);
var notFound = metadata.GetValue("not-found");
Assert.AreEqual(null, notFound);
}
[Test]
public void GetValue_BytesValue()
{
var metadata = new Metadata
{
{ "xyz-bin", Encoding.ASCII.GetBytes("xyz-value1") },
};
Assert.Throws<InvalidOperationException>(() => metadata.GetValue("xyz-bin"));
}
[Test]
public void GetValueBytes()
{
var metadata = new Metadata
{
{ "abc-bin", Encoding.ASCII.GetBytes("abc-value1") },
{ "abc-bin", Encoding.ASCII.GetBytes("abc-value2") },
{ "xyz-bin", Encoding.ASCII.GetBytes("xyz-value1") },
};
var abcValue = metadata.GetValueBytes("abc-bin");
Assert.AreEqual(Encoding.ASCII.GetBytes("abc-value2"), abcValue);
var xyzValue = metadata.GetValueBytes("xyz-bin");
Assert.AreEqual(Encoding.ASCII.GetBytes("xyz-value1"), xyzValue);
var notFound = metadata.GetValueBytes("not-found");
Assert.AreEqual(null, notFound);
}
[Test]
public void GetValueBytes_StringValue()
{
var metadata = new Metadata
{
{ "xyz", "xyz-value1" },
};
var xyzValue = metadata.GetValueBytes("xyz");
Assert.AreEqual(Encoding.ASCII.GetBytes("xyz-value1"), xyzValue);
}
private Metadata CreateMetadata()
{
return new Metadata
{
{ "abc", "abc-value" },
{ "xyz", "xyz-value" },
};
}
}
}
| |
namespace Toolkit
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
WeifenLuo.WinFormsUI.Docking.DockPanelSkin dockPanelSkin1 = new WeifenLuo.WinFormsUI.Docking.DockPanelSkin();
WeifenLuo.WinFormsUI.Docking.AutoHideStripSkin autoHideStripSkin1 = new WeifenLuo.WinFormsUI.Docking.AutoHideStripSkin();
WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient();
WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient1 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
WeifenLuo.WinFormsUI.Docking.DockPaneStripSkin dockPaneStripSkin1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripSkin();
WeifenLuo.WinFormsUI.Docking.DockPaneStripGradient dockPaneStripGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripGradient();
WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient2 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient2 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient();
WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient3 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
WeifenLuo.WinFormsUI.Docking.DockPaneStripToolWindowGradient dockPaneStripToolWindowGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripToolWindowGradient();
WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient4 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient5 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient3 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient();
WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient6 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient7 = new WeifenLuo.WinFormsUI.Docking.TabGradient();
this.statusBar = new System.Windows.Forms.StatusStrip();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemNewProject = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemLoadProject = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemView = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripMenuItem();
this.showMapGridToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem();
this.consoleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.networkMonitorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.contentExplorerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.assetExplorerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.layersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tilesetsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem();
this.closeAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.settingsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pluginsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.gameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.testToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuMain = new System.Windows.Forms.MenuStrip();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.buttonSaveContent = new System.Windows.Forms.ToolStripButton();
this.buttonSaveAll = new System.Windows.Forms.ToolStripButton();
this.toolStripButton3 = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.cutButton = new System.Windows.Forms.ToolStripButton();
this.copyButton = new System.Windows.Forms.ToolStripButton();
this.pasteButton = new System.Windows.Forms.ToolStripButton();
this.buttonUndo = new System.Windows.Forms.ToolStripButton();
this.buttonRedo = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.buttonPencil = new System.Windows.Forms.ToolStripButton();
this.buttonDropper = new System.Windows.Forms.ToolStripButton();
this.buttonEraser = new System.Windows.Forms.ToolStripButton();
this.buttonFill = new System.Windows.Forms.ToolStripButton();
this.toolStripButton10 = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.dockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel();
this.menuMain.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.SuspendLayout();
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 387);
this.statusBar.Name = "statusBar";
this.statusBar.Size = new System.Drawing.Size(579, 22);
this.statusBar.TabIndex = 4;
//
// imageList
//
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.Transparent;
this.imageList.Images.SetKeyName(0, "");
this.imageList.Images.SetKeyName(1, "");
this.imageList.Images.SetKeyName(2, "");
this.imageList.Images.SetKeyName(3, "");
this.imageList.Images.SetKeyName(4, "");
this.imageList.Images.SetKeyName(5, "");
this.imageList.Images.SetKeyName(6, "");
this.imageList.Images.SetKeyName(7, "");
this.imageList.Images.SetKeyName(8, "");
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItemNewProject,
this.toolStripMenuItemLoadProject,
this.toolStripSeparator6,
this.toolStripMenuItem6,
this.toolStripMenuItem1,
this.toolStripSeparator1,
this.printPreviewToolStripMenuItem,
this.toolStripSeparator2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// toolStripMenuItemNewProject
//
this.toolStripMenuItemNewProject.Enabled = false;
this.toolStripMenuItemNewProject.Image = global::Toolkit.Properties.Resources.folder_add;
this.toolStripMenuItemNewProject.Name = "toolStripMenuItemNewProject";
this.toolStripMenuItemNewProject.Size = new System.Drawing.Size(187, 22);
this.toolStripMenuItemNewProject.Text = "New Project...";
this.toolStripMenuItemNewProject.Click += new System.EventHandler(this.toolStripMenuItemNewProject_Click);
//
// toolStripMenuItemLoadProject
//
this.toolStripMenuItemLoadProject.Enabled = false;
this.toolStripMenuItemLoadProject.Image = global::Toolkit.Properties.Resources.folder_edit;
this.toolStripMenuItemLoadProject.Name = "toolStripMenuItemLoadProject";
this.toolStripMenuItemLoadProject.Size = new System.Drawing.Size(187, 22);
this.toolStripMenuItemLoadProject.Text = "Load Project...";
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(184, 6);
//
// toolStripMenuItem6
//
this.toolStripMenuItem6.Image = global::Toolkit.Properties.Resources.disk1;
this.toolStripMenuItem6.Name = "toolStripMenuItem6";
this.toolStripMenuItem6.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.toolStripMenuItem6.Size = new System.Drawing.Size(187, 22);
this.toolStripMenuItem6.Text = "Save Content";
this.toolStripMenuItem6.Click += new System.EventHandler(this.toolStripMenuItem6_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Image = global::Toolkit.Properties.Resources.disks;
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.S)));
this.toolStripMenuItem1.Size = new System.Drawing.Size(187, 22);
this.toolStripMenuItem1.Text = "Save All";
this.toolStripMenuItem1.Click += new System.EventHandler(this.toolStripMenuItem1_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(184, 6);
//
// printPreviewToolStripMenuItem
//
this.printPreviewToolStripMenuItem.Enabled = false;
this.printPreviewToolStripMenuItem.Image = global::Toolkit.Properties.Resources.cog;
this.printPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem";
this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
this.printPreviewToolStripMenuItem.Text = "Project Settings...";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(184, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Image = global::Toolkit.Properties.Resources.door;
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.E)));
this.exitToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// toolStripMenuItemView
//
this.toolStripMenuItemView.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem8,
this.toolStripMenuItem7,
this.toolStripSeparator8,
this.toolStripMenuItem2,
this.contentExplorerToolStripMenuItem,
this.assetExplorerToolStripMenuItem,
this.layersToolStripMenuItem,
this.tilesetsToolStripMenuItem});
this.toolStripMenuItemView.Name = "toolStripMenuItemView";
this.toolStripMenuItemView.Size = new System.Drawing.Size(44, 20);
this.toolStripMenuItemView.Text = "View";
//
// toolStripMenuItem8
//
this.toolStripMenuItem8.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.showMapGridToolStripMenuItem});
this.toolStripMenuItem8.Name = "toolStripMenuItem8";
this.toolStripMenuItem8.Size = new System.Drawing.Size(187, 22);
this.toolStripMenuItem8.Text = "Mapping";
//
// showMapGridToolStripMenuItem
//
this.showMapGridToolStripMenuItem.Name = "showMapGridToolStripMenuItem";
this.showMapGridToolStripMenuItem.Size = new System.Drawing.Size(155, 22);
this.showMapGridToolStripMenuItem.Text = "Show Map Grid";
//
// toolStripMenuItem7
//
this.toolStripMenuItem7.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.consoleToolStripMenuItem,
this.networkMonitorToolStripMenuItem});
this.toolStripMenuItem7.Enabled = false;
this.toolStripMenuItem7.Name = "toolStripMenuItem7";
this.toolStripMenuItem7.Size = new System.Drawing.Size(187, 22);
this.toolStripMenuItem7.Text = "Debug";
//
// consoleToolStripMenuItem
//
this.consoleToolStripMenuItem.Image = global::Toolkit.Properties.Resources.terminal;
this.consoleToolStripMenuItem.Name = "consoleToolStripMenuItem";
this.consoleToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D)));
this.consoleToolStripMenuItem.Size = new System.Drawing.Size(165, 22);
this.consoleToolStripMenuItem.Text = "Console";
//
// networkMonitorToolStripMenuItem
//
this.networkMonitorToolStripMenuItem.Image = global::Toolkit.Properties.Resources.network;
this.networkMonitorToolStripMenuItem.Name = "networkMonitorToolStripMenuItem";
this.networkMonitorToolStripMenuItem.Size = new System.Drawing.Size(165, 22);
this.networkMonitorToolStripMenuItem.Text = "Network Monitor";
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(184, 6);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Image = global::Toolkit.Properties.Resources.image;
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.T)));
this.toolStripMenuItem2.Size = new System.Drawing.Size(187, 22);
this.toolStripMenuItem2.Text = "History";
this.toolStripMenuItem2.Visible = false;
this.toolStripMenuItem2.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// contentExplorerToolStripMenuItem
//
this.contentExplorerToolStripMenuItem.Image = global::Toolkit.Properties.Resources.folder_explore;
this.contentExplorerToolStripMenuItem.Name = "contentExplorerToolStripMenuItem";
this.contentExplorerToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F10;
this.contentExplorerToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
this.contentExplorerToolStripMenuItem.Text = "Content Explorer";
this.contentExplorerToolStripMenuItem.Click += new System.EventHandler(this.contentExplorerToolStripMenuItem_Click);
//
// assetExplorerToolStripMenuItem
//
this.assetExplorerToolStripMenuItem.Image = global::Toolkit.Properties.Resources.book;
this.assetExplorerToolStripMenuItem.Name = "assetExplorerToolStripMenuItem";
this.assetExplorerToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
this.assetExplorerToolStripMenuItem.Text = "Asset Explorer";
this.assetExplorerToolStripMenuItem.Click += new System.EventHandler(this.assetExplorerToolStripMenuItem_Click);
//
// layersToolStripMenuItem
//
this.layersToolStripMenuItem.Name = "layersToolStripMenuItem";
this.layersToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
this.layersToolStripMenuItem.Text = "Layers";
this.layersToolStripMenuItem.Click += new System.EventHandler(this.layersToolStripMenuItem_Click);
//
// tilesetsToolStripMenuItem
//
this.tilesetsToolStripMenuItem.Name = "tilesetsToolStripMenuItem";
this.tilesetsToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
this.tilesetsToolStripMenuItem.Text = "Tilesets";
this.tilesetsToolStripMenuItem.Click += new System.EventHandler(this.tilesetsToolStripMenuItem_Click);
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.closeAllToolStripMenuItem});
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(63, 20);
this.toolStripMenuItem3.Text = "Window";
this.toolStripMenuItem3.Visible = false;
//
// closeAllToolStripMenuItem
//
this.closeAllToolStripMenuItem.Name = "closeAllToolStripMenuItem";
this.closeAllToolStripMenuItem.Size = new System.Drawing.Size(120, 22);
this.closeAllToolStripMenuItem.Text = "Close All";
this.closeAllToolStripMenuItem.Click += new System.EventHandler(this.closeAllToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem5,
this.toolStripMenuItem4,
this.toolStripSeparator7,
this.settingsMenuItem,
this.pluginsToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.toolsToolStripMenuItem.Text = "&Tools";
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Enabled = false;
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.B)));
this.toolStripMenuItem5.Size = new System.Drawing.Size(198, 22);
this.toolStripMenuItem5.Text = "Database Editor";
this.toolStripMenuItem5.Click += new System.EventHandler(this.toolStripMenuItem5_Click);
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Enabled = false;
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D)));
this.toolStripMenuItem4.Size = new System.Drawing.Size(198, 22);
this.toolStripMenuItem4.Text = "Resource Editor";
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(195, 6);
//
// settingsMenuItem
//
this.settingsMenuItem.Image = global::Toolkit.Properties.Resources.gear;
this.settingsMenuItem.Name = "settingsMenuItem";
this.settingsMenuItem.Size = new System.Drawing.Size(198, 22);
this.settingsMenuItem.Text = "&Settings";
//
// pluginsToolStripMenuItem
//
this.pluginsToolStripMenuItem.Image = global::Toolkit.Properties.Resources.plugin;
this.pluginsToolStripMenuItem.Name = "pluginsToolStripMenuItem";
this.pluginsToolStripMenuItem.Size = new System.Drawing.Size(198, 22);
this.pluginsToolStripMenuItem.Text = "Plugins";
//
// gameToolStripMenuItem
//
this.gameToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.testToolStripMenuItem});
this.gameToolStripMenuItem.Name = "gameToolStripMenuItem";
this.gameToolStripMenuItem.Size = new System.Drawing.Size(50, 20);
this.gameToolStripMenuItem.Text = "Game";
//
// testToolStripMenuItem
//
this.testToolStripMenuItem.Image = global::Toolkit.Properties.Resources.resultset_next;
this.testToolStripMenuItem.Name = "testToolStripMenuItem";
this.testToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F5;
this.testToolStripMenuItem.Size = new System.Drawing.Size(124, 22);
this.testToolStripMenuItem.Text = "Test...";
this.testToolStripMenuItem.Click += new System.EventHandler(this.testToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.contentsToolStripMenuItem,
this.toolStripSeparator5,
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// contentsToolStripMenuItem
//
this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
this.contentsToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F1;
this.contentsToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.contentsToolStripMenuItem.Text = "Documentation";
this.contentsToolStripMenuItem.Click += new System.EventHandler(this.contentsToolStripMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(173, 6);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Image = global::Toolkit.Properties.Resources.information1;
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(176, 22);
this.aboutToolStripMenuItem.Text = "&About...";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// menuMain
//
this.menuMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.toolStripMenuItemView,
this.toolsToolStripMenuItem,
this.toolStripMenuItem3,
this.gameToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuMain.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
this.menuMain.Location = new System.Drawing.Point(0, 0);
this.menuMain.Name = "menuMain";
this.menuMain.Size = new System.Drawing.Size(579, 24);
this.menuMain.TabIndex = 10;
this.menuMain.Text = "menuStrip1";
//
// toolStrip1
//
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.buttonSaveContent,
this.buttonSaveAll,
this.toolStripButton3,
this.toolStripSeparator3,
this.cutButton,
this.copyButton,
this.pasteButton,
this.buttonUndo,
this.buttonRedo,
this.toolStripSeparator4,
this.buttonPencil,
this.buttonDropper,
this.buttonEraser,
this.buttonFill,
this.toolStripButton10,
this.toolStripSeparator9});
this.toolStrip1.Location = new System.Drawing.Point(0, 24);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(579, 25);
this.toolStrip1.TabIndex = 16;
this.toolStrip1.Text = "toolStrip1";
//
// buttonSaveContent
//
this.buttonSaveContent.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.buttonSaveContent.Image = global::Toolkit.Properties.Resources.disk1;
this.buttonSaveContent.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonSaveContent.Name = "buttonSaveContent";
this.buttonSaveContent.Size = new System.Drawing.Size(23, 22);
this.buttonSaveContent.Text = "Save";
this.buttonSaveContent.Click += new System.EventHandler(this.buttonSaveContent_Click);
//
// buttonSaveAll
//
this.buttonSaveAll.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.buttonSaveAll.Image = global::Toolkit.Properties.Resources.disks;
this.buttonSaveAll.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonSaveAll.Name = "buttonSaveAll";
this.buttonSaveAll.Size = new System.Drawing.Size(23, 22);
this.buttonSaveAll.Text = "Save All";
this.buttonSaveAll.Click += new System.EventHandler(this.buttonSaveAll_Click);
//
// toolStripButton3
//
this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton3.Image")));
this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton3.Name = "toolStripButton3";
this.toolStripButton3.Size = new System.Drawing.Size(23, 22);
this.toolStripButton3.Text = "toolStripButton3";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25);
//
// cutButton
//
this.cutButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cutButton.Image = global::Toolkit.Properties.Resources.scissors;
this.cutButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutButton.Name = "cutButton";
this.cutButton.Size = new System.Drawing.Size(23, 22);
this.cutButton.Text = "Cut";
this.cutButton.Click += new System.EventHandler(this.toolStripButton4_Click);
//
// copyButton
//
this.copyButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.copyButton.Image = global::Toolkit.Properties.Resources.clipboard_sign;
this.copyButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyButton.Name = "copyButton";
this.copyButton.Size = new System.Drawing.Size(23, 22);
this.copyButton.Text = "Copy";
this.copyButton.Click += new System.EventHandler(this.toolStripButton6_Click);
//
// pasteButton
//
this.pasteButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.pasteButton.Image = global::Toolkit.Properties.Resources.clipboard_paste;
this.pasteButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteButton.Name = "pasteButton";
this.pasteButton.Size = new System.Drawing.Size(23, 22);
this.pasteButton.Text = "Paste";
this.pasteButton.Click += new System.EventHandler(this.toolStripButton1_Click);
//
// buttonUndo
//
this.buttonUndo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.buttonUndo.Image = global::Toolkit.Properties.Resources.arrow_undo;
this.buttonUndo.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonUndo.Name = "buttonUndo";
this.buttonUndo.Size = new System.Drawing.Size(23, 22);
this.buttonUndo.Text = "Undo";
this.buttonUndo.Click += new System.EventHandler(this.buttonUndo_Click);
//
// buttonRedo
//
this.buttonRedo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.buttonRedo.Image = global::Toolkit.Properties.Resources.arrow_redo;
this.buttonRedo.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonRedo.Name = "buttonRedo";
this.buttonRedo.Size = new System.Drawing.Size(23, 22);
this.buttonRedo.Text = "Redo";
this.buttonRedo.Click += new System.EventHandler(this.buttonRedo_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25);
//
// buttonPencil
//
this.buttonPencil.Checked = true;
this.buttonPencil.CheckOnClick = true;
this.buttonPencil.CheckState = System.Windows.Forms.CheckState.Checked;
this.buttonPencil.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.buttonPencil.Image = global::Toolkit.Properties.Resources.pencil2;
this.buttonPencil.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonPencil.Name = "buttonPencil";
this.buttonPencil.Size = new System.Drawing.Size(23, 22);
this.buttonPencil.Text = "Pencil";
this.buttonPencil.Click += new System.EventHandler(this.buttonPencil_Click);
//
// buttonDropper
//
this.buttonDropper.CheckOnClick = true;
this.buttonDropper.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.buttonDropper.Image = global::Toolkit.Properties.Resources.wand1;
this.buttonDropper.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonDropper.Name = "buttonDropper";
this.buttonDropper.Size = new System.Drawing.Size(23, 22);
this.buttonDropper.Text = "Finder";
this.buttonDropper.Click += new System.EventHandler(this.buttonDropper_Click);
//
// buttonEraser
//
this.buttonEraser.CheckOnClick = true;
this.buttonEraser.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.buttonEraser.Image = global::Toolkit.Properties.Resources.eraser;
this.buttonEraser.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonEraser.Name = "buttonEraser";
this.buttonEraser.Size = new System.Drawing.Size(23, 22);
this.buttonEraser.Text = "Eraser";
this.buttonEraser.Click += new System.EventHandler(this.buttonEraser_Click);
//
// buttonFill
//
this.buttonFill.CheckOnClick = true;
this.buttonFill.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.buttonFill.Image = global::Toolkit.Properties.Resources.paint_can;
this.buttonFill.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonFill.Name = "buttonFill";
this.buttonFill.Size = new System.Drawing.Size(23, 22);
this.buttonFill.Text = "Fill";
this.buttonFill.Click += new System.EventHandler(this.buttonFill_Click);
//
// toolStripButton10
//
this.toolStripButton10.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButton10.Enabled = false;
this.toolStripButton10.Image = global::Toolkit.Properties.Resources.shape_square;
this.toolStripButton10.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton10.Name = "toolStripButton10";
this.toolStripButton10.Size = new System.Drawing.Size(23, 22);
this.toolStripButton10.Text = "Rectangle Fill";
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
this.toolStripSeparator9.Size = new System.Drawing.Size(6, 25);
//
// dockPanel
//
this.dockPanel.DefaultFloatWindowSize = new System.Drawing.Size(800, 600);
this.dockPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.dockPanel.DockBackColor = System.Drawing.SystemColors.AppWorkspace;
this.dockPanel.DockBottomPortion = 150D;
this.dockPanel.DockLeftPortion = 200D;
this.dockPanel.DockRightPortion = 200D;
this.dockPanel.DockTopPortion = 150D;
this.dockPanel.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World, ((byte)(0)));
this.dockPanel.Location = new System.Drawing.Point(0, 49);
this.dockPanel.Name = "dockPanel";
this.dockPanel.RightToLeftLayout = true;
this.dockPanel.Size = new System.Drawing.Size(579, 338);
dockPanelGradient1.EndColor = System.Drawing.SystemColors.ControlLight;
dockPanelGradient1.StartColor = System.Drawing.SystemColors.ControlLight;
autoHideStripSkin1.DockStripGradient = dockPanelGradient1;
tabGradient1.EndColor = System.Drawing.SystemColors.Control;
tabGradient1.StartColor = System.Drawing.SystemColors.Control;
tabGradient1.TextColor = System.Drawing.SystemColors.ControlDarkDark;
autoHideStripSkin1.TabGradient = tabGradient1;
autoHideStripSkin1.TextFont = new System.Drawing.Font("Segoe UI", 9F);
dockPanelSkin1.AutoHideStripSkin = autoHideStripSkin1;
tabGradient2.EndColor = System.Drawing.SystemColors.ControlLightLight;
tabGradient2.StartColor = System.Drawing.SystemColors.ControlLightLight;
tabGradient2.TextColor = System.Drawing.SystemColors.ControlText;
dockPaneStripGradient1.ActiveTabGradient = tabGradient2;
dockPanelGradient2.EndColor = System.Drawing.SystemColors.Control;
dockPanelGradient2.StartColor = System.Drawing.SystemColors.Control;
dockPaneStripGradient1.DockStripGradient = dockPanelGradient2;
tabGradient3.EndColor = System.Drawing.SystemColors.ControlLight;
tabGradient3.StartColor = System.Drawing.SystemColors.ControlLight;
tabGradient3.TextColor = System.Drawing.SystemColors.ControlText;
dockPaneStripGradient1.InactiveTabGradient = tabGradient3;
dockPaneStripSkin1.DocumentGradient = dockPaneStripGradient1;
dockPaneStripSkin1.TextFont = new System.Drawing.Font("Segoe UI", 9F);
tabGradient4.EndColor = System.Drawing.SystemColors.ActiveCaption;
tabGradient4.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
tabGradient4.StartColor = System.Drawing.SystemColors.GradientActiveCaption;
tabGradient4.TextColor = System.Drawing.SystemColors.ActiveCaptionText;
dockPaneStripToolWindowGradient1.ActiveCaptionGradient = tabGradient4;
tabGradient5.EndColor = System.Drawing.SystemColors.Control;
tabGradient5.StartColor = System.Drawing.SystemColors.Control;
tabGradient5.TextColor = System.Drawing.SystemColors.ControlText;
dockPaneStripToolWindowGradient1.ActiveTabGradient = tabGradient5;
dockPanelGradient3.EndColor = System.Drawing.SystemColors.ControlLight;
dockPanelGradient3.StartColor = System.Drawing.SystemColors.ControlLight;
dockPaneStripToolWindowGradient1.DockStripGradient = dockPanelGradient3;
tabGradient6.EndColor = System.Drawing.SystemColors.GradientInactiveCaption;
tabGradient6.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
tabGradient6.StartColor = System.Drawing.SystemColors.GradientInactiveCaption;
tabGradient6.TextColor = System.Drawing.SystemColors.ControlText;
dockPaneStripToolWindowGradient1.InactiveCaptionGradient = tabGradient6;
tabGradient7.EndColor = System.Drawing.Color.Transparent;
tabGradient7.StartColor = System.Drawing.Color.Transparent;
tabGradient7.TextColor = System.Drawing.SystemColors.ControlDarkDark;
dockPaneStripToolWindowGradient1.InactiveTabGradient = tabGradient7;
dockPaneStripSkin1.ToolWindowGradient = dockPaneStripToolWindowGradient1;
dockPanelSkin1.DockPaneStripSkin = dockPaneStripSkin1;
this.dockPanel.Skin = dockPanelSkin1;
this.dockPanel.SkinStyle = WeifenLuo.WinFormsUI.Docking.Skins.Style.VisualStudio2012Light;
this.dockPanel.TabIndex = 18;
//
// MainForm
//
this.ClientSize = new System.Drawing.Size(579, 409);
this.Controls.Add(this.dockPanel);
this.Controls.Add(this.toolStrip1);
this.Controls.Add(this.menuMain);
this.Controls.Add(this.statusBar);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.IsMdiContainer = true;
this.KeyPreview = true;
this.MainMenuStrip = this.menuMain;
this.Name = "MainForm";
this.Text = "Inspire";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
this.Load += new System.EventHandler(this.MainForm_Load);
this.Shown += new System.EventHandler(this.MainForm_Shown);
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MainForm_KeyPress);
this.Leave += new System.EventHandler(this.MainForm_Leave);
this.menuMain.ResumeLayout(false);
this.menuMain.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.StatusStrip statusBar;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemNewProject;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemLoadProject;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemView;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem contentExplorerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem assetExplorerToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem closeAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem4;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripMenuItem settingsMenuItem;
private System.Windows.Forms.ToolStripMenuItem pluginsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem gameToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem testToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.MenuStrip menuMain;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton buttonSaveContent;
private System.Windows.Forms.ToolStripButton buttonSaveAll;
private System.Windows.Forms.ToolStripButton toolStripButton3;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripButton cutButton;
private System.Windows.Forms.ToolStripButton buttonRedo;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel;
private System.Windows.Forms.ToolStripMenuItem layersToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tilesetsToolStripMenuItem;
private System.Windows.Forms.ToolStripButton buttonPencil;
private System.Windows.Forms.ToolStripButton buttonDropper;
private System.Windows.Forms.ToolStripButton buttonEraser;
private System.Windows.Forms.ToolStripButton buttonFill;
private System.Windows.Forms.ToolStripButton toolStripButton10;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem6;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem7;
private System.Windows.Forms.ToolStripMenuItem consoleToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripMenuItem networkMonitorToolStripMenuItem;
private System.Windows.Forms.ToolStripButton pasteButton;
private System.Windows.Forms.ToolStripButton copyButton;
private System.Windows.Forms.ToolStripButton buttonUndo;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem8;
private System.Windows.Forms.ToolStripMenuItem showMapGridToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
}
}
| |
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 PomfSharpApi.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) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Remoting.Lifetime;
using OpenMetaverse;
using Nini.Config;
using OpenSim;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Aurora.ScriptEngine.AuroraDotNetEngine.Plugins;
using LSL_Float = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLFloat;
using LSL_Integer = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLInteger;
using LSL_Key = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using LSL_List = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.list;
using LSL_Rotation = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Quaternion;
using LSL_String = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using LSL_Vector = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Vector3;
using Aurora.ScriptEngine.AuroraDotNetEngine.APIs.Interfaces;
using Aurora.ScriptEngine.AuroraDotNetEngine.Runtime;
using Aurora.Framework;
namespace Aurora.ScriptEngine.AuroraDotNetEngine.APIs
{
[Serializable]
public class LS_Api : MarshalByRefObject, ILS_Api, IScriptApi
{
internal IScriptModulePlugin m_ScriptEngine;
internal ISceneChildEntity m_host;
internal uint m_localID;
internal UUID m_itemID;
internal bool m_LSFunctionsEnabled = false;
internal IScriptModuleComms m_comms = null;
internal ScriptProtectionModule ScriptProtection;
//internal IWindLightSettingsModule m_lightShareModule;
public void Initialize(IScriptModulePlugin ScriptEngine, ISceneChildEntity host, uint localID, UUID itemID, ScriptProtectionModule module)
{
m_ScriptEngine = ScriptEngine;
m_host = host;
m_localID = localID;
m_itemID = itemID;
ScriptProtection = module;
if (m_ScriptEngine.Config.GetBoolean("AllowLightShareFunctions", false))
m_LSFunctionsEnabled = true;
m_comms = World.RequestModuleInterface<IScriptModuleComms>();
if (m_comms == null)
m_LSFunctionsEnabled = false;
}
public string Name
{
get { return "ls"; }
}
public string InterfaceName
{
get { return "ILS_Api"; }
}
/// <summary>
/// We don't have to add any assemblies here
/// </summary>
public string[] ReferencedAssemblies
{
get { return new string[0]; }
}
/// <summary>
/// We use the default namespace, so we don't have any to add
/// </summary>
public string[] NamespaceAdditions
{
get { return new string[0]; }
}
public IScriptApi Copy()
{
return new LS_Api();
}
public void Dispose()
{
}
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
// lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
// lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
public IScene World
{
get { return m_host.ParentEntity.Scene; }
}
//
//Dumps an error message on the debug console.
//
internal void LSShoutError(string message)
{
if (message.Length > 1023)
message = message.Substring(0, 1023);
IChatModule chatModule = World.RequestModuleInterface<IChatModule>();
if (chatModule != null)
chatModule.SimChat(message,
ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL,
m_host.ParentEntity.RootChild.AbsolutePosition, m_host.Name, m_host.UUID, true, World);
IWorldComm wComm = World.RequestModuleInterface<IWorldComm>();
wComm.DeliverMessage(ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.Name, m_host.UUID, message);
}
/// <summary>
/// Get the current Windlight scene
/// </summary>
/// <returns>List of windlight parameters</returns>
public LSL_List lsGetWindlightScene(LSL_List rules)
{
ScriptProtection.CheckThreatLevel(ThreatLevel.None, "lsGetWindlightScene", m_host, "LS");
/*RegionLightShareData wl = m_lightShareModule.WindLightSettings;
LSL_List values = new LSL_List();
int idx = 0;
while (idx < rules.Length)
{
uint rule = (uint)rules.GetLSLIntegerItem(idx);
LSL_List toadd = new LSL_List();
switch (rule)
{
case (int)ScriptBaseClass.WL_AMBIENT:
toadd.Add(new LSL_Rotation(wl.ambient.X, wl.ambient.Y, wl.ambient.Z, wl.ambient.W));
break;
case (int)ScriptBaseClass.WL_BIG_WAVE_DIRECTION:
toadd.Add(new LSL_Vector(wl.bigWaveDirection.X, wl.bigWaveDirection.Y, 0.0f));
break;
case (int)ScriptBaseClass.WL_BLUE_DENSITY:
toadd.Add(new LSL_Rotation(wl.blueDensity.X, wl.blueDensity.Y, wl.blueDensity.Z, wl.blueDensity.W));
break;
case (int)ScriptBaseClass.WL_BLUR_MULTIPLIER:
toadd.Add(new LSL_Float(wl.blurMultiplier));
break;
case (int)ScriptBaseClass.WL_CLOUD_COLOR:
toadd.Add(new LSL_Rotation(wl.cloudColor.X, wl.cloudColor.Y, wl.cloudColor.Z, wl.cloudColor.W));
break;
case (int)ScriptBaseClass.WL_CLOUD_COVERAGE:
toadd.Add(new LSL_Float(wl.cloudCoverage));
break;
case (int)ScriptBaseClass.WL_CLOUD_DETAIL_XY_DENSITY:
toadd.Add(new LSL_Vector(wl.cloudDetailXYDensity.X, wl.cloudDetailXYDensity.Y, wl.cloudDetailXYDensity.Z));
break;
case (int)ScriptBaseClass.WL_CLOUD_SCALE:
toadd.Add(new LSL_Float(wl.cloudScale));
break;
case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X:
toadd.Add(new LSL_Float(wl.cloudScrollX));
break;
case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X_LOCK:
toadd.Add(new LSL_Integer(wl.cloudScrollXLock ? 1 : 0));
break;
case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y:
toadd.Add(new LSL_Float(wl.cloudScrollY));
break;
case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y_LOCK:
toadd.Add(new LSL_Integer(wl.cloudScrollYLock ? 1 : 0));
break;
case (int)ScriptBaseClass.WL_CLOUD_XY_DENSITY:
toadd.Add(new LSL_Vector(wl.cloudXYDensity.X, wl.cloudXYDensity.Y, wl.cloudXYDensity.Z));
break;
case (int)ScriptBaseClass.WL_DENSITY_MULTIPLIER:
toadd.Add(new LSL_Float(wl.densityMultiplier));
break;
case (int)ScriptBaseClass.WL_DISTANCE_MULTIPLIER:
toadd.Add(new LSL_Float(wl.distanceMultiplier));
break;
case (int)ScriptBaseClass.WL_DRAW_CLASSIC_CLOUDS:
toadd.Add(new LSL_Integer(wl.drawClassicClouds ? 1 : 0));
break;
case (int)ScriptBaseClass.WL_EAST_ANGLE:
toadd.Add(new LSL_Float(wl.eastAngle));
break;
case (int)ScriptBaseClass.WL_FRESNEL_OFFSET:
toadd.Add(new LSL_Float(wl.fresnelOffset));
break;
case (int)ScriptBaseClass.WL_FRESNEL_SCALE:
toadd.Add(new LSL_Float(wl.fresnelScale));
break;
case (int)ScriptBaseClass.WL_HAZE_DENSITY:
toadd.Add(new LSL_Float(wl.hazeDensity));
break;
case (int)ScriptBaseClass.WL_HAZE_HORIZON:
toadd.Add(new LSL_Float(wl.hazeHorizon));
break;
case (int)ScriptBaseClass.WL_HORIZON:
toadd.Add(new LSL_Rotation(wl.horizon.X, wl.horizon.Y, wl.horizon.Z, wl.horizon.W));
break;
case (int)ScriptBaseClass.WL_LITTLE_WAVE_DIRECTION:
toadd.Add(new LSL_Vector(wl.littleWaveDirection.X, wl.littleWaveDirection.Y, 0.0f));
break;
case (int)ScriptBaseClass.WL_MAX_ALTITUDE:
toadd.Add(new LSL_Integer(wl.maxAltitude));
break;
case (int)ScriptBaseClass.WL_NORMAL_MAP_TEXTURE:
toadd.Add(new LSL_Key(wl.normalMapTexture.ToString()));
break;
case (int)ScriptBaseClass.WL_REFLECTION_WAVELET_SCALE:
toadd.Add(new LSL_Vector(wl.reflectionWaveletScale.X, wl.reflectionWaveletScale.Y, wl.reflectionWaveletScale.Z));
break;
case (int)ScriptBaseClass.WL_REFRACT_SCALE_ABOVE:
toadd.Add(new LSL_Float(wl.refractScaleAbove));
break;
case (int)ScriptBaseClass.WL_REFRACT_SCALE_BELOW:
toadd.Add(new LSL_Float(wl.refractScaleBelow));
break;
case (int)ScriptBaseClass.WL_SCENE_GAMMA:
toadd.Add(new LSL_Float(wl.sceneGamma));
break;
case (int)ScriptBaseClass.WL_STAR_BRIGHTNESS:
toadd.Add(new LSL_Float(wl.starBrightness));
break;
case (int)ScriptBaseClass.WL_SUN_GLOW_FOCUS:
toadd.Add(new LSL_Float(wl.sunGlowFocus));
break;
case (int)ScriptBaseClass.WL_SUN_GLOW_SIZE:
toadd.Add(new LSL_Float(wl.sunGlowSize));
break;
case (int)ScriptBaseClass.WL_SUN_MOON_COLOR:
toadd.Add(new LSL_Rotation(wl.sunMoonColor.X, wl.sunMoonColor.Y, wl.sunMoonColor.Z, wl.sunMoonColor.W));
break;
case (int)ScriptBaseClass.WL_UNDERWATER_FOG_MODIFIER:
toadd.Add(new LSL_Float(wl.underwaterFogModifier));
break;
case (int)ScriptBaseClass.WL_WATER_COLOR:
toadd.Add(new LSL_Vector(wl.waterColor.X, wl.waterColor.Y, wl.waterColor.Z));
break;
case (int)ScriptBaseClass.WL_WATER_FOG_DENSITY_EXPONENT:
toadd.Add(new LSL_Float(wl.waterFogDensityExponent));
break;
}
if (toadd.Length > 0)
{
values.Add(rule);
values.Add(toadd.Data[0]);
}
idx++;
}
return values;
*/
return null;
}
private RegionLightShareData getWindlightProfileFromRules(LSL_List rules)
{
/*RegionLightShareData wl = m_lightShareModule.WindLightSettings;
LSL_List values = new LSL_List();
int idx = 0;
while (idx < rules.Length)
{
uint rule = (uint)rules.GetLSLIntegerItem(idx);
LSL_Types.Quaternion iQ;
LSL_Types.Vector3 iV;
switch (rule)
{
case (int)ScriptBaseClass.WL_SUN_MOON_POSITION:
idx++;
wl.sunMoonPosition = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_AMBIENT:
idx++;
iQ = rules.GetQuaternionItem(idx);
wl.ambient = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s);
break;
case (int)ScriptBaseClass.WL_BIG_WAVE_DIRECTION:
idx++;
iV = rules.GetVector3Item(idx);
wl.bigWaveDirection = new Vector2((float)iV.x, (float)iV.y);
break;
case (int)ScriptBaseClass.WL_BLUE_DENSITY:
idx++;
iQ = rules.GetQuaternionItem(idx);
wl.blueDensity = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s);
break;
case (int)ScriptBaseClass.WL_BLUR_MULTIPLIER:
idx++;
wl.blurMultiplier = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_CLOUD_COLOR:
idx++;
iQ = rules.GetQuaternionItem(idx);
wl.cloudColor = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s);
break;
case (int)ScriptBaseClass.WL_CLOUD_COVERAGE:
idx++;
wl.cloudCoverage = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_CLOUD_DETAIL_XY_DENSITY:
idx++;
iV = rules.GetVector3Item(idx);
wl.cloudDetailXYDensity = new Vector3((float)iV.x, (float)iV.y, (float)iV.z);
break;
case (int)ScriptBaseClass.WL_CLOUD_SCALE:
idx++;
wl.cloudScale = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X:
idx++;
wl.cloudScrollX = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X_LOCK:
idx++;
wl.cloudScrollXLock = rules.GetLSLIntegerItem(idx).value == 1 ? true : false;
break;
case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y:
idx++;
wl.cloudScrollY = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y_LOCK:
idx++;
wl.cloudScrollYLock = rules.GetLSLIntegerItem(idx).value == 1 ? true : false;
break;
case (int)ScriptBaseClass.WL_CLOUD_XY_DENSITY:
idx++;
iV = rules.GetVector3Item(idx);
wl.cloudXYDensity = new Vector3((float)iV.x, (float)iV.y, (float)iV.z);
break;
case (int)ScriptBaseClass.WL_DENSITY_MULTIPLIER:
idx++;
wl.densityMultiplier = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_DISTANCE_MULTIPLIER:
idx++;
wl.distanceMultiplier = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_DRAW_CLASSIC_CLOUDS:
idx++;
wl.drawClassicClouds = rules.GetLSLIntegerItem(idx).value == 1 ? true : false;
break;
case (int)ScriptBaseClass.WL_EAST_ANGLE:
idx++;
wl.eastAngle = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_FRESNEL_OFFSET:
idx++;
wl.fresnelOffset = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_FRESNEL_SCALE:
idx++;
wl.fresnelScale = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_HAZE_DENSITY:
idx++;
wl.hazeDensity = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_HAZE_HORIZON:
idx++;
wl.hazeHorizon = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_HORIZON:
idx++;
iQ = rules.GetQuaternionItem(idx);
wl.horizon = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s);
break;
case (int)ScriptBaseClass.WL_LITTLE_WAVE_DIRECTION:
idx++;
iV = rules.GetVector3Item(idx);
wl.littleWaveDirection = new Vector2((float)iV.x, (float)iV.y);
break;
case (int)ScriptBaseClass.WL_MAX_ALTITUDE:
idx++;
wl.maxAltitude = (ushort)rules.GetLSLIntegerItem(idx).value;
break;
case (int)ScriptBaseClass.WL_NORMAL_MAP_TEXTURE:
idx++;
wl.normalMapTexture = new UUID(rules.GetLSLStringItem(idx).m_string);
break;
case (int)ScriptBaseClass.WL_REFLECTION_WAVELET_SCALE:
idx++;
iV = rules.GetVector3Item(idx);
wl.reflectionWaveletScale = new Vector3((float)iV.x, (float)iV.y, (float)iV.z);
break;
case (int)ScriptBaseClass.WL_REFRACT_SCALE_ABOVE:
idx++;
wl.refractScaleAbove = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_REFRACT_SCALE_BELOW:
idx++;
wl.refractScaleBelow = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_SCENE_GAMMA:
idx++;
wl.sceneGamma = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_STAR_BRIGHTNESS:
idx++;
wl.starBrightness = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_SUN_GLOW_FOCUS:
idx++;
wl.sunGlowFocus = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_SUN_GLOW_SIZE:
idx++;
wl.sunGlowSize = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_SUN_MOON_COLOR:
idx++;
iQ = rules.GetQuaternionItem(idx);
wl.sunMoonColor = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s);
break;
case (int)ScriptBaseClass.WL_UNDERWATER_FOG_MODIFIER:
idx++;
wl.underwaterFogModifier = (float)rules.GetLSLFloatItem(idx);
break;
case (int)ScriptBaseClass.WL_WATER_COLOR:
idx++;
iV = rules.GetVector3Item(idx);
wl.waterColor = new Vector4((float)iV.x, (float)iV.y, (float)iV.z, 0);
break;
case (int)ScriptBaseClass.WL_WATER_FOG_DENSITY_EXPONENT:
idx++;
wl.waterFogDensityExponent = (float)rules.GetLSLFloatItem(idx);
break;
}
idx++;
}
wl.regionID = m_host.ParentGroup.Scene.RegionInfo.RegionID;
return wl;*/
return null;
}
/// <summary>
/// Set the current Windlight scene
/// </summary>
/// <param name="rules"></param>
/// <returns>success: true or false</returns>
public int lsSetWindlightScene(LSL_List rules)
{
ScriptProtection.CheckThreatLevel(ThreatLevel.Moderate, "lsSetWindlightScene", m_host, "LS");
if (!World.RegionInfo.EstateSettings.IsEstateManager(m_host.OwnerID) && World.GetScenePresence(m_host.OwnerID).GodLevel < 200)
{
LSShoutError("lsSetWindlightScene can only be used by estate managers or owners.");
return 0;
}
int success = 0;
/*if (m_lightShareModule.EnableWindLight)
{
RegionLightShareData wl = getWindlightProfileFromRules(rules);
//m_lightShareModule.SaveWindLightSettings(0, wl);
success = 1;
}
else
{
LSShoutError("Windlight module is disabled");
return 0;
}*/
return success;
}
/// <summary>
/// Set the current Windlight scene to a target avatar
/// </summary>
/// <param name="rules"></param>
/// <returns>success: true or false</returns>
public int lsSetWindlightSceneTargeted(LSL_List rules, LSL_Key target)
{
if (!m_LSFunctionsEnabled)
{
LSShoutError("LightShare functions are not enabled.");
return 0;
}
if (!World.RegionInfo.EstateSettings.IsEstateManager(m_host.OwnerID) && World.GetScenePresence(m_host.OwnerID).GodLevel < 200)
{
LSShoutError("lsSetWindlightSceneTargeted can only be used by estate managers or owners.");
return 0;
}
int success = 0;
/*if (m_lightShareModule.EnableWindLight)
{
RegionLightShareData wl = getWindlightProfileFromRules(rules);
m_lightShareModule.SendWindlightProfileTargeted(wl, new UUID(target.m_string));
success = 1;
}
else
{
LSShoutError("Windlight module is disabled");
return 0;
}*/
return success;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Network.Fluent
{
using ApplicationGatewayListener.Definition;
using ApplicationGatewayListener.UpdateDefinition;
using Models;
using ResourceManager.Fluent.Core;
using System.IO;
using ResourceManager.Fluent.Core.ChildResourceActions;
using ResourceManager.Fluent;
/// <summary>
/// Implementation for ApplicationGatewayListener.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm5ldHdvcmsuaW1wbGVtZW50YXRpb24uQXBwbGljYXRpb25HYXRld2F5TGlzdGVuZXJJbXBs
internal partial class ApplicationGatewayListenerImpl :
ChildResource<ApplicationGatewayHttpListenerInner, ApplicationGatewayImpl, IApplicationGateway>,
IApplicationGatewayListener,
IDefinition<ApplicationGateway.Definition.IWithCreate>,
IUpdateDefinition<ApplicationGateway.Update.IUpdate>,
ApplicationGatewayListener.Update.IUpdate
{
///GENMHASH:FDD79F9F4A54F00F3D88A305BD6E4101:C0847EA0CDA78F6D91EFD239C70F0FA7
internal ApplicationGatewayListenerImpl(ApplicationGatewayHttpListenerInner inner, ApplicationGatewayImpl parent) : base(inner, parent)
{
}
#region Withers
///GENMHASH:5ACBA6D500464D19A23A5A5A6A184B79:3CAED6F38D63250A1D8283E364506FF5
public ApplicationGatewayListenerImpl WithHostName(string hostname)
{
Inner.HostName = hostname;
return this;
}
///GENMHASH:CB6B71434C2E17A82873B7892EE00D55:5B3EF817B7C74BB136E1CA2B7400D046
public ApplicationGatewayListenerImpl WithoutServerNameIndication()
{
Inner.RequireServerNameIndication = false;
return this;
}
///GENMHASH:7C5A670BDA8BF576E8AFC752CD10A797:588DD8355CC6B8BBA6CED27FD5C42C76
public ApplicationGatewayListenerImpl WithPrivateFrontend()
{
WithFrontend(Parent.EnsureDefaultPrivateFrontend().Name());
return this;
}
///GENMHASH:1D7C0E3D335976570E947F3D48437E66:90F5612F9FB70607B79E07A32AEB8B8D
public ApplicationGatewayListenerImpl WithSslCertificate(string name)
{
var certRef = new SubResource()
{
Id = Parent.FutureResourceId() + "/sslCertificates/" + name
};
Inner.SslCertificate = certRef;
return this;
}
///GENMHASH:FA888A1E446DDA9E368D1EF43B428BAC:0FE70D5AE03341449A2D980808F522FC
public ApplicationGatewayListenerImpl WithHttps()
{
Inner.Protocol = ApplicationGatewayProtocol.Https;
return this;
}
///GENMHASH:FD5739AFD5E74CB55C9C465B3661FBF2:393821A9A3F65B68E26BFBEA4350B3DD
public ApplicationGatewayListenerImpl WithFrontendPort(string name)
{
SubResource portRef = new SubResource()
{
Id = Parent.FutureResourceId() + "/frontendPorts/" + name
};
Inner.FrontendPort = portRef;
return this;
}
///GENMHASH:1E7046ABBFA82B3370C0EE4358FCAAB3:B63632305CE5D2C6D9FE2C2AE6DFF9D7
public ApplicationGatewayListenerImpl WithFrontendPort(int portNumber)
{
// Attempt to find an existing port referencing this port number
string portName = Parent.FrontendPortNameFromNumber(portNumber);
if (portName == null)
{
// Existing frontend port with this number not found so create one
portName = SdkContext.RandomResourceName("port", 9);
Parent.WithFrontendPort(portNumber, portName);
}
return WithFrontendPort(portName);
}
///GENMHASH:8214BDBBC03F37877598DD319CF9DA28:6A89D21D1F64E0716C2BB0607B2B985E
public ApplicationGatewayListenerImpl WithPublicFrontend()
{
WithFrontend(Parent.EnsureDefaultPublicFrontend().Name());
return this;
}
///GENMHASH:2EC798C5560EA4F2234EFA1478E59C04:409B6655E16BAB2E8CCE5B4E431083EE
private ApplicationGatewayListenerImpl WithFrontend(string name)
{
var frontendRef = new SubResource()
{
Id = Parent.FutureResourceId() + "/frontendIPConfigurations/" + name
};
Inner.FrontendIPConfiguration = frontendRef;
return this;
}
///GENMHASH:85408D425EF4341A6D39C75F68ED8A2B:60CB6094D3C3120ABC72B2E26313EF5A
public ApplicationGatewayListenerImpl WithServerNameIndication()
{
Inner.RequireServerNameIndication = true;
return this;
}
///GENMHASH:604F12B361C77B3E3AD5768A73BA6DCF:ABADA5A8E77FDA08CD893ADDC4895F32
public ApplicationGatewayListenerImpl WithHttp()
{
Inner.Protocol = ApplicationGatewayProtocol.Http;
return this;
}
///GENMHASH:AFBFDB5617AA4227641C045CF9D86F66:EB7981C52FAC33B9BCE219D5852A1E18
public ApplicationGatewayListenerImpl WithSslCertificateFromPfxFile(FileInfo pfxFile)
{
return WithSslCertificateFromPfxFile(pfxFile, null);
}
///GENMHASH:8ADE3A1B894E5D01B188A0822FC89126:8F3C216CEC2F2F3C970738DE571B9D47
private ApplicationGatewayListenerImpl WithSslCertificateFromPfxFile(FileInfo pfxFile, string name)
{
if (name == null)
{
name = SdkContext.RandomResourceName("cert", 10);
}
Parent.DefineSslCertificate(name)
.WithPfxFromFile(pfxFile)
.Attach();
return WithSslCertificate(name);
}
///GENMHASH:382D2BF4EBC04F5E7DF95B5EF5A97146:C01DAB0F887720B1B1F54C7664754686
public ApplicationGatewayListenerImpl WithSslCertificatePassword(string password)
{
var sslCert = (ApplicationGatewaySslCertificateImpl)SslCertificate();
if (sslCert != null)
{
sslCert.WithPfxPassword(password);
}
return this;
}
#endregion
#region Accessors
///GENMHASH:A80C3FC8655E547C3392C10C546FFF39:F5F48992AF3FBAF8C1BC9C9A59C415FF
public bool RequiresServerNameIndication()
{
return (Inner.RequireServerNameIndication != null) ? Inner.RequireServerNameIndication.Value : false;
}
///GENMHASH:3E38805ED0E7BA3CAEE31311D032A21C:61C1065B307679F3800C701AE0D87070
public override string Name()
{
return Inner.Name;
}
///GENMHASH:5EF934D4E2CF202DF23C026435D9F6D6:4A43E80905D41DF094F9B704945856D1
public string PublicIPAddressId()
{
var frontend = Frontend();
return (frontend != null) ? frontend.PublicIPAddressId : null;
}
///GENMHASH:B206A6556439FF2D98365C5283836AD5:125C0E491D4D29CEE8322DF9019C1DE7
public IApplicationGatewayFrontend Frontend()
{
var frontendInner = Inner.FrontendIPConfiguration;
if (frontendInner == null)
{
return null;
}
string frontendName = ResourceUtils.NameFromResourceId(frontendInner.Id);
IApplicationGatewayFrontend frontend;
return (Parent.Frontends().TryGetValue(frontendName, out frontend)) ? frontend : null;
}
ApplicationGateway.Update.IUpdate ISettable<ApplicationGateway.Update.IUpdate>.Parent()
{
return Parent;
}
///GENMHASH:1C444C90348D7064AB23705C542DDF18:ADFE7EEA0734BA251C7A2C00B4ED3531
public string NetworkId()
{
var frontend = Frontend();
return (frontend != null) ? frontend.NetworkId : null;
}
///GENMHASH:C57133CD301470A479B3BA07CD283E86:251CDCA01439FEEC30E23AD50DA1453A
public string SubnetName()
{
var frontend = Frontend();
return (frontend != null) ? frontend.SubnetName : null;
}
///GENMHASH:E40B3F1FA93E71A00314196726D4960B:B71AFF4FEE8DFD54B2E5B5F488E605CC
public string FrontendPortName()
{
return (Inner.FrontendPort != null) ? ResourceUtils.NameFromResourceId(Inner.FrontendPort.Id) : null;
}
///GENMHASH:D684E7477889A9013C81FAD82F69C54F:BD249A015EF71106387B78281489583A
public ApplicationGatewayProtocol Protocol()
{
return Inner.Protocol;
}
///GENMHASH:1207E16326E66DA6A51CBA6F0565D088:3F3B707B427A3370160F5D3A76951425
public IApplicationGatewaySslCertificate SslCertificate()
{
var certRef = Inner.SslCertificate;
if (certRef == null)
{
return null;
}
string name = ResourceUtils.NameFromResourceId(certRef.Id);
IApplicationGatewaySslCertificate cert = null;
return (Parent.SslCertificates().TryGetValue(name, out cert)) ? cert : null;
}
///GENMHASH:A50A011CA652E846C1780DCE98D171DE:1130E1FDC5A612FAE78D6B24DD71D43E
public string HostName()
{
return Inner.HostName;
}
///GENMHASH:EB912111C9441B9619D3AD0CCFB7E471:98FC7DF998F67011FCA026433ADD5507
public int FrontendPortNumber()
{
string name = FrontendPortName();
if (name == null)
{
return 0;
}
else
{
int portNumber = 0;
return (Parent.FrontendPorts().TryGetValue(name, out portNumber)) ? portNumber : 0;
}
}
#endregion
#region Actions
///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:0C6B6B4DD8E378E1E80FAA7AD88AD383
public ApplicationGatewayImpl Attach()
{
Parent.WithHttpListener(this);
return Parent;
}
///GENMHASH:166583FE514624A3D800151836CD57C1:CC312A186A3A88FA6CF6445A4520AE59
public IPublicIPAddress GetPublicIPAddress()
{
string pipId = PublicIPAddressId();
return (pipId != null) ? Parent.Manager.PublicIPAddresses.GetById(pipId) : null;
}
#endregion
}
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using Gtk;
using SailorsTab.Common;
namespace SailorsTab.Tabmin
{
public class ObjectEditorWindow<T> : Window, IObjectEditor<T>
{
private bool initialized;
private SortedDictionary<String, Property> properties = new SortedDictionary<String, Property>();
private T currentObject;
private Table table;
private Button opslaanButton;
private Button annulerenButton;
public ObjectEditorWindow() : base(WindowType.Toplevel) { }
public void EditObject(T obj, Action<T> saveObjectFunc)
{
lock(this)
{
if (initialized)
{
throw new InvalidOperationException("ObjectEditorWindow has already been initialized.");
}
Initialize(obj, saveObjectFunc);
initialized = true;
}
ShowAll();
}
protected void Initialize(T obj, Action<T> saveObjectFunc)
{
currentObject = obj;
loadProperties(obj);
Modal = true;
table = new Table((uint)properties.Count + 1, 2, false);
uint index = 0;
foreach(Property property in properties.Values)
{
table.Attach(property.Label, 0, 1, index, index + 1);
table.Attach(property.GetWidget(), 1, 2, index, index + 1);
index++;
}
opslaanButton = new Button("Opslaan");
opslaanButton.Clicked += delegate {
foreach(string name in properties.Keys)
{
if (!ValidateValue(name, properties[name].GetValue()))
{
UIHelper.ShowErrorDialog(this, "De waarde van '{0}' is ongeldig", name);
return;
}
}
try
{
updateObject();
}
catch(Exception ex)
{
UIHelper.ShowErrorDialog(this, "Kan properties niet parsen: " + ex.Message);
return;
}
saveObjectFunc(obj);
Destroy();
};
table.Attach(opslaanButton, 0, 1, index + 1, index + 2);
annulerenButton = new Button("Annuleren");
annulerenButton.Clicked += delegate {
Destroy();
};
table.Attach(annulerenButton, 1, 2, index + 1, index + 2);
Add(table);
}
protected virtual string[] GetIncludedProperties()
{
// To be overriden
return null;
}
protected virtual bool ValidateValue(string property, object value)
{
// To be overriden
return true;
}
private void updateObject()
{
foreach(string name in properties.Keys)
{
object value = parseValue(properties[name].GetValue().ToString(), properties[name].PropertyInfo.PropertyType);
properties[name].PropertyInfo.SetValue(currentObject, value, null);
}
}
private object parseValue(string value, Type requestedType)
{
if (requestedType == typeof(double))
{
return double.Parse(value);
}
else if (requestedType == typeof(string))
{
return value;
}
else if (requestedType == typeof(decimal))
{
return decimal.Parse(value);
}
else if (requestedType == typeof(int))
{
return int.Parse(value);
}
else
{
throw new NotSupportedException("Cannot convert value to type '" + requestedType + "', not supported");
}
}
private void loadProperties(T obj)
{
PropertyInfo[] propertiesInfo = obj.GetType().GetProperties();
string[] includedProperties = GetIncludedProperties();
foreach(var propertyInfo in propertiesInfo)
{
if (includedProperties != null && includedProperties.Contains(propertyInfo.Name))
{
Property property = new TextProperty(propertyInfo);
property.SetValue(propertyInfo.GetValue(obj, null));
properties.Add(propertyInfo.Name, property);
}
}
}
private abstract class Property
{
public PropertyInfo PropertyInfo { get; private set; }
public Label Label { get; private set; }
public Property(PropertyInfo propertyInfo)
{
PropertyInfo = propertyInfo;
Label = new Label();
Label.Text = propertyInfo.Name;
}
public String LabelText
{
get { return Label.Text; }
set { Label.Text = value; }
}
public abstract void SetValue(object value);
public abstract object GetValue();
public abstract Widget GetWidget();
}
private class TextProperty : Property
{
public TextView Field { get; private set; }
public TextProperty(PropertyInfo propertyInfo) : base(propertyInfo)
{
TextBuffer buffer = new TextBuffer(new TextTagTable());
Field = new TextView(buffer);
Field.Buffer.Text = "";
}
public override void SetValue (object value)
{
Field.Buffer.Text = value == null ? "" : value.ToString();
}
public override object GetValue ()
{
return Field.Buffer.Text;
}
public override Widget GetWidget()
{
return Field;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Animation;
namespace Avalon.Windows.Media.Animation
{
/// <summary>
/// Animates the value of a <typeparamref name="T" /> property along a set of
/// <see cref="KeyFramesAnimationBase{T}.KeyFrames" />.
/// </summary>
/// <typeparam name="T"></typeparam>
[ContentProperty("KeyFrames")]
public abstract class KeyFramesAnimationBase<T> : AnimationBase<T>, IKeyFrameAnimation, IAddChild
where T : struct
{
#region Fields
private bool _areKeyTimesValid = true;
private KeyFrameCollection<T> _keyFrames;
private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
#endregion
#region IAddChild Methods
/// <summary>Adds a child <see cref="KeyFrame{T}" /> to this <see cref="KeyFramesAnimationBase{T}" />. </summary>
/// <param name="child">The object to be added as the child of this <see cref="KeyFramesAnimationBase{T}" />. </param>
/// <exception cref="System.ArgumentException">The parameter child is not a <see cref="KeyFrame{T}" />.</exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddChild(object child)
{
var keyFrame = child as KeyFrame<T>;
if (keyFrame == null)
{
throw new ArgumentException(
string.Format(CultureInfo.CurrentCulture, SR.KeyFramesAnimationBase_ChildNotKeyFrame,
typeof(T).Name), "child");
}
KeyFrames.Add(keyFrame);
}
/// <summary>Adds a text string as a child of this <see cref="KeyFramesAnimationBase{T}" />.</summary>
/// <param name="childText">The text added to the <see cref="KeyFramesAnimationBase{T}" />.</param>
/// <exception cref="System.InvalidOperationException">
/// A <see cref="KeyFramesAnimationBase{T}" /> does not accept text as a
/// child, so this method will raise this exception unless a derived class has overridden this behavior which allows
/// text to be added.
/// </exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddText(string childText)
{
throw new InvalidOperationException("Text children not allowed.");
}
void IAddChild.AddChild(object child)
{
WritePreamble();
if (child == null)
{
throw new ArgumentNullException("child");
}
AddChild(child);
WritePostscript();
}
void IAddChild.AddText(string childText)
{
if (childText == null)
{
throw new ArgumentNullException("childText");
}
AddText(childText);
}
#endregion
#region Clone/Freeze Methods
/// <summary>
/// Creates a modifiable clone of this <see cref="KeyFramesAnimationBase{T}" />, making deep copies of this
/// object's values. When copying dependency properties, this method copies resource references and data bindings (but
/// they might no longer resolve) but not animations or their current values.
/// </summary>
/// <returns>
/// A modifiable clone of the current object. The cloned object's <see cref="System.Windows.Freezable.IsFrozen" />
/// property will be false even if the source's <see cref="System.Windows.Freezable.IsFrozen" /> property was true.
/// </returns>
public new KeyFramesAnimationBase<T> Clone()
{
return (KeyFramesAnimationBase<T>)base.Clone();
}
/// <summary>
/// Makes this instance a deep copy of the specified <see cref="KeyFramesAnimationBase{T}" />. When copying
/// dependency properties, this method copies resource references and data bindings (but they might no longer resolve)
/// but not animations or their current values.
/// </summary>
/// <param name="sourceFreezable">The <see cref="KeyFramesAnimationBase{T}" /> to clone.</param>
protected override void CloneCore(Freezable sourceFreezable)
{
var frames = (KeyFramesAnimationBase<T>)sourceFreezable;
base.CloneCore(sourceFreezable);
CopyCommon(frames, false);
}
/// <summary>
/// Creates a modifiable clone of this <see cref="KeyFramesAnimationBase{T}" /> object, making deep copies of this
/// object's current values. Resource references, data bindings, and animations are not copied, but their current
/// values are.
/// </summary>
/// <returns>
/// A modifiable clone of the current object. The cloned object's <see cref="System.Windows.Freezable.IsFrozen" />
/// property will be false even if the source's <see cref="System.Windows.Freezable.IsFrozen" /> property was true.
/// </returns>
public new KeyFramesAnimationBase<T> CloneCurrentValue()
{
return (KeyFramesAnimationBase<T>)base.CloneCurrentValue();
}
/// <summary>
/// Makes this instance a modifiable deep copy of the specified <see cref="KeyFramesAnimationBase{T}" /> using
/// current property values. Resource references, data bindings, and animations are not copied, but their current
/// values are.
/// </summary>
/// <param name="sourceFreezable">The <see cref="KeyFramesAnimationBase{T}" /> to clone.</param>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
var anim = (KeyFramesAnimationBase<T>)sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
CopyCommon(anim, true);
}
private void CopyCommon(KeyFramesAnimationBase<T> sourceAnimation, bool isCurrentValueClone)
{
_areKeyTimesValid = sourceAnimation._areKeyTimesValid;
if (_areKeyTimesValid && (sourceAnimation._sortedResolvedKeyFrames != null))
{
_sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone();
}
if (sourceAnimation._keyFrames != null)
{
if (isCurrentValueClone)
{
_keyFrames = (KeyFrameCollection<T>)sourceAnimation._keyFrames.CloneCurrentValue();
}
else
{
_keyFrames = sourceAnimation._keyFrames.Clone();
}
OnFreezablePropertyChanged(null, _keyFrames);
}
}
/// <summary>Creates a new instance of <see cref="KeyFramesAnimationBase{T}" />. </summary>
/// <returns>A new instance of <see cref="KeyFramesAnimationBase{T}" />.</returns>
protected abstract override Freezable CreateInstanceCore();
/// <summary>
/// Makes this instance of <see cref="KeyFramesAnimationBase{T}" /> object unmodifiable or determines whether it
/// can be made unmodifiable..
/// </summary>
/// <returns>
/// If isChecking is true, this method returns true if this <see cref="KeyFramesAnimationBase{T}" /> can be made
/// unmodifiable, or false if it cannot be made unmodifiable. If isChecking is false, this method returns true if the
/// specified <see cref="KeyFramesAnimationBase{T}" /> is now unmodifiable, or false if it cannot be made unmodifiable,
/// with the side effect of having made the actual change in frozen status to this object.
/// </returns>
/// <param name="isChecking">
/// true if the <see cref="KeyFramesAnimationBase{T}" /> instance should actually freeze itself
/// when this method is called. false if the <see cref="KeyFramesAnimationBase{T}" /> instance should simply return
/// whether it can be frozen.
/// </param>
protected override bool FreezeCore(bool isChecking)
{
bool freeze = base.FreezeCore(isChecking) && Freeze(_keyFrames, isChecking);
if (freeze & !_areKeyTimesValid)
{
ResolveKeyTimes();
}
return freeze;
}
/// <summary>Makes this instance a clone of the specified <see cref="KeyFramesAnimationBase{T}" /> object. </summary>
/// <param name="sourceFreezable">The <see cref="KeyFramesAnimationBase{T}" /> object to clone.</param>
protected override void GetAsFrozenCore(Freezable sourceFreezable)
{
var frames = (KeyFramesAnimationBase<T>)sourceFreezable;
base.GetAsFrozenCore(sourceFreezable);
CopyCommon(frames, false);
}
/// <summary>
/// Makes this instance a frozen clone of the specified <see cref="KeyFramesAnimationBase{T}" />. Resource
/// references, data bindings, and animations are not copied, but their current values are.
/// </summary>
/// <param name="sourceFreezable">The <see cref="KeyFramesAnimationBase{T}" /> to copy and freeze.</param>
protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable)
{
var frames = (KeyFramesAnimationBase<T>)sourceFreezable;
base.GetCurrentValueAsFrozenCore(sourceFreezable);
CopyCommon(frames, true);
}
#endregion
#region Animation Methods
/// <summary>
/// Calculates a value that represents the current value of the property being animated, as determined by this
/// instance of <see cref="KeyFramesAnimationBase{T}" />.
/// </summary>
/// <returns>The calculated value of the property, as determined by the current instance.</returns>
/// <param name="defaultOriginValue">
/// The suggested origin value, used if the animation does not have its own explicitly set
/// start value.
/// </param>
/// <param name="defaultDestinationValue">
/// The suggested destination value, used if the animation does not have its own
/// explicitly set end value.
/// </param>
/// <param name="animationClock">
/// An <see cref="System.Windows.Media.Animation.AnimationClock" /> that generates the
/// <see cref="System.Windows.Media.Animation.Clock.CurrentTime" /> or
/// <see cref="System.Windows.Media.Animation.Clock.CurrentProgress" /> used by the host animation.
/// </param>
protected override sealed T GetCurrentValueCore(T defaultOriginValue, T defaultDestinationValue,
AnimationClock animationClock)
{
T value;
if (_keyFrames == null)
{
return defaultDestinationValue;
}
if (!_areKeyTimesValid)
{
ResolveKeyTimes();
}
if (_sortedResolvedKeyFrames == null)
{
return defaultDestinationValue;
}
// ReSharper disable once PossibleInvalidOperationException
TimeSpan currentTime = animationClock.CurrentTime.Value;
int frames = _sortedResolvedKeyFrames.Length;
int lastFrameIndex = frames - 1;
int frameCount = 0;
while ((frameCount < frames) && (currentTime > _sortedResolvedKeyFrames[frameCount].resolvedKeyTime))
{
frameCount++;
}
while ((frameCount < lastFrameIndex) &&
(currentTime == _sortedResolvedKeyFrames[frameCount + 1].resolvedKeyTime))
{
frameCount++;
}
if (frameCount == frames)
{
value = GetResolvedKeyFrameValue(lastFrameIndex);
}
else if (currentTime == _sortedResolvedKeyFrames[frameCount].resolvedKeyTime)
{
value = GetResolvedKeyFrameValue(frameCount);
}
else
{
T newValue;
double progress;
if (frameCount == 0)
{
newValue = IsAdditive ? Calculator.GetZeroValue(defaultOriginValue) : defaultOriginValue;
progress = currentTime.TotalMilliseconds /
_sortedResolvedKeyFrames[0].resolvedKeyTime.TotalMilliseconds;
}
else
{
int prevFrame = frameCount - 1;
TimeSpan keyTime = _sortedResolvedKeyFrames[prevFrame].resolvedKeyTime;
newValue = GetResolvedKeyFrameValue(prevFrame);
TimeSpan timeDiff = currentTime - keyTime;
TimeSpan totalTimeDiff = _sortedResolvedKeyFrames[frameCount].resolvedKeyTime - keyTime;
progress = timeDiff.TotalMilliseconds / totalTimeDiff.TotalMilliseconds;
}
value = GetResolvedKeyFrame(frameCount).InterpolateValue(newValue, progress);
}
if (IsCumulative)
{
int? currentIteration = animationClock.CurrentIteration;
currentIteration = currentIteration - 1;
double currentValue = currentIteration.GetValueOrDefault();
if (currentValue > 0)
{
value = Calculator.Add(value,
Calculator.Scale(GetResolvedKeyFrameValue(lastFrameIndex), currentValue));
}
}
if (IsAdditive)
{
return Calculator.Add(defaultOriginValue, value);
}
return value;
}
/// <summary>
/// Provide a custom natural <see cref="System.Windows.Duration" /> when the
/// <see cref="System.Windows.Duration" /> property is set to <see cref="System.Windows.Duration.Automatic" />.
/// </summary>
/// <returns>
/// If the last key frame of this animation is a <see cref="System.Windows.Media.Animation.KeyTime" />, then this
/// value is used as the <see cref="System.Windows.Media.Animation.Clock.NaturalDuration" />; otherwise it will be one
/// second.
/// </returns>
/// <param name="clock">The <see cref="System.Windows.Media.Animation.Clock" /> whose natural duration is desired.</param>
protected override sealed Duration GetNaturalDurationCore(Clock clock)
{
return new Duration(LargestTimeSpanKeyTime);
}
private KeyFrame<T> GetResolvedKeyFrame(int resolvedKeyFrameIndex)
{
return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex].originalKeyFrameIndex];
}
private T GetResolvedKeyFrameValue(int resolvedKeyFrameIndex)
{
return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value;
}
/// <summary>Called when the current <see cref="KeyFramesAnimationBase{T}" /> object is modified.</summary>
protected override void OnChanged()
{
_areKeyTimesValid = false;
base.OnChanged();
}
private void ResolveKeyTimes()
{
int keyFramesCount = 0;
if (_keyFrames != null)
{
keyFramesCount = _keyFrames.Count;
}
if (keyFramesCount == 0)
{
_sortedResolvedKeyFrames = null;
_areKeyTimesValid = true;
}
else
{
_sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFramesCount];
int currentFrameIndex = 0;
while (currentFrameIndex < keyFramesCount)
{
_sortedResolvedKeyFrames[currentFrameIndex].originalKeyFrameIndex = currentFrameIndex;
currentFrameIndex++;
}
Duration duration = Duration;
var time = duration.HasTimeSpan ? duration.TimeSpan : LargestTimeSpanKeyTime;
int lastKeyFrameIndex = keyFramesCount - 1;
List<KeyTimeBlock> blocks = new List<KeyTimeBlock>();
bool isPaced = false;
currentFrameIndex = 0;
while (currentFrameIndex < keyFramesCount)
{
// ReSharper disable once PossibleNullReferenceException
KeyTime keyTime = _keyFrames[currentFrameIndex].KeyTime;
switch (keyTime.Type)
{
case KeyTimeType.Uniform:
case KeyTimeType.Paced:
{
if (currentFrameIndex != lastKeyFrameIndex)
{
break;
}
_sortedResolvedKeyFrames[currentFrameIndex].resolvedKeyTime = time;
currentFrameIndex++;
continue;
}
case KeyTimeType.Percent:
{
_sortedResolvedKeyFrames[currentFrameIndex].resolvedKeyTime =
TimeSpan.FromMilliseconds(keyTime.Percent * time.TotalMilliseconds);
currentFrameIndex++;
continue;
}
case KeyTimeType.TimeSpan:
{
_sortedResolvedKeyFrames[currentFrameIndex].resolvedKeyTime = keyTime.TimeSpan;
currentFrameIndex++;
continue;
}
default:
{
continue;
}
}
if ((currentFrameIndex == 0) && (keyTime.Type == KeyTimeType.Paced))
{
_sortedResolvedKeyFrames[currentFrameIndex].resolvedKeyTime = TimeSpan.Zero;
currentFrameIndex++;
continue;
}
if (keyTime.Type == KeyTimeType.Paced)
{
isPaced = true;
}
KeyTimeBlock block = new KeyTimeBlock { BeginIndex = currentFrameIndex };
while (++currentFrameIndex < lastKeyFrameIndex)
{
KeyTimeType keyTimeType = _keyFrames[currentFrameIndex].KeyTime.Type;
if (keyTimeType == KeyTimeType.Paced)
{
isPaced = true;
}
}
block.EndIndex = currentFrameIndex;
blocks.Add(block);
}
foreach (KeyTimeBlock block in blocks)
{
TimeSpan blockTime = TimeSpan.Zero;
if (block.BeginIndex > 0)
{
blockTime = _sortedResolvedKeyFrames[block.BeginIndex - 1].resolvedKeyTime;
}
long blockIndices = (block.EndIndex - block.BeginIndex) + 1;
TimeSpan blockTimeDiff = _sortedResolvedKeyFrames[block.EndIndex].resolvedKeyTime - blockTime;
TimeSpan blockAvgTime = TimeSpan.FromTicks(blockTimeDiff.Ticks / blockIndices);
currentFrameIndex = block.BeginIndex;
TimeSpan currentBlockTime = blockTime + blockAvgTime;
while (currentFrameIndex < block.EndIndex)
{
_sortedResolvedKeyFrames[currentFrameIndex].resolvedKeyTime = currentBlockTime;
currentBlockTime += blockAvgTime;
currentFrameIndex++;
}
}
if (isPaced)
{
ResolvePacedKeyTimes();
}
Array.Sort(_sortedResolvedKeyFrames);
_areKeyTimesValid = true;
}
}
private void ResolvePacedKeyTimes()
{
int count = 1;
int lastFrameIndex = _sortedResolvedKeyFrames.Length - 1;
do
{
if (_keyFrames[count].KeyTime.Type == KeyTimeType.Paced)
{
int originalCount = count;
List<double> segLengthSums = new List<double>();
TimeSpan time = _sortedResolvedKeyFrames[count - 1].resolvedKeyTime;
double segLengthSum = 0;
T value = _keyFrames[count - 1].Value;
do
{
T newValue = _keyFrames[count].Value;
segLengthSum += Calculator.GetSegmentLength(value, newValue);
segLengthSums.Add(segLengthSum);
value = newValue;
count++;
} while ((count < lastFrameIndex) && (_keyFrames[count].KeyTime.Type == KeyTimeType.Paced));
segLengthSum += Calculator.GetSegmentLength(value, _keyFrames[count].Value);
TimeSpan timeDiff = _sortedResolvedKeyFrames[count].resolvedKeyTime - time;
for (int i = 0, j = originalCount; i < segLengthSums.Count; j++)
{
_sortedResolvedKeyFrames[j].resolvedKeyTime = time +
TimeSpan.FromMilliseconds((segLengthSums[i] /
segLengthSum) *
timeDiff
.TotalMilliseconds);
i++;
}
}
else
{
count++;
}
} while (count < lastFrameIndex);
}
/// <summary>
/// Returns true if the value of the <see cref="KeyFramesAnimationBase{T}.KeyFrames" /> property of this instance
/// of <see cref="KeyFramesAnimationBase{T}" /> should be value-serialized.
/// </summary>
/// <returns>true if the property value should be serialized; otherwise, false.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeKeyFrames()
{
ReadPreamble();
if (_keyFrames != null)
{
return (_keyFrames.Count > 0);
}
return false;
}
#endregion
#region Properties
/// <summary> Gets or sets the collection of <see cref="KeyFrame{T}" /> objects that define the animation. </summary>
/// <returns>
/// The collection of <see cref="KeyFrame{T}" /> objects that define the animation. The default value is
/// <see cref="KeyFrameCollection{T}.Empty" />.
/// </returns>
public KeyFrameCollection<T> KeyFrames
{
get
{
ReadPreamble();
if (_keyFrames == null)
{
if (IsFrozen)
{
_keyFrames = KeyFrameCollection<T>.Empty;
}
else
{
WritePreamble();
_keyFrames = new KeyFrameCollection<T>();
OnFreezablePropertyChanged(null, _keyFrames);
WritePostscript();
}
}
return _keyFrames;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
WritePreamble();
if (!ReferenceEquals(_keyFrames, value))
{
OnFreezablePropertyChanged(_keyFrames, value);
_keyFrames = value;
WritePostscript();
}
}
}
private TimeSpan LargestTimeSpanKeyTime
{
get
{
bool success = false;
TimeSpan time = TimeSpan.Zero;
if (_keyFrames != null)
{
foreach (var keyFrame in _keyFrames)
{
KeyTime newTime = keyFrame.KeyTime;
if (newTime.Type == KeyTimeType.TimeSpan)
{
success = true;
if (newTime.TimeSpan > time)
{
time = newTime.TimeSpan;
}
}
}
}
if (success)
{
return time;
}
return TimeSpan.FromSeconds(1);
}
}
IList IKeyFrameAnimation.KeyFrames
{
get { return KeyFrames; }
set { KeyFrames = (KeyFrameCollection<T>)value; }
}
#endregion
#region Structures
[StructLayout(LayoutKind.Sequential)]
private struct KeyTimeBlock
{
public int BeginIndex;
public int EndIndex;
}
[StructLayout(LayoutKind.Sequential)]
internal struct ResolvedKeyFrameEntry : IComparable<ResolvedKeyFrameEntry>
{
internal int originalKeyFrameIndex;
internal TimeSpan resolvedKeyTime;
public int CompareTo(ResolvedKeyFrameEntry other)
{
if (other.resolvedKeyTime > resolvedKeyTime)
{
return -1;
}
if (other.resolvedKeyTime < resolvedKeyTime)
{
return 1;
}
if (other.originalKeyFrameIndex > originalKeyFrameIndex)
{
return -1;
}
if (other.originalKeyFrameIndex < originalKeyFrameIndex)
{
return 1;
}
return 0;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Exceptions;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public class ParserTest
{
/// <summary>
/// Make a fake element location for methods who need one.
/// </summary>
private MockElementLocation _elementLocation = MockElementLocation.Instance;
/// <summary>
/// </summary>
[Fact]
public void SimpleParseTest()
{
Console.WriteLine("SimpleParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
tree = p.Parse("$(foo)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("$(foo)=='hello'", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("$(foo)==''", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("$(debug) and $(buildlab) and $(full)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("$(debug) or $(buildlab) or $(full)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("$(debug) and $(buildlab) or $(full)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("$(full) or $(debug) and $(buildlab)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("%(culture)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("%(culture)=='french'", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("'foo_%(culture)'=='foo_french'", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("true", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("false", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("0", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("0.0 == 0", ParserOptions.AllowAll, _elementLocation);
}
/// <summary>
/// </summary>
[Fact]
public void ComplexParseTest()
{
Console.WriteLine("ComplexParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
tree = p.Parse("$(foo)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("($(foo) or $(bar)) and $(baz)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("$(foo) <= 5 and $(bar) >= 15", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("(($(foo) <= 5 and $(bar) >= 15) and $(baz) == simplestring) and 'a more complex string' != $(quux)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("(($(foo) or $(bar) == false) and !($(baz) == simplestring))", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("(($(foo) or Exists('c:\\foo.txt')) and !(($(baz) == simplestring)))", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("'CONTAINS%27QUOTE%27' == '$(TestQuote)'", ParserOptions.AllowAll, _elementLocation);
}
/// <summary>
/// </summary>
[Fact]
public void NotParseTest()
{
Console.WriteLine("NegationParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
tree = p.Parse("!true", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("!(true)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("!($(foo) <= 5)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("!(%(foo) <= 5)", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("!($(foo) <= 5 and $(bar) >= 15)", ParserOptions.AllowAll, _elementLocation);
}
/// <summary>
/// </summary>
[Fact]
public void FunctionCallParseTest()
{
Console.WriteLine("FunctionCallParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
tree = p.Parse("SimpleFunctionCall()", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("SimpleFunctionCall( 1234 )", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("SimpleFunctionCall( true )", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("SimpleFunctionCall( $(property) )", ParserOptions.AllowAll, _elementLocation);
tree = p.Parse("SimpleFunctionCall( $(property), 1234, abcd, 'abcd efgh' )", ParserOptions.AllowAll, _elementLocation);
}
[Fact]
public void ItemListParseTest()
{
Console.WriteLine("FunctionCallParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
bool fExceptionCaught;
fExceptionCaught = false;
try
{
tree = p.Parse("@(foo) == 'a.cs;b.cs'", ParserOptions.AllowProperties, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'a.cs;b.cs' == @(foo)", ParserOptions.AllowProperties, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'@(foo)' == 'a.cs;b.cs'", ParserOptions.AllowProperties, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'otherstuff@(foo)' == 'a.cs;b.cs'", ParserOptions.AllowProperties, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'@(foo)otherstuff' == 'a.cs;b.cs'", ParserOptions.AllowProperties, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("somefunction(@(foo), 'otherstuff')", ParserOptions.AllowProperties, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
}
[Fact]
public void ItemFuncParseTest()
{
Console.WriteLine("ItemFuncParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
tree = p.Parse("@(item->foo('ab'))",
ParserOptions.AllowProperties | ParserOptions.AllowItemLists, _elementLocation);
Assert.IsType<StringExpressionNode>(tree);
Assert.Equal("@(item->foo('ab'))", tree.GetUnexpandedValue(null));
tree = p.Parse("!@(item->foo())",
ParserOptions.AllowProperties | ParserOptions.AllowItemLists, _elementLocation);
Assert.IsType<NotExpressionNode>(tree);
tree = p.Parse("(@(item->foo('ab')) and @(item->foo('bc')))",
ParserOptions.AllowProperties | ParserOptions.AllowItemLists, _elementLocation);
Assert.IsType<AndExpressionNode>(tree);
}
[Fact]
public void MetadataParseTest()
{
Console.WriteLine("FunctionCallParseTest()");
Parser p = new Parser();
GenericExpressionNode tree;
bool fExceptionCaught;
fExceptionCaught = false;
try
{
tree = p.Parse("%(foo) == 'a.cs;b.cs'", ParserOptions.AllowProperties | ParserOptions.AllowItemLists, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'a.cs;b.cs' == %(foo)", ParserOptions.AllowProperties | ParserOptions.AllowItemLists, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'%(foo)' == 'a.cs;b.cs'", ParserOptions.AllowProperties | ParserOptions.AllowItemLists, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'otherstuff%(foo)' == 'a.cs;b.cs'", ParserOptions.AllowProperties | ParserOptions.AllowItemLists, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("'%(foo)otherstuff' == 'a.cs;b.cs'", ParserOptions.AllowProperties | ParserOptions.AllowItemLists, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
fExceptionCaught = false;
try
{
tree = p.Parse("somefunction(%(foo), 'otherstuff')", ParserOptions.AllowProperties | ParserOptions.AllowItemLists, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
}
/// <summary>
/// </summary>
[Fact]
public void NegativeTests()
{
Console.WriteLine("NegativeTests()");
Parser p = new Parser();
GenericExpressionNode tree;
bool fExceptionCaught;
try
{
fExceptionCaught = false;
// Note no close quote ----------------------------------------------------V
tree = p.Parse("'a more complex' == 'asdf", ParserOptions.AllowAll, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
try
{
fExceptionCaught = false;
// Note no close quote ----------------------------------------------------V
tree = p.Parse("(($(foo) <= 5 and $(bar) >= 15) and $(baz) == 'simple string) and 'a more complex string' != $(quux)", ParserOptions.AllowAll, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("($(foo) == 'simple string') $(bar)", ParserOptions.AllowAll, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("=='x'", ParserOptions.AllowAll, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("==", ParserOptions.AllowAll, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse(">", ParserOptions.AllowAll, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("true!=false==", ParserOptions.AllowAll, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("true!=false==true", ParserOptions.AllowAll, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
try
{
fExceptionCaught = false;
// Correct tokens, but bad parse -----------V
tree = p.Parse("1==(2", ParserOptions.AllowAll, _elementLocation);
}
catch (InvalidProjectFileException e)
{
Console.WriteLine(e.BaseMessage);
fExceptionCaught = true;
}
Assert.True(fExceptionCaught);
}
/// <summary>
/// This test verifies that we trigger warnings for expressions that
/// could be incorrectly evaluated
/// </summary>
[Fact]
public void VerifyWarningForOrder()
{
// Create a project file that has an expression
MockLogger ml = ObjectModelHelpers.BuildProjectExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`$(a) == 1 and $(b) == 2 or $(c) == 3`/>
</Target>
</Project>
");
// Make sure the log contains the correct strings.
Assert.Contains("MSB4130:", ml.FullLog); // "Need to warn for this expression - (a) == 1 and $(b) == 2 or $(c) == 3."
ml = ObjectModelHelpers.BuildProjectExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`$(a) == 1 or $(b) == 2 and $(c) == 3`/>
</Target>
</Project>
");
// Make sure the log contains the correct strings.
Assert.Contains("MSB4130:", ml.FullLog); // "Need to warn for this expression - (a) == 1 or $(b) == 2 and $(c) == 3."
ml = ObjectModelHelpers.BuildProjectExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`($(a) == 1 or $(b) == 2 and $(c) == 3) or $(d) == 4`/>
</Target>
</Project>
");
// Make sure the log contains the correct strings.
Assert.Contains("MSB4130:", ml.FullLog); // "Need to warn for this expression - ($(a) == 1 or $(b) == 2 and $(c) == 3) or $(d) == 4."
}
/// <summary>
/// This test verifies that we don't trigger warnings for expressions that
/// couldn't be incorrectly evaluated
/// </summary>
[Fact]
public void VerifyNoWarningForOrder()
{
// Create a project file that has an expression
MockLogger ml = ObjectModelHelpers.BuildProjectExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`$(a) == 1 and $(b) == 2 and $(c) == 3`/>
</Target>
</Project>
");
// Make sure the log contains the correct strings.
Assert.DoesNotContain("MSB4130:", ml.FullLog); // "No need to warn for this expression - (a) == 1 and $(b) == 2 and $(c) == 3."
ml = ObjectModelHelpers.BuildProjectExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`$(a) == 1 or $(b) == 2 or $(c) == 3`/>
</Target>
</Project>
");
// Make sure the log contains the correct strings.
Assert.DoesNotContain("MSB4130:", ml.FullLog); // "No need to warn for this expression - (a) == 1 or $(b) == 2 or $(c) == 3."
ml = ObjectModelHelpers.BuildProjectExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`($(a) == 1 and $(b) == 2) or $(c) == 3`/>
</Target>
</Project>
");
// Make sure the log contains the correct strings.
Assert.DoesNotContain("MSB4130:", ml.FullLog); // "No need to warn for this expression - ($(a) == 1 and $(b) == 2) or $(c) == 3."
ml = ObjectModelHelpers.BuildProjectExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`Build`>
<Message Text=`expression 1 is true ` Condition=`($(a) == 1 or $(b) == 2) and $(c) == 3`/>
</Target>
</Project>
");
// Make sure the log contains the correct strings.
Assert.DoesNotContain("MSB4130:", ml.FullLog); // "No need to warn for this expression - ($(a) == 1 or $(b) == 2) and $(c) == 3."
}
}
}
| |
#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
namespace System.Collections.Generic
{
/// <summary>
/// DictionaryExtensions
/// </summary>
public static class DictionaryExtensions
{
//public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, int index, TValue defaultValue)
//{
// return defaultValue;
//}
/// <summary>
/// Appends the specified value array to the underlying instance of <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="values">String array of default values to use in initializing the collection.</param>
/// <returns></returns>
public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, string[] values)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if ((values == null) || (values.Length == 0))
return dictionary;
foreach (string value in values)
{
if (value == null)
throw new NullReferenceException(Local.InvalidArrayNullItem);
if (value.Length > 0)
{
int valueEqualIndex = value.IndexOf('=');
if (valueEqualIndex >= 0)
dictionary[value.Substring(0, valueEqualIndex)] = value.Substring(valueEqualIndex + 1);
else
dictionary[value] = value;
}
}
return dictionary;
}
/// <summary>
/// Appends the specified value array to the underlying instance of <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="values">String array of default values to use in initializing the collection.</param>
/// <param name="startIndex">The initial index value to use as a starting point when processing the specified <c>values</c></param>
/// <returns></returns>
public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, string[] values, int startIndex)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex");
if ((values == null) || (startIndex >= values.Length))
return dictionary;
for (int valueIndex = startIndex; valueIndex < values.Length; valueIndex++)
{
string value = values[valueIndex];
if (value == null)
throw new NullReferenceException(Local.InvalidArrayNullItem);
if (value.Length > 0)
{
int valueEqualIndex = value.IndexOf('=');
if (valueEqualIndex >= 0)
dictionary[value.Substring(0, valueEqualIndex)] = value.Substring(valueEqualIndex + 1);
else
dictionary[value] = value;
}
}
return dictionary;
}
/// <summary>
/// Appends the specified value array to the underlying instance of <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="values">String array of default values to use in initializing the collection.</param>
/// <param name="startIndex">The initial index value to use as a starting point when processing the specified <c>values</c></param>
/// <param name="count">The number of value from <c>values</c> to process, starting at the position indicated by <c>startIndex</c>.</param>
/// <returns></returns>
public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, string[] values, int startIndex, int count)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if ((values == null) || (startIndex >= count))
return dictionary;
if (count > values.Length)
count = values.Length;
for (int valueIndex = startIndex; valueIndex < count; valueIndex++)
{
string value = values[valueIndex];
if (value == null)
throw new InvalidOperationException(Local.InvalidArrayNullItem);
if (value.Length > 0)
{
int valueEqualIndex = value.IndexOf('=');
if (valueEqualIndex >= 0)
dictionary[value.Substring(0, valueEqualIndex)] = value.Substring(valueEqualIndex + 1);
else
dictionary[value] = value;
}
}
return dictionary;
}
/// <summary>
/// Appends the specified value array to the underlying instance of <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="values">String array of default values to use in initializing the collection.</param>
/// <param name="namespace">A namespace prefix to search when setting initial values.</param>
/// <returns></returns>
/// <remarks>When processing <c>values</c>, the underlying instance of <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/>
/// is search for values. The <c>namespaceKey</c> + ":" is used as a prefix to the keys found in the internal dictionary to determine a match for initializing to the value provided by <c>values.</c>
/// </remarks>
public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, string[] values, string @namespace)
{
if (string.IsNullOrEmpty(@namespace))
{
Insert(dictionary, values);
return dictionary;
}
if (values == null)
return dictionary;
@namespace += ":";
int namespaceKeyLength = @namespace.Length;
int valueDataIndex;
foreach (string value in values)
{
if (value == null)
throw new InvalidOperationException(Local.InvalidArrayNullItem);
if ((value.Length > -1) && ((valueDataIndex = value.IndexOf(@namespace, StringComparison.OrdinalIgnoreCase)) > -1))
{
valueDataIndex += namespaceKeyLength;
int valueEqualIndex = value.IndexOf('=', valueDataIndex);
if (valueEqualIndex >= 0)
dictionary[value.Substring(valueDataIndex, valueEqualIndex - valueDataIndex)] = value.Substring(valueDataIndex + valueEqualIndex + 1);
else
{
string value2 = value.Substring(valueDataIndex);
dictionary[value2] = value2;
}
}
}
return dictionary;
}
/// <summary>
/// Appends the specified value array to the underlying instance of<see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="values">String array of default values to use in initializing the collection.</param>
/// <param name="namespace">A namespace prefix to search when setting initial values.</param>
/// <param name="startIndex">The initial index value to use as a starting point when processing the specified <c>values</c></param>
/// <param name="count">The number of value from <c>values</c> to process, starting at the position indicated by <c>startIndex</c>.</param>
/// <returns></returns>
/// <remarks>When processing <c>values</c>, the underlying instance of <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/>
/// is search for values. The <c>namespaceKey</c> + ":" is used as a prefix to the keys found in the internal dictionary to determine a match for initializing to the value provided by <c>values.</c>
/// </remarks>
public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, string[] values, string @namespace, int startIndex, int count)
{
if (string.IsNullOrEmpty(@namespace))
{
Insert(dictionary, values, startIndex, count);
return dictionary;
}
if ((values == null) || (startIndex >= count))
return dictionary;
if (count > values.Length)
count = values.Length;
@namespace += ":";
int namespaceKeyLength = @namespace.Length;
int valueDataIndex;
for (int valueIndex = startIndex; valueIndex < count; valueIndex++)
{
string value = values[valueIndex];
if (value == null)
throw new InvalidOperationException(Local.InvalidArrayNullItem);
if ((value.Length > -1) && ((valueDataIndex = value.IndexOf(@namespace, StringComparison.OrdinalIgnoreCase)) > -1))
{
valueDataIndex += namespaceKeyLength;
int valueEqualIndex = value.IndexOf('=', valueDataIndex);
if (valueEqualIndex >= 0)
dictionary[value.Substring(valueDataIndex, valueEqualIndex - valueDataIndex)] = value.Substring(valueDataIndex + valueEqualIndex + 1);
else
{
value = value.Substring(valueDataIndex);
dictionary[value] = value;
}
}
}
return dictionary;
}
/// <summary>
/// Appends the specified hash to the underlying instance of <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="sourceDictionary">The source dictionary.</param>
/// <returns></returns>
public static Dictionary<string, string> Insert(this Dictionary<string, string> dictionary, IDictionary<string, string> sourceDictionary)
{
if (sourceDictionary == null)
return dictionary;
foreach (string key in sourceDictionary.Keys)
dictionary[key] = sourceDictionary[key];
return dictionary;
}
/// <summary>
/// Gets the bit.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
public static bool GetBool(this Dictionary<string, string> dictionary, string key)
{
string value;
return ((dictionary.TryGetValue(key, out value)) && (string.Compare(value, key, StringComparison.OrdinalIgnoreCase) == 0));
}
/// <summary>
/// Sets the bit.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void SetBool(this Dictionary<string, string> dictionary, string key, bool value)
{
if (value)
dictionary[key] = key;
else if (dictionary.ContainsKey(key))
dictionary.Remove(key);
}
/// <summary>
/// Slices or removes all keys prefixed with the provided <c>namespaceKey</c> value from the underlying
/// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> instance that contains
/// the values stored within the collection object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="namespace">The namespace to target.</param>
/// <returns></returns>
public static T Slice<T>(this Dictionary<string, string> dictionary, string @namespace)
where T : Dictionary<string, string>, new() { return Slice<T>(dictionary, @namespace, false); }
/// <summary>
/// Slices or removes all keys prefixed with the provided <c>namespaceKey</c> value from the underlying
/// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> instance that contains
/// the values stored within the collection object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="namespace">The namespace to target.</param>
/// <param name="returnNullIfNoMatch">if set to <c>true</c> [return null if no match].</param>
/// <returns></returns>
public static T Slice<T>(this Dictionary<string, string> dictionary, string @namespace, bool returnNullIfNoMatch)
where T : Dictionary<string, string>, new()
{
T slicedDictionary = null;
if (@namespace.Length > 0)
{
@namespace += ":";
int namespaceLength = @namespace.Length;
//+ return namespace set
foreach (string key in new List<string>(dictionary.Keys))
if (key.StartsWith(@namespace))
{
if (slicedDictionary == null)
slicedDictionary = new T();
// add & remove
string value = dictionary[key];
if (key != value)
slicedDictionary[key.Substring(namespaceLength)] = value;
else
{
// isbit
value = key.Substring(namespaceLength);
slicedDictionary[value] = value;
}
dictionary.Remove(key);
}
}
// return root-namespace set
else
foreach (string key in new List<string>(dictionary.Keys))
if (key.IndexOf(":") == -1)
{
slicedDictionary[key] = dictionary[key];
dictionary.Remove(key);
}
return ((slicedDictionary != null) || (returnNullIfNoMatch) ? slicedDictionary : new T());
}
/// <summary>
/// Slices or removes all keys prefixed with the provided <c>namespaceKey</c> value from the underlying
/// <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/> instance that contains
/// the values stored within the collection object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="namespace">The namespace to target.</param>
/// <param name="isReturnNullIfNoMatch">TODO.</param>
/// <param name="valueReplacerIfStartsWith">The value replacer if starts with.</param>
/// <param name="valueReplacer">The value replacer.</param>
/// <returns></returns>
public static T Slice<T>(this Dictionary<string, string> dictionary, string @namespace, bool isReturnNullIfNoMatch, string valueReplacerIfStartsWith, Func<string, string> valueReplacer)
where T : Dictionary<string, string>, new()
{
T slicedDictionary = null;
if (@namespace.Length > 0)
{
@namespace += ":";
int namespaceLength = @namespace.Length;
string compositeNamespace = valueReplacerIfStartsWith + @namespace;
int compositeNamespaceLength = compositeNamespace.Length;
// return namespace set
foreach (string key in new List<string>(dictionary.Keys))
if (key.StartsWith(compositeNamespace))
{
if (slicedDictionary == null)
slicedDictionary = new T();
// add & remove
string value = valueReplacer(dictionary[key]);
if (key != value)
slicedDictionary[key.Substring(compositeNamespaceLength)] = value;
else
{
// isbit
value = key.Substring(compositeNamespaceLength);
slicedDictionary[value] = value;
}
dictionary.Remove(key);
}
else if (key.StartsWith(@namespace))
{
if (slicedDictionary == null)
slicedDictionary = new T();
// add and remove
string value = dictionary[key];
if (key != value)
slicedDictionary[key.Substring(namespaceLength)] = value;
else
{
// isbit
value = key.Substring(namespaceLength);
slicedDictionary[value] = value;
}
dictionary.Remove(key);
}
}
// return root-namespace set
else
foreach (string key in new List<string>(dictionary.Keys))
if (key.IndexOf(":") == -1)
{
slicedDictionary[key] = (!key.StartsWith(valueReplacerIfStartsWith) ? dictionary[key] : valueReplacer(dictionary[key]));
dictionary.Remove(key);
}
return ((slicedDictionary != null) || (isReturnNullIfNoMatch) ? slicedDictionary : new T());
}
/// <summary>
/// Looks for the item in the underlying hash and if exists, removes it and returns it.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
public static bool SliceBool(this Dictionary<string, string> dictionary, string key)
{
string value;
if (dictionary.TryGetValue(key, out value))
{
bool wasSliced = (string.Compare(value, key, StringComparison.OrdinalIgnoreCase) == 0);
dictionary.Remove(key);
return wasSliced;
}
return false;
}
/// <summary>
/// Looks for the item in the underlying hash and if exists, removes it and returns it, or returns default value if not found.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public static bool SliceBool(this Dictionary<string, string> dictionary, string key, bool defaultValue)
{
string value;
if (dictionary.TryGetValue(key, out value))
{
bool wasSliced = (string.Compare(value, key, StringComparison.OrdinalIgnoreCase) == 0);
dictionary.Remove(key);
return wasSliced;
}
return defaultValue;
}
/// <summary>
/// Converts the underlying collection of string representations.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <returns>
/// Returns a string array of values following the format "<c>key</c>=<c>value</c>"
/// </returns>
public static string[] ToStringArray(this Dictionary<string, string> dictionary)
{
var keys = dictionary.Keys;
int keyIndex = 0;
string[] array = new string[keys.Count];
foreach (var entry in dictionary)
array[keyIndex++] = entry.Key + "=" + entry.Value;
return array;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace LitJson
{
public class JsonReader
{
private static IDictionary<int, IDictionary<int, int[]>> parse_table;
private Stack<int> automaton_stack;
private int current_input;
private int current_symbol;
private bool end_of_json;
private bool end_of_input;
private Lexer lexer;
private bool parser_in_string;
private bool parser_return;
private bool read_started;
private TextReader reader;
private bool reader_is_owned;
private bool skip_non_members;
private object token_value;
private JsonToken token;
public bool AllowComments
{
get
{
return this.lexer.AllowComments;
}
set
{
this.lexer.AllowComments = value;
}
}
public bool AllowSingleQuotedStrings
{
get
{
return this.lexer.AllowSingleQuotedStrings;
}
set
{
this.lexer.AllowSingleQuotedStrings = value;
}
}
public bool SkipNonMembers
{
get
{
return this.skip_non_members;
}
set
{
this.skip_non_members = value;
}
}
public bool EndOfInput
{
get
{
return this.end_of_input;
}
}
public bool EndOfJson
{
get
{
return this.end_of_json;
}
}
public JsonToken Token
{
get
{
return this.token;
}
}
public object Value
{
get
{
return this.token_value;
}
}
public JsonReader(string json_text) : this(new StringReader(json_text), true)
{
}
public JsonReader(TextReader reader) : this(reader, false)
{
}
private JsonReader(TextReader reader, bool owned)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
this.parser_in_string = false;
this.parser_return = false;
this.read_started = false;
this.automaton_stack = new Stack<int>();
this.automaton_stack.Push(65553);
this.automaton_stack.Push(65543);
this.lexer = new Lexer(reader);
this.end_of_input = false;
this.end_of_json = false;
this.skip_non_members = true;
this.reader = reader;
this.reader_is_owned = owned;
}
static JsonReader()
{
JsonReader.PopulateParseTable();
}
private static void PopulateParseTable()
{
JsonReader.parse_table = new Dictionary<int, IDictionary<int, int[]>>();
JsonReader.TableAddRow(ParserToken.Array);
JsonReader.TableAddCol(ParserToken.Array, 91, new int[]
{
91,
65549
});
JsonReader.TableAddRow(ParserToken.ArrayPrime);
JsonReader.TableAddCol(ParserToken.ArrayPrime, 34, new int[]
{
65550,
65551,
93
});
JsonReader.TableAddCol(ParserToken.ArrayPrime, 91, new int[]
{
65550,
65551,
93
});
JsonReader.TableAddCol(ParserToken.ArrayPrime, 93, new int[]
{
93
});
JsonReader.TableAddCol(ParserToken.ArrayPrime, 123, new int[]
{
65550,
65551,
93
});
JsonReader.TableAddCol(ParserToken.ArrayPrime, 65537, new int[]
{
65550,
65551,
93
});
JsonReader.TableAddCol(ParserToken.ArrayPrime, 65538, new int[]
{
65550,
65551,
93
});
JsonReader.TableAddCol(ParserToken.ArrayPrime, 65539, new int[]
{
65550,
65551,
93
});
JsonReader.TableAddCol(ParserToken.ArrayPrime, 65540, new int[]
{
65550,
65551,
93
});
JsonReader.TableAddRow(ParserToken.Object);
JsonReader.TableAddCol(ParserToken.Object, 123, new int[]
{
123,
65545
});
JsonReader.TableAddRow(ParserToken.ObjectPrime);
JsonReader.TableAddCol(ParserToken.ObjectPrime, 34, new int[]
{
65546,
65547,
125
});
JsonReader.TableAddCol(ParserToken.ObjectPrime, 125, new int[]
{
125
});
JsonReader.TableAddRow(ParserToken.Pair);
JsonReader.TableAddCol(ParserToken.Pair, 34, new int[]
{
65552,
58,
65550
});
JsonReader.TableAddRow(ParserToken.PairRest);
JsonReader.TableAddCol(ParserToken.PairRest, 44, new int[]
{
44,
65546,
65547
});
JsonReader.TableAddCol(ParserToken.PairRest, 125, new int[]
{
65554
});
JsonReader.TableAddRow(ParserToken.String);
JsonReader.TableAddCol(ParserToken.String, 34, new int[]
{
34,
65541,
34
});
JsonReader.TableAddRow(ParserToken.Text);
JsonReader.TableAddCol(ParserToken.Text, 91, new int[]
{
65548
});
JsonReader.TableAddCol(ParserToken.Text, 123, new int[]
{
65544
});
JsonReader.TableAddRow(ParserToken.Value);
JsonReader.TableAddCol(ParserToken.Value, 34, new int[]
{
65552
});
JsonReader.TableAddCol(ParserToken.Value, 91, new int[]
{
65548
});
JsonReader.TableAddCol(ParserToken.Value, 123, new int[]
{
65544
});
JsonReader.TableAddCol(ParserToken.Value, 65537, new int[]
{
65537
});
JsonReader.TableAddCol(ParserToken.Value, 65538, new int[]
{
65538
});
JsonReader.TableAddCol(ParserToken.Value, 65539, new int[]
{
65539
});
JsonReader.TableAddCol(ParserToken.Value, 65540, new int[]
{
65540
});
JsonReader.TableAddRow(ParserToken.ValueRest);
JsonReader.TableAddCol(ParserToken.ValueRest, 44, new int[]
{
44,
65550,
65551
});
JsonReader.TableAddCol(ParserToken.ValueRest, 93, new int[]
{
65554
});
}
private static void TableAddCol(ParserToken row, int col, params int[] symbols)
{
JsonReader.parse_table[(int)row].Add(col, symbols);
}
private static void TableAddRow(ParserToken rule)
{
JsonReader.parse_table.Add((int)rule, new Dictionary<int, int[]>());
}
private void ProcessNumber(string number)
{
double num;
if ((number.IndexOf('.') != -1 || number.IndexOf('e') != -1 || number.IndexOf('E') != -1) && double.TryParse(number, out num))
{
this.token = JsonToken.Double;
this.token_value = num;
return;
}
int num2;
if (int.TryParse(number, out num2))
{
this.token = JsonToken.Int;
this.token_value = num2;
return;
}
long num3;
if (long.TryParse(number, out num3))
{
this.token = JsonToken.Long;
this.token_value = num3;
return;
}
this.token = JsonToken.Int;
this.token_value = 0;
}
private void ProcessSymbol()
{
if (this.current_symbol == 91)
{
this.token = JsonToken.ArrayStart;
this.parser_return = true;
}
else if (this.current_symbol == 93)
{
this.token = JsonToken.ArrayEnd;
this.parser_return = true;
}
else if (this.current_symbol == 123)
{
this.token = JsonToken.ObjectStart;
this.parser_return = true;
}
else if (this.current_symbol == 125)
{
this.token = JsonToken.ObjectEnd;
this.parser_return = true;
}
else if (this.current_symbol == 34)
{
if (this.parser_in_string)
{
this.parser_in_string = false;
this.parser_return = true;
}
else
{
if (this.token == JsonToken.None)
{
this.token = JsonToken.String;
}
this.parser_in_string = true;
}
}
else if (this.current_symbol == 65541)
{
this.token_value = this.lexer.StringValue;
}
else if (this.current_symbol == 65539)
{
this.token = JsonToken.Boolean;
this.token_value = false;
this.parser_return = true;
}
else if (this.current_symbol == 65540)
{
this.token = JsonToken.Null;
this.parser_return = true;
}
else if (this.current_symbol == 65537)
{
this.ProcessNumber(this.lexer.StringValue);
this.parser_return = true;
}
else if (this.current_symbol == 65546)
{
this.token = JsonToken.PropertyName;
}
else if (this.current_symbol == 65538)
{
this.token = JsonToken.Boolean;
this.token_value = true;
this.parser_return = true;
}
}
private bool ReadToken()
{
if (this.end_of_input)
{
return false;
}
this.lexer.NextToken();
if (this.lexer.EndOfInput)
{
this.Close();
return false;
}
this.current_input = this.lexer.Token;
return true;
}
public void Close()
{
if (this.end_of_input)
{
return;
}
this.end_of_input = true;
this.end_of_json = true;
if (this.reader_is_owned)
{
this.reader.Close();
}
this.reader = null;
}
public bool Read()
{
if (this.end_of_input)
{
return false;
}
if (this.end_of_json)
{
this.end_of_json = false;
this.automaton_stack.Clear();
this.automaton_stack.Push(65553);
this.automaton_stack.Push(65543);
}
this.parser_in_string = false;
this.parser_return = false;
this.token = JsonToken.None;
this.token_value = null;
if (!this.read_started)
{
this.read_started = true;
if (!this.ReadToken())
{
return false;
}
}
while (!this.parser_return)
{
this.current_symbol = this.automaton_stack.Pop();
this.ProcessSymbol();
if (this.current_symbol == this.current_input)
{
if (!this.ReadToken())
{
if (this.automaton_stack.Peek() != 65553)
{
throw new JsonException("Input doesn't evaluate to proper JSON text");
}
return this.parser_return;
}
}
else
{
int[] array;
try
{
array = JsonReader.parse_table[this.current_symbol][this.current_input];
}
catch (KeyNotFoundException inner_exception)
{
throw new JsonException((ParserToken)this.current_input, inner_exception);
}
if (array[0] != 65554)
{
for (int i = array.Length - 1; i >= 0; i--)
{
this.automaton_stack.Push(array[i]);
}
}
}
}
if (this.automaton_stack.Peek() == 65553)
{
this.end_of_json = true;
}
return true;
}
}
}
| |
// DeflaterOutputStream.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
using GameAnalyticsSDK.Net.Utilities.Zip.Checksums;
namespace GameAnalyticsSDK.Net.Utilities.Zip.Compression.Streams
{
/// <summary>
/// A special stream deflating or compressing the bytes that are
/// written to it. It uses a Deflater to perform actual deflating.<br/>
/// Authors of the original java version : Tom Tromey, Jochen Hoenicke
/// </summary>
public class DeflaterOutputStream : Stream
{
/// <summary>
/// This buffer is used temporarily to retrieve the bytes from the
/// deflater and write them to the underlying output stream.
/// </summary>
protected byte[] buf;
/// <summary>
/// The deflater which is used to deflate the stream.
/// </summary>
protected Deflater def;
/// <summary>
/// Base stream the deflater depends on.
/// </summary>
protected Stream baseOutputStream;
bool isClosed = false;
bool isStreamOwner = true;
/// <summary>
/// Get/set flag indicating ownership of underlying stream.
/// When the flag is true <see cref="Close"></see> will close the underlying stream also.
/// </summary>
public bool IsStreamOwner
{
get { return isStreamOwner; }
set { isStreamOwner = value; }
}
/// <summary>
/// Allows client to determine if an entry can be patched after its added
/// </summary>
public bool CanPatchEntries {
get {
return baseOutputStream.CanSeek;
}
}
/// <summary>
/// Gets value indicating stream can be read from
/// </summary>
public override bool CanRead {
get {
return baseOutputStream.CanRead;
}
}
/// <summary>
/// Gets a value indicating if seeking is supported for this stream
/// This property always returns false
/// </summary>
public override bool CanSeek {
get {
return false;
}
}
/// <summary>
/// Get value indicating if this stream supports writing
/// </summary>
public override bool CanWrite {
get {
return baseOutputStream.CanWrite;
}
}
/// <summary>
/// Get current length of stream
/// </summary>
public override long Length {
get {
return baseOutputStream.Length;
}
}
/// <summary>
/// The current position within the stream.
/// Always throws a NotSupportedExceptionNotSupportedException
/// </summary>
/// <exception cref="NotSupportedException">Any attempt to set position</exception>
public override long Position {
get {
return baseOutputStream.Position;
}
set {
throw new NotSupportedException("DefalterOutputStream Position not supported");
}
}
/// <summary>
/// Sets the current position of this stream to the given value. Not supported by this class!
/// </summary>
/// <exception cref="NotSupportedException">Any access</exception>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("DeflaterOutputStream Seek not supported");
}
/// <summary>
/// Sets the length of this stream to the given value. Not supported by this class!
/// </summary>
/// <exception cref="NotSupportedException">Any access</exception>
public override void SetLength(long val)
{
throw new NotSupportedException("DeflaterOutputStream SetLength not supported");
}
/// <summary>
/// Read a byte from stream advancing position by one
/// </summary>
/// <exception cref="NotSupportedException">Any access</exception>
public override int ReadByte()
{
throw new NotSupportedException("DeflaterOutputStream ReadByte not supported");
}
/// <summary>
/// Read a block of bytes from stream
/// </summary>
/// <exception cref="NotSupportedException">Any access</exception>
public override int Read(byte[] b, int off, int len)
{
throw new NotSupportedException("DeflaterOutputStream Read not supported");
}
/// <summary>
/// Asynchronous reads are not supported a NotSupportedException is always thrown
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException("DeflaterOutputStream BeginRead not currently supported");
}
/// <summary>
/// Asynchronous writes arent supported, a NotSupportedException is always thrown
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException("DeflaterOutputStream BeginWrite not currently supported");
}
/// <summary>
/// Deflates everything in the input buffers. This will call
/// <code>def.deflate()</code> until all bytes from the input buffers
/// are processed.
/// </summary>
protected void Deflate()
{
while (!def.IsNeedingInput) {
int len = def.Deflate(buf, 0, buf.Length);
if (len <= 0) {
break;
}
if (this.keys != null) {
this.EncryptBlock(buf, 0, len);
}
baseOutputStream.Write(buf, 0, len);
}
if (!def.IsNeedingInput) {
throw new SharpZipBaseException("DeflaterOutputStream can't deflate all input?");
}
}
/// <summary>
/// Creates a new DeflaterOutputStream with a default Deflater and default buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// the output stream where deflated output should be written.
/// </param>
public DeflaterOutputStream(Stream baseOutputStream) : this(baseOutputStream, new Deflater(), 512)
{
}
/// <summary>
/// Creates a new DeflaterOutputStream with the given Deflater and
/// default buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// the output stream where deflated output should be written.
/// </param>
/// <param name="defl">
/// the underlying deflater.
/// </param>
public DeflaterOutputStream(Stream baseOutputStream, Deflater defl) : this(baseOutputStream, defl, 512)
{
}
/// <summary>
/// Creates a new DeflaterOutputStream with the given Deflater and
/// buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// The output stream where deflated output is written.
/// </param>
/// <param name="deflater">
/// The underlying deflater to use
/// </param>
/// <param name="bufsize">
/// The buffer size to use when deflating
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// bufsize is less than or equal to zero.
/// </exception>
/// <exception cref="ArgumentException">
/// baseOutputStream does not support writing
/// </exception>
/// <exception cref="ArgumentNullException">
/// deflater instance is null
/// </exception>
public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater, int bufsize)
{
if (baseOutputStream.CanWrite == false) {
throw new ArgumentException("baseOutputStream", "must support writing");
}
if (deflater == null) {
throw new ArgumentNullException("deflater");
}
if (bufsize <= 0) {
throw new ArgumentOutOfRangeException("bufsize");
}
this.baseOutputStream = baseOutputStream;
buf = new byte[bufsize];
def = deflater;
}
/// <summary>
/// Flushes the stream by calling flush() on the deflater and then
/// on the underlying stream. This ensures that all bytes are
/// flushed.
/// </summary>
public override void Flush()
{
def.Flush();
Deflate();
baseOutputStream.Flush();
}
/// <summary>
/// Finishes the stream by calling finish() on the deflater.
/// </summary>
/// <exception cref="SharpZipBaseException">
/// Not all input is deflated
/// </exception>
public virtual void Finish()
{
def.Finish();
while (!def.IsFinished) {
int len = def.Deflate(buf, 0, buf.Length);
if (len <= 0) {
break;
}
if (this.keys != null) {
this.EncryptBlock(buf, 0, len);
}
baseOutputStream.Write(buf, 0, len);
}
if (!def.IsFinished) {
throw new SharpZipBaseException("Can't deflate all input?");
}
baseOutputStream.Flush();
keys = null;
}
/// <summary>
/// Calls finish() and closes the underlying
/// stream when <see cref="IsStreamOwner"></see> is true.
/// </summary>
public override void Close()
{
if ( !isClosed ) {
isClosed = true;
Finish();
if ( isStreamOwner ) {
baseOutputStream.Close();
}
}
}
/// <summary>
/// Writes a single byte to the compressed output stream.
/// </summary>
/// <param name="bval">
/// The byte value.
/// </param>
public override void WriteByte(byte bval)
{
byte[] b = new byte[1];
b[0] = bval;
Write(b, 0, 1);
}
/// <summary>
/// Writes bytes from an array to the compressed stream.
/// </summary>
/// <param name="buf">
/// The byte array
/// </param>
/// <param name="off">
/// The offset into the byte array where to start.
/// </param>
/// <param name="len">
/// The number of bytes to write.
/// </param>
public override void Write(byte[] buf, int off, int len)
{
def.SetInput(buf, off, len);
Deflate();
}
#region Encryption
// TODO: Refactor this code. The presence of Zip specific code in this low level class is wrong
string password = null;
uint[] keys = null;
/// <summary>
/// Get/set the password used for encryption. When null no encryption is performed
/// </summary>
public string Password {
get {
return password;
}
set {
if ( value != null && value.Length == 0 ) {
password = null;
} else {
password = value;
}
}
}
/// <summary>
/// Encrypt a single byte
/// </summary>
/// <returns>
/// The encrypted value
/// </returns>
protected byte EncryptByte()
{
uint temp = ((keys[2] & 0xFFFF) | 2);
return (byte)((temp * (temp ^ 1)) >> 8);
}
/// <summary>
/// Encrypt a block of data
/// </summary>
/// <param name="buffer">
/// Data to encrypt. NOTE the original contents of the buffer are lost
/// </param>
/// <param name="offset">
/// Offset of first byte in buffer to encrypt
/// </param>
/// <param name="length">
/// Number of bytes in buffer to encrypt
/// </param>
protected void EncryptBlock(byte[] buffer, int offset, int length)
{
// TODO: refactor to use crypto transform
for (int i = offset; i < offset + length; ++i) {
byte oldbyte = buffer[i];
buffer[i] ^= EncryptByte();
UpdateKeys(oldbyte);
}
}
/// <summary>
/// Initializes encryption keys based on given password
/// </summary>
protected void InitializePassword(string password) {
keys = new uint[] {
0x12345678,
0x23456789,
0x34567890
};
for (int i = 0; i < password.Length; ++i) {
UpdateKeys((byte)password[i]);
}
}
/// <summary>
/// Update encryption keys
/// </summary>
protected void UpdateKeys(byte ch)
{
keys[0] = Crc32.ComputeCrc32(keys[0], ch);
keys[1] = keys[1] + (byte)keys[0];
keys[1] = keys[1] * 134775813 + 1;
keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24));
}
#endregion
}
}
| |
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace dal.SqlServerLibrary
{
public class SqlImplHelper
{
private static string _connectionString = null;
private static MySqlTransaction _transaction = null;
private static MySqlConnection _connection = null;
/*getConnectionString vieja. Se mantiene para referencia.*/
public static string getConnectionString()
{
if (_connectionString == null)
{
Services.Utility oUtil = new Services.Utility();
_connectionString = oUtil.Decrypt(dal.SqlServerLibrary.Properties.Settings.Default.CadenaConexion);
}
return _connectionString;
}
/*
public static string getConnectionString()
{
return _connectionString;
}
*/
public static MySqlTransaction getTransaction()
{
try
{
if (_transaction == null || _transaction.Connection == null)
{
_connection = new MySqlConnection(getConnectionString());
_connection.Open();
_transaction = _connection.BeginTransaction(IsolationLevel.ReadCommitted);
}
return _transaction;
}
catch (Exception ex)
{
throw ex;
}
}
public static void commitTransaction()
{
try
{
if (_transaction != null)
{
_transaction.Commit();
_connection.Close();
_connection = null;
_transaction = null;
}
}
catch (Exception ex)
{
throw ex;
}
}
public static void rollbackTransaction()
{
try
{
if (_transaction != null)
{
_transaction.Rollback();
_connection.Close();
_connection = null;
_transaction = null;
}
}
catch (Exception ex)
{
throw ex;
}
}
public static bool setConnectionString(string cadenaConexion)
{
if (cadenaConexion == null || cadenaConexion == "")
return false;
Services.Utility oUtil = new Services.Utility();
_connectionString = oUtil.Decrypt(cadenaConexion);
if (_connectionString == null)
return false;
return true;
}
#region Datarows GettersRows
public static bool getBoolValue(object drValue, string valueToCompare)
{
if (Convert.IsDBNull(drValue))
{
return false;
}
else
{
return drValue.ToString().Trim().Equals(valueToCompare) ? true : false;
}
}
public static DateTime getDateTimeValue(object drValue)
{
return Convert.IsDBNull(drValue) ? new DateTime(1, 1, 1) : Convert.ToDateTime(drValue.ToString());
}
public static DateTime getMinValueIfNull(object drValue)
{
return Convert.IsDBNull(drValue) || drValue.ToString().Length == 0 ? new DateTime(1, 1, 1) : Convert.ToDateTime(drValue.ToString());
}
public static DateTime getMaxValueIfNull(object drValue)
{
return Convert.IsDBNull(drValue) || drValue.ToString().Length == 0 ? DateTime.MaxValue : Convert.ToDateTime(drValue.ToString());
}
public static int getIntValue(object drValue)
{
if (Convert.IsDBNull(drValue) || drValue.ToString().Trim().Length == 0)
{
return 0;
}
return Convert.ToInt32(drValue.ToString().Trim());
}
public static long getLongValue(object drValue)
{
if (Convert.IsDBNull(drValue) || drValue.ToString().Trim().Length == 0)
{
return 0;
}
return Convert.ToInt64(drValue.ToString().Trim());
}
public static double getDoubleValue(object drValue)
{
if (Convert.IsDBNull(drValue) || drValue.ToString().Trim().Length == 0)
{
return 0;
}
return Convert.ToDouble(drValue.ToString().Trim());
}
public static decimal getDecimalValue(object drValue)
{
if (Convert.IsDBNull(drValue) || drValue.ToString().Trim().Length == 0)
{
return 0;
}
return Convert.ToDecimal(drValue.ToString().Trim());
}
public static string getStringValue(object drValue)
{
return Convert.IsDBNull(drValue) ? "" : drValue.ToString().Trim();
}
#endregion
#region GettersNull
public static object getNullIfEmpty(string sValue)
{
if (sValue == null || sValue.Trim().Length == 0)
{
return null;
}
return sValue;
}
public static object getNullIfNegative(int iValue)
{
if (iValue <= 0)
{
return null;
}
return iValue;
}
public static object getNullIfNegative(long iValue)
{
if (iValue <= 0)
{
return null;
}
return iValue;
}
public static object getNullIfDateMinValue(DateTime dtValue)
{
if (dtValue == DateTime.MinValue)
{
return null;
}
return dtValue;
}
public static object getNullIfDateMaxValue(DateTime dtValue)
{
if (dtValue == DateTime.MaxValue)
{
return null;
}
return dtValue;
}
public static string getSifTrue(bool bValue)
{
return bValue == true ? "S" : "N";
}
public static object getNullIfCero(string value)
{
return value == "0" ? null : value;
}
public static object getNullIfMinus(string value)
{
return value == "-1" ? null : value;
}
#endregion
public static string getDefault(string sClave)
{
try
{
string spCommandText = "SELECT mpls_neg_pkg.Busca_valor_default('" + sClave + "') FROM dual";
MySqlParameter[] oParams = { };
return SqlServerLibrary.SqlHelper.ExecuteScalar(getConnectionString(), CommandType.Text, spCommandText, oParams).ToString();
}
catch (System.Exception ex)
{
throw new SqlImplException("Error in getDefault", ex);
}
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace Reporting.RdlDesign
{
/// <summary>
/// Summary description for ReportCtl.
/// </summary>
internal class TableCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
bool fDataSet, fPBBefore, fPBAfter, fNoRows;
bool fDetailElementName, fDetailCollectionName, fRenderDetails;
bool fCheckRows;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox cbDataSet;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox chkPBBefore;
private System.Windows.Forms.CheckBox chkPBAfter;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbNoRows;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.CheckBox chkRenderDetails;
private System.Windows.Forms.TextBox tbDetailElementName;
private System.Windows.Forms.TextBox tbDetailCollectionName;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.CheckBox chkDetails;
private System.Windows.Forms.CheckBox chkHeaderRows;
private System.Windows.Forms.CheckBox chkFooterRows;
private CheckBox chkFooterRepeat;
private CheckBox chkHeaderRepeat;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal TableCtl(DesignXmlDraw dxDraw, List<XmlNode> ris)
{
_ReportItems = ris;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
XmlNode riNode = _ReportItems[0];
tbNoRows.Text = _Draw.GetElementValue(riNode, "NoRows", "");
cbDataSet.Items.AddRange(_Draw.DataSetNames);
cbDataSet.Text = _Draw.GetDataSetNameValue(riNode);
if (_Draw.GetReportItemDataRegionContainer(riNode) != null)
cbDataSet.Enabled = false;
chkPBBefore.Checked = _Draw.GetElementValue(riNode, "PageBreakAtStart", "false").ToLower()=="true"? true:false;
chkPBAfter.Checked = _Draw.GetElementValue(riNode, "PageBreakAtEnd", "false").ToLower()=="true"? true:false;
this.chkRenderDetails.Checked = _Draw.GetElementValue(riNode, "DetailDataElementOutput", "output").ToLower() == "output";
this.tbDetailElementName.Text = _Draw.GetElementValue(riNode, "DetailDataElementName", "Details");
this.tbDetailCollectionName.Text = _Draw.GetElementValue(riNode, "DetailDataCollectionName", "Details_Collection");
this.chkDetails.Checked = _Draw.GetNamedChildNode(riNode, "Details") != null;
XmlNode fNode = _Draw.GetNamedChildNode(riNode, "Footer");
this.chkFooterRows.Checked = fNode != null;
if (fNode != null)
{
chkFooterRepeat.Checked = _Draw.GetElementValue(fNode, "RepeatOnNewPage", "false").ToLower() == "true" ? true : false;
}
else
chkFooterRepeat.Enabled = false;
XmlNode hNode = _Draw.GetNamedChildNode(riNode, "Header");
this.chkHeaderRows.Checked = hNode != null;
if (hNode != null)
{
chkHeaderRepeat.Checked = _Draw.GetElementValue(hNode, "RepeatOnNewPage", "false").ToLower() == "true" ? true : false;
}
else
chkHeaderRepeat.Enabled = false;
fNoRows = fDataSet = fPBBefore = fPBAfter =
fDetailElementName = fDetailCollectionName = fRenderDetails =
fCheckRows = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label2 = new System.Windows.Forms.Label();
this.cbDataSet = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.chkPBAfter = new System.Windows.Forms.CheckBox();
this.chkPBBefore = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.tbNoRows = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.tbDetailCollectionName = new System.Windows.Forms.TextBox();
this.tbDetailElementName = new System.Windows.Forms.TextBox();
this.chkRenderDetails = new System.Windows.Forms.CheckBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.chkFooterRows = new System.Windows.Forms.CheckBox();
this.chkHeaderRows = new System.Windows.Forms.CheckBox();
this.chkDetails = new System.Windows.Forms.CheckBox();
this.chkHeaderRepeat = new System.Windows.Forms.CheckBox();
this.chkFooterRepeat = new System.Windows.Forms.CheckBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// label2
//
this.label2.Location = new System.Drawing.Point(24, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 23);
this.label2.TabIndex = 5;
this.label2.Text = "DataSet Name";
//
// cbDataSet
//
this.cbDataSet.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDataSet.Location = new System.Drawing.Point(120, 16);
this.cbDataSet.Name = "cbDataSet";
this.cbDataSet.Size = new System.Drawing.Size(304, 21);
this.cbDataSet.TabIndex = 0;
this.cbDataSet.SelectedIndexChanged += new System.EventHandler(this.cbDataSet_SelectedIndexChanged);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.chkPBAfter);
this.groupBox1.Controls.Add(this.chkPBBefore);
this.groupBox1.Location = new System.Drawing.Point(24, 64);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(400, 48);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Page Breaks";
//
// chkPBAfter
//
this.chkPBAfter.Location = new System.Drawing.Point(192, 16);
this.chkPBAfter.Name = "chkPBAfter";
this.chkPBAfter.Size = new System.Drawing.Size(128, 24);
this.chkPBAfter.TabIndex = 1;
this.chkPBAfter.Text = "Insert after Table";
this.chkPBAfter.CheckedChanged += new System.EventHandler(this.chkPBAfter_CheckedChanged);
//
// chkPBBefore
//
this.chkPBBefore.Location = new System.Drawing.Point(16, 16);
this.chkPBBefore.Name = "chkPBBefore";
this.chkPBBefore.Size = new System.Drawing.Size(128, 24);
this.chkPBBefore.TabIndex = 0;
this.chkPBBefore.Text = "Insert before Table";
this.chkPBBefore.CheckedChanged += new System.EventHandler(this.chkPBBefore_CheckedChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(24, 40);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(96, 23);
this.label1.TabIndex = 6;
this.label1.Text = "No rows message";
//
// tbNoRows
//
this.tbNoRows.Location = new System.Drawing.Point(120, 40);
this.tbNoRows.Name = "tbNoRows";
this.tbNoRows.Size = new System.Drawing.Size(304, 20);
this.tbNoRows.TabIndex = 1;
this.tbNoRows.Text = "textBox1";
this.tbNoRows.TextChanged += new System.EventHandler(this.tbNoRows_TextChanged);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.tbDetailCollectionName);
this.groupBox2.Controls.Add(this.tbDetailElementName);
this.groupBox2.Controls.Add(this.chkRenderDetails);
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Location = new System.Drawing.Point(24, 190);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(400, 92);
this.groupBox2.TabIndex = 4;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "XML";
//
// tbDetailCollectionName
//
this.tbDetailCollectionName.Location = new System.Drawing.Point(160, 62);
this.tbDetailCollectionName.Name = "tbDetailCollectionName";
this.tbDetailCollectionName.Size = new System.Drawing.Size(224, 20);
this.tbDetailCollectionName.TabIndex = 3;
this.tbDetailCollectionName.Text = "textBox1";
this.tbDetailCollectionName.TextChanged += new System.EventHandler(this.tbDetailCollectionName_TextChanged);
//
// tbDetailElementName
//
this.tbDetailElementName.Location = new System.Drawing.Point(160, 36);
this.tbDetailElementName.Name = "tbDetailElementName";
this.tbDetailElementName.Size = new System.Drawing.Size(224, 20);
this.tbDetailElementName.TabIndex = 2;
this.tbDetailElementName.Text = "textBox1";
this.tbDetailElementName.TextChanged += new System.EventHandler(this.tbDetailElementName_TextChanged);
//
// chkRenderDetails
//
this.chkRenderDetails.Location = new System.Drawing.Point(16, 12);
this.chkRenderDetails.Name = "chkRenderDetails";
this.chkRenderDetails.Size = new System.Drawing.Size(160, 24);
this.chkRenderDetails.TabIndex = 0;
this.chkRenderDetails.Text = "Render Details in Output";
this.chkRenderDetails.CheckedChanged += new System.EventHandler(this.chkRenderDetails_CheckedChanged);
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 64);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(120, 16);
this.label4.TabIndex = 1;
this.label4.Text = "Detail Collection Name";
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 38);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(112, 16);
this.label3.TabIndex = 1;
this.label3.Text = "Detail Element Name";
//
// groupBox3
//
this.groupBox3.Controls.Add(this.chkFooterRepeat);
this.groupBox3.Controls.Add(this.chkHeaderRepeat);
this.groupBox3.Controls.Add(this.chkFooterRows);
this.groupBox3.Controls.Add(this.chkHeaderRows);
this.groupBox3.Controls.Add(this.chkDetails);
this.groupBox3.Location = new System.Drawing.Point(24, 120);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(400, 64);
this.groupBox3.TabIndex = 3;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Include Table Rows";
//
// chkFooterRows
//
this.chkFooterRows.Location = new System.Drawing.Point(272, 13);
this.chkFooterRows.Name = "chkFooterRows";
this.chkFooterRows.Size = new System.Drawing.Size(104, 24);
this.chkFooterRows.TabIndex = 2;
this.chkFooterRows.Text = "Footer Rows";
this.chkFooterRows.CheckedChanged += new System.EventHandler(this.chkRows_CheckedChanged);
//
// chkHeaderRows
//
this.chkHeaderRows.Location = new System.Drawing.Point(144, 13);
this.chkHeaderRows.Name = "chkHeaderRows";
this.chkHeaderRows.Size = new System.Drawing.Size(104, 24);
this.chkHeaderRows.TabIndex = 1;
this.chkHeaderRows.Text = "Header Rows";
this.chkHeaderRows.CheckedChanged += new System.EventHandler(this.chkRows_CheckedChanged);
//
// chkDetails
//
this.chkDetails.Location = new System.Drawing.Point(16, 13);
this.chkDetails.Name = "chkDetails";
this.chkDetails.Size = new System.Drawing.Size(104, 24);
this.chkDetails.TabIndex = 1;
this.chkDetails.Text = "Detail Rows";
this.chkDetails.CheckedChanged += new System.EventHandler(this.chkRows_CheckedChanged);
//
// chkHeaderRepeat
//
this.chkHeaderRepeat.Location = new System.Drawing.Point(144, 34);
this.chkHeaderRepeat.Name = "chkHeaderRepeat";
this.chkHeaderRepeat.Size = new System.Drawing.Size(122, 30);
this.chkHeaderRepeat.TabIndex = 3;
this.chkHeaderRepeat.Text = "Repeat header on new page";
this.chkHeaderRepeat.CheckedChanged += new System.EventHandler(this.chkRows_CheckedChanged);
//
// chkFooterRepeat
//
this.chkFooterRepeat.Location = new System.Drawing.Point(272, 34);
this.chkFooterRepeat.Name = "chkFooterRepeat";
this.chkFooterRepeat.Size = new System.Drawing.Size(122, 30);
this.chkFooterRepeat.TabIndex = 4;
this.chkFooterRepeat.Text = "Repeat footer on new page";
this.chkFooterRepeat.CheckedChanged += new System.EventHandler(this.chkRows_CheckedChanged);
//
// TableCtl
//
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.tbNoRows);
this.Controls.Add(this.label1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.cbDataSet);
this.Controls.Add(this.label2);
this.Name = "TableCtl";
this.Size = new System.Drawing.Size(472, 288);
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public bool IsValid()
{
if (this.chkDetails.Checked || this.chkFooterRows.Checked || this.chkHeaderRows.Checked)
return true;
MessageBox.Show("Table must have at least one Header, Details or Footer row defined.", "Table");
return false;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
// No more changes
fNoRows = fDataSet = fPBBefore = fPBAfter =
fDetailElementName = fDetailCollectionName = fRenderDetails =
fCheckRows = false;
}
public void ApplyChanges(XmlNode node)
{
if (fNoRows)
_Draw.SetElement(node, "NoRows", this.tbNoRows.Text);
if (fDataSet)
_Draw.SetElement(node, "DataSetName", this.cbDataSet.Text);
if (fPBBefore)
_Draw.SetElement(node, "PageBreakAtStart", this.chkPBBefore.Checked? "true":"false");
if (fPBAfter)
_Draw.SetElement(node, "PageBreakAtEnd", this.chkPBAfter.Checked? "true":"false");
if (fCheckRows)
{
if (this.chkDetails.Checked)
CreateTableRow(node, "Details", false);
else
_Draw.RemoveElement(node, "Details");
if (this.chkHeaderRows.Checked)
CreateTableRow(node, "Header", chkHeaderRepeat.Checked);
else
_Draw.RemoveElement(node, "Header");
if (this.chkFooterRows.Checked)
CreateTableRow(node, "Footer", chkFooterRepeat.Checked);
else
_Draw.RemoveElement(node, "Footer");
}
if (fRenderDetails)
_Draw.SetElement(node, "DetailDataElementOutput", this.chkRenderDetails.Checked? "Output":"NoOutput");
if (this.fDetailElementName)
{
if (this.tbDetailElementName.Text.Length > 0)
_Draw.SetElement(node, "DetailDataElementName", this.tbDetailElementName.Text);
else
_Draw.RemoveElement(node, "DetailDataElementName");
}
if (this.fDetailCollectionName)
{
if (this.tbDetailCollectionName.Text.Length > 0)
_Draw.SetElement(node, "DetailDataCollectionName", this.tbDetailCollectionName.Text);
else
_Draw.RemoveElement(node, "DetailDataCollectionName");
}
}
private void CreateTableRow(XmlNode tblNode, string elementName, bool bRepeatOnNewPage)
{
XmlNode node = _Draw.GetNamedChildNode(tblNode, elementName);
if (node == null)
{
node = _Draw.CreateElement(tblNode, elementName, null);
XmlNode tblRows = _Draw.CreateElement(node, "TableRows", null);
_Draw.InsertTableRow(tblRows);
}
if (bRepeatOnNewPage)
_Draw.SetElement(node, "RepeatOnNewPage", "true");
else
_Draw.RemoveElement(node, "RepeatOnNewPage");
return;
}
private void cbDataSet_SelectedIndexChanged(object sender, System.EventArgs e)
{
fDataSet = true;
}
private void chkPBBefore_CheckedChanged(object sender, System.EventArgs e)
{
fPBBefore = true;
}
private void chkPBAfter_CheckedChanged(object sender, System.EventArgs e)
{
fPBAfter = true;
}
private void tbNoRows_TextChanged(object sender, System.EventArgs e)
{
fNoRows = true;
}
private void chkRows_CheckedChanged(object sender, System.EventArgs e)
{
this.fCheckRows = true;
chkFooterRepeat.Enabled = chkFooterRows.Checked;
chkHeaderRepeat.Enabled = chkHeaderRows.Checked;
}
private void chkRenderDetails_CheckedChanged(object sender, System.EventArgs e)
{
fRenderDetails = true;
}
private void tbDetailElementName_TextChanged(object sender, System.EventArgs e)
{
fDetailElementName = true;
}
private void tbDetailCollectionName_TextChanged(object sender, System.EventArgs e)
{
fDetailCollectionName = true;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Avalonia.Utilities
{
/// <summary>
/// Provides utilities for working with types at runtime.
/// </summary>
public static class TypeUtilities
{
private static readonly int[] Conversions =
{
0b101111111111101, // Boolean
0b100001111111110, // Char
0b101111111111111, // SByte
0b101111111111111, // Byte
0b101111111111111, // Int16
0b101111111111111, // UInt16
0b101111111111111, // Int32
0b101111111111111, // UInt32
0b101111111111111, // Int64
0b101111111111111, // UInt64
0b101111111111101, // Single
0b101111111111101, // Double
0b101111111111101, // Decimal
0b110000000000000, // DateTime
0b111111111111111, // String
};
private static readonly int[] ImplicitConversions =
{
0b000000000000001, // Boolean
0b001110111100010, // Char
0b001110101010100, // SByte
0b001111111111000, // Byte
0b001110101010000, // Int16
0b001111111100000, // UInt16
0b001110101000000, // Int32
0b001111110000000, // UInt32
0b001110100000000, // Int64
0b001111000000000, // UInt64
0b000110000000000, // Single
0b000100000000000, // Double
0b001000000000000, // Decimal
0b010000000000000, // DateTime
0b100000000000000, // String
};
private static readonly Type[] InbuiltTypes =
{
typeof(Boolean),
typeof(Char),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(Decimal),
typeof(DateTime),
typeof(String),
};
private static readonly Type[] NumericTypes =
{
typeof(Byte),
typeof(Decimal),
typeof(Double),
typeof(Int16),
typeof(Int32),
typeof(Int64),
typeof(SByte),
typeof(Single),
typeof(UInt16),
typeof(UInt32),
typeof(UInt64),
};
/// <summary>
/// Returns a value indicating whether null can be assigned to the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>True if the type accepts null values; otherwise false.</returns>
public static bool AcceptsNull(Type type)
{
return !type.IsValueType || IsNullableType(type);
}
/// <summary>
/// Try to convert a value to a type by any means possible.
/// </summary>
/// <param name="to">The type to cast to.</param>
/// <param name="value">The value to cast.</param>
/// <param name="culture">The culture to use.</param>
/// <param name="result">If successful, contains the cast value.</param>
/// <returns>True if the cast was successful, otherwise false.</returns>
public static bool TryConvert(Type to, object value, CultureInfo culture, out object result)
{
if (value == null)
{
result = null;
return AcceptsNull(to);
}
if (value == AvaloniaProperty.UnsetValue)
{
result = value;
return true;
}
var toUnderl = Nullable.GetUnderlyingType(to) ?? to;
var from = value.GetType();
if (toUnderl.IsAssignableFrom(from))
{
result = value;
return true;
}
if (toUnderl == typeof(string))
{
result = Convert.ToString(value, culture);
return true;
}
if (toUnderl.IsEnum && from == typeof(string))
{
if (Enum.IsDefined(toUnderl, (string)value))
{
result = Enum.Parse(toUnderl, (string)value);
return true;
}
}
if (!from.IsEnum && toUnderl.IsEnum)
{
result = null;
if (TryConvert(Enum.GetUnderlyingType(toUnderl), value, culture, out object enumValue))
{
result = Enum.ToObject(toUnderl, enumValue);
return true;
}
}
if (from.IsEnum && IsNumeric(toUnderl))
{
try
{
result = Convert.ChangeType((int)value, toUnderl, culture);
return true;
}
catch
{
result = null;
return false;
}
}
var convertableFrom = Array.IndexOf(InbuiltTypes, from);
var convertableTo = Array.IndexOf(InbuiltTypes, toUnderl);
if (convertableFrom != -1 && convertableTo != -1)
{
if ((Conversions[convertableFrom] & 1 << convertableTo) != 0)
{
try
{
result = Convert.ChangeType(value, toUnderl, culture);
return true;
}
catch
{
result = null;
return false;
}
}
}
var toTypeConverter = TypeDescriptor.GetConverter(toUnderl);
if (toTypeConverter.CanConvertFrom(from) == true)
{
result = toTypeConverter.ConvertFrom(null, culture, value);
return true;
}
var fromTypeConverter = TypeDescriptor.GetConverter(from);
if (fromTypeConverter.CanConvertTo(toUnderl) == true)
{
result = fromTypeConverter.ConvertTo(null, culture, value, toUnderl);
return true;
}
var cast = FindTypeConversionOperatorMethod(from, toUnderl, OperatorType.Implicit | OperatorType.Explicit);
if (cast != null)
{
result = cast.Invoke(null, new[] { value });
return true;
}
result = null;
return false;
}
/// <summary>
/// Try to convert a value to a type using the implicit conversions allowed by the C#
/// language.
/// </summary>
/// <param name="to">The type to cast to.</param>
/// <param name="value">The value to cast.</param>
/// <param name="result">If successful, contains the cast value.</param>
/// <returns>True if the cast was successful, otherwise false.</returns>
public static bool TryConvertImplicit(Type to, object value, out object result)
{
if (value == null)
{
result = null;
return AcceptsNull(to);
}
if (value == AvaloniaProperty.UnsetValue)
{
result = value;
return true;
}
var from = value.GetType();
if (to.IsAssignableFrom(from))
{
result = value;
return true;
}
var convertableFrom = Array.IndexOf(InbuiltTypes, from);
var convertableTo = Array.IndexOf(InbuiltTypes, to);
if (convertableFrom != -1 && convertableTo != -1)
{
if ((ImplicitConversions[convertableFrom] & 1 << convertableTo) != 0)
{
try
{
result = Convert.ChangeType(value, to, CultureInfo.InvariantCulture);
return true;
}
catch
{
result = null;
return false;
}
}
}
var cast = FindTypeConversionOperatorMethod(from, to, OperatorType.Implicit);
if (cast != null)
{
result = cast.Invoke(null, new[] { value });
return true;
}
result = null;
return false;
}
/// <summary>
/// Convert a value to a type by any means possible, returning the default for that type
/// if the value could not be converted.
/// </summary>
/// <param name="value">The value to cast.</param>
/// <param name="type">The type to cast to..</param>
/// <param name="culture">The culture to use.</param>
/// <returns>A value of <paramref name="type"/>.</returns>
public static object ConvertOrDefault(object value, Type type, CultureInfo culture)
{
return TryConvert(type, value, culture, out object result) ? result : Default(type);
}
/// <summary>
/// Convert a value to a type using the implicit conversions allowed by the C# language or
/// return the default for the type if the value could not be converted.
/// </summary>
/// <param name="value">The value to cast.</param>
/// <param name="type">The type to cast to..</param>
/// <returns>A value of <paramref name="type"/>.</returns>
public static object ConvertImplicitOrDefault(object value, Type type)
{
return TryConvertImplicit(type, value, out object result) ? result : Default(type);
}
public static T ConvertImplicit<T>(object value)
{
if (TryConvertImplicit(typeof(T), value, out var result))
{
return (T)result;
}
throw new InvalidCastException(
$"Unable to convert object '{value ?? "(null)"}' of type '{value?.GetType()}' to type '{typeof(T)}'.");
}
/// <summary>
/// Gets the default value for the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The default value.</returns>
public static object Default(Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
else
{
return null;
}
}
/// <summary>
/// Determines if a type is numeric. Nullable numeric types are considered numeric.
/// </summary>
/// <returns>
/// True if the type is numeric; otherwise false.
/// </returns>
/// <remarks>
/// Boolean is not considered numeric.
/// </remarks>
public static bool IsNumeric(Type type)
{
if (type == null)
{
return false;
}
Type underlyingType = Nullable.GetUnderlyingType(type);
if (underlyingType != null)
{
return IsNumeric(underlyingType);
}
else
{
return NumericTypes.Contains(type);
}
}
[Flags]
private enum OperatorType
{
Implicit = 1,
Explicit = 2
}
private static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
private static MethodInfo FindTypeConversionOperatorMethod(Type fromType, Type toType, OperatorType operatorType)
{
const string implicitName = "op_Implicit";
const string explicitName = "op_Explicit";
bool allowImplicit = (operatorType & OperatorType.Implicit) != 0;
bool allowExplicit = (operatorType & OperatorType.Explicit) != 0;
foreach (MethodInfo method in fromType.GetMethods())
{
if (!method.IsSpecialName || method.ReturnType != toType)
{
continue;
}
if (allowImplicit && method.Name == implicitName)
{
return method;
}
if (allowExplicit && method.Name == explicitName)
{
return method;
}
}
return null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace FirstREST.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
namespace Projections
{
partial class MiscPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.m_toolTip = new System.Windows.Forms.ToolTip(this.components);
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.m_longitudeDMSTextBox = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.m_latitudeDMSTextBox = new System.Windows.Forms.TextBox();
this.m_LongitudeTextBox = new System.Windows.Forms.TextBox();
this.m_latitudeTextBox = new System.Windows.Forms.TextBox();
this.m_geohashTextBox = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(13, 33);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(54, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Longitude";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(120, 4);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(31, 13);
this.label2.TabIndex = 1;
this.label2.Text = "DMS";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(229, 4);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(88, 13);
this.label3.TabIndex = 2;
this.label3.Text = "Decimal Degrees";
//
// m_longitudeDMSTextBox
//
this.m_longitudeDMSTextBox.Location = new System.Drawing.Point(86, 29);
this.m_longitudeDMSTextBox.Name = "m_longitudeDMSTextBox";
this.m_longitudeDMSTextBox.Size = new System.Drawing.Size(100, 20);
this.m_longitudeDMSTextBox.TabIndex = 3;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(13, 63);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(45, 13);
this.label4.TabIndex = 4;
this.label4.Text = "Latitude";
//
// m_latitudeDMSTextBox
//
this.m_latitudeDMSTextBox.Location = new System.Drawing.Point(86, 56);
this.m_latitudeDMSTextBox.Name = "m_latitudeDMSTextBox";
this.m_latitudeDMSTextBox.Size = new System.Drawing.Size(100, 20);
this.m_latitudeDMSTextBox.TabIndex = 5;
//
// m_LongitudeTextBox
//
this.m_LongitudeTextBox.Location = new System.Drawing.Point(203, 29);
this.m_LongitudeTextBox.Name = "m_LongitudeTextBox";
this.m_LongitudeTextBox.Size = new System.Drawing.Size(137, 20);
this.m_LongitudeTextBox.TabIndex = 6;
//
// m_latitudeTextBox
//
this.m_latitudeTextBox.Location = new System.Drawing.Point(203, 55);
this.m_latitudeTextBox.Name = "m_latitudeTextBox";
this.m_latitudeTextBox.Size = new System.Drawing.Size(137, 20);
this.m_latitudeTextBox.TabIndex = 7;
//
// m_geohashTextBox
//
this.m_geohashTextBox.Location = new System.Drawing.Point(360, 43);
this.m_geohashTextBox.Name = "m_geohashTextBox";
this.m_geohashTextBox.Size = new System.Drawing.Size(155, 20);
this.m_geohashTextBox.TabIndex = 8;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(409, 4);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(50, 13);
this.label5.TabIndex = 9;
this.label5.Text = "Geohash";
//
// button1
//
this.button1.Location = new System.Drawing.Point(96, 83);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 10;
this.button1.Text = "Convert ->";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.OnConvertDMS);
//
// button2
//
this.button2.Location = new System.Drawing.Point(229, 83);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(85, 23);
this.button2.TabIndex = 11;
this.button2.Text = "<- Convert ->";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.OnConvert);
//
// button3
//
this.button3.Location = new System.Drawing.Point(400, 83);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 23);
this.button3.TabIndex = 12;
this.button3.Text = "<- Convert";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.OnConvertGeohash);
//
// button4
//
this.button4.Location = new System.Drawing.Point(541, 4);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 23);
this.button4.TabIndex = 13;
this.button4.Text = "Validate";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.OnValidate);
//
// MiscPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.label5);
this.Controls.Add(this.m_geohashTextBox);
this.Controls.Add(this.m_latitudeTextBox);
this.Controls.Add(this.m_LongitudeTextBox);
this.Controls.Add(this.m_latitudeDMSTextBox);
this.Controls.Add(this.label4);
this.Controls.Add(this.m_longitudeDMSTextBox);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "MiscPanel";
this.Size = new System.Drawing.Size(977, 389);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolTip m_toolTip;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox m_longitudeDMSTextBox;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox m_latitudeDMSTextBox;
private System.Windows.Forms.TextBox m_LongitudeTextBox;
private System.Windows.Forms.TextBox m_latitudeTextBox;
private System.Windows.Forms.TextBox m_geohashTextBox;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.IO.Tests;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class ReadOnlyMemoryContentTest
{
public static IEnumerable<object[]> ContentLengthsAndUseArrays()
{
foreach (int length in new[] { 0, 1, 4096 })
{
foreach (bool useArray in new[] { true, false })
{
yield return new object[] { length, useArray };
}
}
}
public static IEnumerable<object[]> TrueFalse()
{
yield return new object[] { true };
yield return new object[] { false };
}
[Theory]
[MemberData(nameof(ContentLengthsAndUseArrays))]
public void ContentLength_LengthMatchesArrayLength(int contentLength, bool useArray)
{
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);
Assert.Equal(contentLength, content.Headers.ContentLength);
ownedMemory?.Dispose();
}
[Theory]
[MemberData(nameof(TrueFalse))]
public async Task ReadAsStreamAsync_TrivialMembersHaveExpectedValuesAndBehavior(bool useArray)
{
const int ContentLength = 42;
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
using (Stream stream = await content.ReadAsStreamAsync())
{
// property values
Assert.Equal(ContentLength, stream.Length);
Assert.Equal(0, stream.Position);
Assert.True(stream.CanRead);
Assert.True(stream.CanSeek);
Assert.False(stream.CanWrite);
// not supported
Assert.Throws<NotSupportedException>(() => stream.SetLength(12345));
Assert.Throws<NotSupportedException>(() => stream.WriteByte(0));
Assert.Throws<NotSupportedException>(() => stream.Write(new byte[1], 0, 1));
Assert.Throws<NotSupportedException>(() => stream.Write(new ReadOnlySpan<byte>(new byte[1])));
await Assert.ThrowsAsync<NotSupportedException>(() => stream.WriteAsync(new byte[1], 0, 1));
await Assert.ThrowsAsync<NotSupportedException>(() => stream.WriteAsync(new ReadOnlyMemory<byte>(new byte[1])));
// nops
stream.Flush();
await stream.FlushAsync();
}
ownedMemory?.Dispose();
}
[Theory]
[MemberData(nameof(TrueFalse))]
public async Task ReadAsStreamAsync_Seek(bool useArray)
{
const int ContentLength = 42;
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
using (Stream s = await content.ReadAsStreamAsync())
{
foreach (int pos in new[] { 0, ContentLength / 2, ContentLength - 1 })
{
s.Position = pos;
Assert.Equal(pos, s.Position);
Assert.Equal(memory.Span[pos], s.ReadByte());
}
foreach (int pos in new[] { 0, ContentLength / 2, ContentLength - 1 })
{
Assert.Equal(0, s.Seek(0, SeekOrigin.Begin));
Assert.Equal(memory.Span[0], s.ReadByte());
}
Assert.Equal(ContentLength, s.Seek(0, SeekOrigin.End));
Assert.Equal(s.Position, s.Length);
Assert.Equal(-1, s.ReadByte());
Assert.Equal(0, s.Seek(-ContentLength, SeekOrigin.End));
Assert.Equal(0, s.Position);
Assert.Equal(memory.Span[0], s.ReadByte());
s.Position = 0;
Assert.Equal(0, s.Seek(0, SeekOrigin.Current));
Assert.Equal(0, s.Position);
Assert.Equal(1, s.Seek(1, SeekOrigin.Current));
Assert.Equal(1, s.Position);
Assert.Equal(memory.Span[1], s.ReadByte());
Assert.Equal(2, s.Position);
Assert.Equal(3, s.Seek(1, SeekOrigin.Current));
Assert.Equal(1, s.Seek(-2, SeekOrigin.Current));
Assert.Equal(int.MaxValue, s.Seek(int.MaxValue, SeekOrigin.Begin));
Assert.Equal(int.MaxValue, s.Position);
Assert.Equal(int.MaxValue, s.Seek(0, SeekOrigin.Current));
Assert.Equal(int.MaxValue, s.Position);
Assert.Equal(int.MaxValue, s.Seek(int.MaxValue - ContentLength, SeekOrigin.End));
Assert.Equal(int.MaxValue, s.Position);
Assert.Equal(-1, s.ReadByte());
Assert.Equal(int.MaxValue, s.Position);
Assert.Throws<ArgumentOutOfRangeException>("value", () => s.Position = -1);
Assert.Throws<IOException>(() => s.Seek(-1, SeekOrigin.Begin));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => s.Position = (long)int.MaxValue + 1);
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => s.Seek((long)int.MaxValue + 1, SeekOrigin.Begin));
Assert.ThrowsAny<ArgumentException>(() => s.Seek(0, (SeekOrigin)42));
}
ownedMemory?.Dispose();
}
[Theory]
[MemberData(nameof(ContentLengthsAndUseArrays))]
public async Task ReadAsStreamAsync_ReadByte_MatchesInput(int contentLength, bool useArray)
{
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);
using (Stream stream = await content.ReadAsStreamAsync())
{
for (int i = 0; i < contentLength; i++)
{
Assert.Equal(memory.Span[i], stream.ReadByte());
Assert.Equal(i + 1, stream.Position);
}
Assert.Equal(-1, stream.ReadByte());
Assert.Equal(stream.Length, stream.Position);
}
ownedMemory?.Dispose();
}
[Theory]
[MemberData(nameof(TrueFalse))]
public async Task ReadAsStreamAsync_Read_InvalidArguments(bool useArray)
{
const int ContentLength = 42;
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
using (Stream stream = await content.ReadAsStreamAsync())
{
AssertExtensions.Throws<ArgumentNullException>("buffer", () => stream.Read(null, 0, 0));
AssertExtensions.Throws<ArgumentNullException>("buffer", () => { stream.ReadAsync(null, 0, 0); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => stream.Read(new byte[1], -1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => stream.Read(new byte[1], -1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => stream.Read(new byte[1], 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => stream.Read(new byte[1], 0, -1));
Assert.ThrowsAny<ArgumentException>(() => { stream.ReadAsync(new byte[1], 2, 0); });
Assert.ThrowsAny<ArgumentException>(() => { stream.ReadAsync(new byte[1], 2, 0); });
Assert.ThrowsAny<ArgumentException>(() => { stream.ReadAsync(new byte[1], 0, 2); });
Assert.ThrowsAny<ArgumentException>(() => { stream.ReadAsync(new byte[1], 0, 2); });
}
ownedMemory?.Dispose();
}
[Theory]
[InlineData(0, false)] // Read(byte[], ...)
[InlineData(1, false)] // Read(Span<byte>, ...)
[InlineData(2, false)] // ReadAsync(byte[], ...)
[InlineData(3, false)] // ReadAsync(Memory<byte>,...)
[InlineData(4, false)] // Begin/EndRead(byte[],...)
[InlineData(0, true)] // Read(byte[], ...)
[InlineData(1, true)] // Read(Span<byte>, ...)
[InlineData(2, true)] // ReadAsync(byte[], ...)
[InlineData(3, true)] // ReadAsync(Memory<byte>,...)
[InlineData(4, true)] // Begin/EndRead(byte[],...)
public async Task ReadAsStreamAsync_ReadMultipleBytes_MatchesInput(int mode, bool useArray)
{
const int ContentLength = 1024;
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
var buffer = new byte[3];
using (Stream stream = await content.ReadAsStreamAsync())
{
for (int i = 0; i < ContentLength; i += buffer.Length)
{
int bytesRead =
mode == 0 ? stream.Read(buffer, 0, buffer.Length) :
mode == 1 ? stream.Read(new Span<byte>(buffer)) :
mode == 2 ? await stream.ReadAsync(buffer, 0, buffer.Length) :
mode == 3 ? await stream.ReadAsync(new Memory<byte>(buffer)) :
await Task.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null);
Assert.Equal(Math.Min(buffer.Length, ContentLength - i), bytesRead);
for (int j = 0; j < bytesRead; j++)
{
Assert.Equal(memory.Span[i + j], buffer[j]);
}
Assert.Equal(i + bytesRead, stream.Position);
}
Assert.Equal(0,
mode == 0 ? stream.Read(buffer, 0, buffer.Length) :
mode == 1 ? stream.Read(new Span<byte>(buffer)) :
mode == 2 ? await stream.ReadAsync(buffer, 0, buffer.Length) :
mode == 3 ? await stream.ReadAsync(new Memory<byte>(buffer)) :
await Task.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null));
}
ownedMemory?.Dispose();
}
[Theory]
[MemberData(nameof(TrueFalse))]
public async Task ReadAsStreamAsync_ReadWithCancelableToken_MatchesInput(bool useArray)
{
const int ContentLength = 100;
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
var buffer = new byte[1];
var cts = new CancellationTokenSource();
int bytesRead;
using (Stream stream = await content.ReadAsStreamAsync())
{
for (int i = 0; i < ContentLength; i++)
{
switch (i % 2)
{
case 0:
bytesRead = await stream.ReadAsync(buffer, 0, 1, cts.Token);
break;
default:
bytesRead = await stream.ReadAsync(new Memory<byte>(buffer), cts.Token);
break;
}
Assert.Equal(1, bytesRead);
Assert.Equal(memory.Span[i], buffer[0]);
}
}
ownedMemory?.Dispose();
}
[Theory]
[MemberData(nameof(TrueFalse))]
public async Task ReadAsStreamAsync_ReadWithCanceledToken_MatchesInput(bool useArray)
{
const int ContentLength = 2;
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
using (Stream stream = await content.ReadAsStreamAsync())
{
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => stream.ReadAsync(new byte[1], 0, 1, new CancellationToken(true)));
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await stream.ReadAsync(new Memory<byte>(new byte[1]), new CancellationToken(true)));
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await stream.CopyToAsync(new MemoryStream(), 1, new CancellationToken(true)));
}
ownedMemory?.Dispose();
}
[Theory]
[MemberData(nameof(ContentLengthsAndUseArrays))]
public async Task CopyToAsync_AllContentCopied(int contentLength, bool useArray)
{
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);
var destination = new MemoryStream();
await content.CopyToAsync(destination);
Assert.Equal<byte>(memory.ToArray(), destination.ToArray());
ownedMemory?.Dispose();
}
[Theory]
[MemberData(nameof(ContentLengthsAndUseArrays))]
public async Task ReadAsStreamAsync_CopyTo_AllContentCopied(int contentLength, bool useArray)
{
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);
var destination = new MemoryStream();
using (Stream s = await content.ReadAsStreamAsync())
{
s.CopyTo(destination);
}
Assert.Equal<byte>(memory.ToArray(), destination.ToArray());
ownedMemory?.Dispose();
}
[Theory]
[MemberData(nameof(TrueFalse))]
public async Task ReadAsStreamAsync_CopyTo_InvalidArguments(bool useArray)
{
const int ContentLength = 42;
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
using (Stream s = await content.ReadAsStreamAsync())
{
AssertExtensions.Throws<ArgumentNullException>("destination", () => s.CopyTo(null));
AssertExtensions.Throws<ArgumentNullException>("destination", () => { s.CopyToAsync(null); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => s.CopyTo(new MemoryStream(), 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => { s.CopyToAsync(new MemoryStream(), 0); });
Assert.Throws<NotSupportedException>(() => s.CopyTo(new MemoryStream(new byte[1], writable:false)));
Assert.Throws<NotSupportedException>(() => { s.CopyToAsync(new MemoryStream(new byte[1], writable: false)); });
var disposedDestination = new MemoryStream();
disposedDestination.Dispose();
Assert.Throws<ObjectDisposedException>(() => s.CopyTo(disposedDestination));
Assert.Throws<ObjectDisposedException>(() => { s.CopyToAsync(disposedDestination); });
}
ownedMemory?.Dispose();
}
[Theory]
[MemberData(nameof(ContentLengthsAndUseArrays))]
public async Task ReadAsStreamAsync_CopyToAsync_AllContentCopied(int contentLength, bool useArray)
{
Memory<byte> memory;
OwnedMemory<byte> ownedMemory;
ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);
var destination = new MemoryStream();
using (Stream s = await content.ReadAsStreamAsync())
{
await s.CopyToAsync(destination);
}
Assert.Equal<byte>(memory.ToArray(), destination.ToArray());
ownedMemory?.Dispose();
}
private static ReadOnlyMemoryContent CreateContent(int contentLength, bool useArray, out Memory<byte> memory, out OwnedMemory<byte> ownedMemory)
{
if (useArray)
{
memory = new byte[contentLength];
ownedMemory = null;
}
else
{
ownedMemory = new NativeOwnedMemory(contentLength);
memory = ownedMemory.Memory;
}
new Random(contentLength).NextBytes(memory.Span);
return new ReadOnlyMemoryContent(memory);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShuffleDouble1()
{
var test = new ImmBinaryOpTest__ShuffleDouble1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__ShuffleDouble1
{
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__ShuffleDouble1 testClass)
{
var result = Sse2.Shuffle(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable;
static ImmBinaryOpTest__ShuffleDouble1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public ImmBinaryOpTest__ShuffleDouble1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Shuffle(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Shuffle(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Shuffle(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Shuffle), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Shuffle), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Shuffle), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Shuffle(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.Shuffle(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Shuffle(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Shuffle(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__ShuffleDouble1();
var result = Sse2.Shuffle(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Shuffle(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Shuffle(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(left[1]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(right[0]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Shuffle)}<Double>(Vector128<Double>.1, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace System.Xml.XPath
{
internal class XNodeNavigator : XPathNavigator, IXmlLineInfo
{
internal static readonly string xmlPrefixNamespace = XNamespace.Xml.NamespaceName;
internal static readonly string xmlnsPrefixNamespace = XNamespace.Xmlns.NamespaceName;
private const int DocumentContentMask =
(1 << (int)XmlNodeType.Element) |
(1 << (int)XmlNodeType.ProcessingInstruction) |
(1 << (int)XmlNodeType.Comment);
private static readonly int[] s_ElementContentMasks = {
0, // Root
(1 << (int)XmlNodeType.Element), // Element
0, // Attribute
0, // Namespace
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text), // Text
0, // SignificantWhitespace
0, // Whitespace
(1 << (int)XmlNodeType.ProcessingInstruction), // ProcessingInstruction
(1 << (int)XmlNodeType.Comment), // Comment
(1 << (int)XmlNodeType.Element) |
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text) |
(1 << (int)XmlNodeType.ProcessingInstruction) |
(1 << (int)XmlNodeType.Comment) // All
};
private const int TextMask =
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text);
private static XAttribute s_XmlNamespaceDeclaration;
// The navigator position is encoded by the tuple (source, parent).
// Namespace declaration uses (instance, parent element).
// Common XObjects uses (instance, null).
private XObject _source;
private XElement _parent;
private XmlNameTable _nameTable;
public XNodeNavigator(XNode node, XmlNameTable nameTable)
{
_source = node;
_nameTable = nameTable != null ? nameTable : CreateNameTable();
}
public XNodeNavigator(XNodeNavigator other)
{
_source = other._source;
_parent = other._parent;
_nameTable = other._nameTable;
}
public override string BaseURI
{
get
{
if (_source != null)
{
return _source.BaseUri;
}
if (_parent != null)
{
return _parent.BaseUri;
}
return string.Empty;
}
}
public override bool HasAttributes
{
get
{
XElement element = _source as XElement;
if (element != null)
{
foreach (XAttribute attribute in element.Attributes())
{
if (!attribute.IsNamespaceDeclaration)
{
return true;
}
}
}
return false;
}
}
public override bool HasChildren
{
get
{
XContainer container = _source as XContainer;
if (container != null)
{
foreach (XNode node in container.Nodes())
{
if (IsContent(container, node))
{
return true;
}
}
}
return false;
}
}
public override bool IsEmptyElement
{
get
{
XElement e = _source as XElement;
return e != null && e.IsEmpty;
}
}
public override string LocalName
{
get { return _nameTable.Add(GetLocalName()); }
}
private string GetLocalName()
{
XElement e = _source as XElement;
if (e != null)
{
return e.Name.LocalName;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null && a.Name.NamespaceName.Length == 0)
{
return string.Empty; // backcompat
}
return a.Name.LocalName;
}
XProcessingInstruction p = _source as XProcessingInstruction;
if (p != null)
{
return p.Target;
}
return string.Empty;
}
public override string Name
{
get
{
string prefix = GetPrefix();
if (prefix.Length == 0)
{
return _nameTable.Add(GetLocalName());
}
return _nameTable.Add(string.Concat(prefix, ":", GetLocalName()));
}
}
public override string NamespaceURI
{
get { return _nameTable.Add(GetNamespaceURI()); }
}
private string GetNamespaceURI()
{
XElement e = _source as XElement;
if (e != null)
{
return e.Name.NamespaceName;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null)
{
return string.Empty; // backcompat
}
return a.Name.NamespaceName;
}
return string.Empty;
}
public override XmlNameTable NameTable
{
get { return _nameTable; }
}
public override XPathNodeType NodeType
{
get
{
if (_source != null)
{
switch (_source.NodeType)
{
case XmlNodeType.Element:
return XPathNodeType.Element;
case XmlNodeType.Attribute:
XAttribute attribute = (XAttribute)_source;
return attribute.IsNamespaceDeclaration ? XPathNodeType.Namespace : XPathNodeType.Attribute;
case XmlNodeType.Document:
return XPathNodeType.Root;
case XmlNodeType.Comment:
return XPathNodeType.Comment;
case XmlNodeType.ProcessingInstruction:
return XPathNodeType.ProcessingInstruction;
default:
return XPathNodeType.Text;
}
}
return XPathNodeType.Text;
}
}
public override string Prefix
{
get { return _nameTable.Add(GetPrefix()); }
}
private string GetPrefix()
{
XElement e = _source as XElement;
if (e != null)
{
string prefix = e.GetPrefixOfNamespace(e.Name.Namespace);
if (prefix != null)
{
return prefix;
}
return string.Empty;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null)
{
return string.Empty; // backcompat
}
string prefix = a.GetPrefixOfNamespace(a.Name.Namespace);
if (prefix != null)
{
return prefix;
}
}
return string.Empty;
}
public override object UnderlyingObject
{
get
{
return _source;
}
}
public override string Value
{
get
{
if (_source != null)
{
switch (_source.NodeType)
{
case XmlNodeType.Element:
return ((XElement)_source).Value;
case XmlNodeType.Attribute:
return ((XAttribute)_source).Value;
case XmlNodeType.Document:
XElement root = ((XDocument)_source).Root;
return root != null ? root.Value : string.Empty;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
return CollectText((XText)_source);
case XmlNodeType.Comment:
return ((XComment)_source).Value;
case XmlNodeType.ProcessingInstruction:
return ((XProcessingInstruction)_source).Data;
default:
return string.Empty;
}
}
return string.Empty;
}
}
public override XPathNavigator Clone()
{
return new XNodeNavigator(this);
}
public override bool IsSamePosition(XPathNavigator navigator)
{
XNodeNavigator other = navigator as XNodeNavigator;
if (other == null)
{
return false;
}
return IsSamePosition(this, other);
}
public override bool MoveTo(XPathNavigator navigator)
{
XNodeNavigator other = navigator as XNodeNavigator;
if (other != null)
{
_source = other._source;
_parent = other._parent;
return true;
}
return false;
}
public override bool MoveToAttribute(string localName, string namespaceName)
{
XElement e = _source as XElement;
if (e != null)
{
foreach (XAttribute attribute in e.Attributes())
{
if (attribute.Name.LocalName == localName &&
attribute.Name.NamespaceName == namespaceName &&
!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
return false;
}
public override bool MoveToChild(string localName, string namespaceName)
{
XContainer c = _source as XContainer;
if (c != null)
{
foreach (XElement element in c.Elements())
{
if (element.Name.LocalName == localName &&
element.Name.NamespaceName == namespaceName)
{
_source = element;
return true;
}
}
}
return false;
}
public override bool MoveToChild(XPathNodeType type)
{
XContainer c = _source as XContainer;
if (c != null)
{
int mask = GetElementContentMask(type);
if ((TextMask & mask) != 0 && c.GetParent() == null && c is XDocument)
{
mask &= ~TextMask;
}
foreach (XNode node in c.Nodes())
{
if (((1 << (int)node.NodeType) & mask) != 0)
{
_source = node;
return true;
}
}
}
return false;
}
public override bool MoveToFirstAttribute()
{
XElement e = _source as XElement;
if (e != null)
{
foreach (XAttribute attribute in e.Attributes())
{
if (!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
return false;
}
public override bool MoveToFirstChild()
{
XContainer container = _source as XContainer;
if (container != null)
{
foreach (XNode node in container.Nodes())
{
if (IsContent(container, node))
{
_source = node;
return true;
}
}
}
return false;
}
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
XElement e = _source as XElement;
if (e != null)
{
XAttribute a = null;
switch (scope)
{
case XPathNamespaceScope.Local:
a = GetFirstNamespaceDeclarationLocal(e);
break;
case XPathNamespaceScope.ExcludeXml:
a = GetFirstNamespaceDeclarationGlobal(e);
while (a != null && a.Name.LocalName == "xml")
{
a = GetNextNamespaceDeclarationGlobal(a);
}
break;
case XPathNamespaceScope.All:
a = GetFirstNamespaceDeclarationGlobal(e);
if (a == null)
{
a = GetXmlNamespaceDeclaration();
}
break;
}
if (a != null)
{
_source = a;
_parent = e;
return true;
}
}
return false;
}
public override bool MoveToId(string id)
{
throw new NotSupportedException(SR.NotSupported_MoveToId);
}
public override bool MoveToNamespace(string localName)
{
XElement e = _source as XElement;
if (e != null)
{
if (localName == "xmlns")
{
return false; // backcompat
}
if (localName != null && localName.Length == 0)
{
localName = "xmlns"; // backcompat
}
XAttribute a = GetFirstNamespaceDeclarationGlobal(e);
while (a != null)
{
if (a.Name.LocalName == localName)
{
_source = a;
_parent = e;
return true;
}
a = GetNextNamespaceDeclarationGlobal(a);
}
if (localName == "xml")
{
_source = GetXmlNamespaceDeclaration();
_parent = e;
return true;
}
}
return false;
}
public override bool MoveToNext()
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
XNode next = null;
for (XNode node = currentNode; node != null; node = next)
{
next = node.NextNode;
if (next == null)
{
break;
}
if (IsContent(container, next) && !(node is XText && next is XText))
{
_source = next;
return true;
}
}
}
}
return false;
}
public override bool MoveToNext(string localName, string namespaceName)
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
foreach (XElement element in currentNode.ElementsAfterSelf())
{
if (element.Name.LocalName == localName &&
element.Name.NamespaceName == namespaceName)
{
_source = element;
return true;
}
}
}
return false;
}
public override bool MoveToNext(XPathNodeType type)
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
int mask = GetElementContentMask(type);
if ((TextMask & mask) != 0 && container.GetParent() == null && container is XDocument)
{
mask &= ~TextMask;
}
XNode next = null;
for (XNode node = currentNode; node != null; node = next)
{
next = node.NextNode;
if (((1 << (int)next.NodeType) & mask) != 0 && !(node is XText && next is XText))
{
_source = next;
return true;
}
}
}
}
return false;
}
public override bool MoveToNextAttribute()
{
XAttribute currentAttribute = _source as XAttribute;
if (currentAttribute != null && _parent == null)
{
XElement e = (XElement)currentAttribute.GetParent();
if (e != null)
{
for (XAttribute attribute = currentAttribute.NextAttribute; attribute != null; attribute = attribute.NextAttribute)
{
if (!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
}
return false;
}
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
XAttribute a = _source as XAttribute;
if (a != null && _parent != null && !IsXmlNamespaceDeclaration(a))
{
switch (scope)
{
case XPathNamespaceScope.Local:
if (a.GetParent() != _parent)
{
return false;
}
a = GetNextNamespaceDeclarationLocal(a);
break;
case XPathNamespaceScope.ExcludeXml:
do
{
a = GetNextNamespaceDeclarationGlobal(a);
} while (a != null &&
(a.Name.LocalName == "xml" ||
HasNamespaceDeclarationInScope(a, _parent)));
break;
case XPathNamespaceScope.All:
do
{
a = GetNextNamespaceDeclarationGlobal(a);
} while (a != null &&
HasNamespaceDeclarationInScope(a, _parent));
if (a == null &&
!HasNamespaceDeclarationInScope(GetXmlNamespaceDeclaration(), _parent))
{
a = GetXmlNamespaceDeclaration();
}
break;
}
if (a != null)
{
_source = a;
return true;
}
}
return false;
}
public override bool MoveToParent()
{
if (_parent != null)
{
_source = _parent;
_parent = null;
return true;
}
XNode parentNode = _source.GetParent();
if (parentNode != null)
{
_source = parentNode;
return true;
}
return false;
}
public override bool MoveToPrevious()
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
XNode previous = null;
foreach (XNode node in container.Nodes())
{
if (node == currentNode)
{
if (previous != null)
{
_source = previous;
return true;
}
return false;
}
if (IsContent(container, node))
{
previous = node;
}
}
}
}
return false;
}
public override XmlReader ReadSubtree()
{
XContainer c = _source as XContainer;
if (c == null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadNodeType, NodeType));
return c.CreateReader();
}
bool IXmlLineInfo.HasLineInfo()
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.HasLineInfo();
}
return false;
}
int IXmlLineInfo.LineNumber
{
get
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.LineNumber;
}
return 0;
}
}
int IXmlLineInfo.LinePosition
{
get
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.LinePosition;
}
return 0;
}
}
private static string CollectText(XText n)
{
string s = n.Value;
if (n.GetParent() != null)
{
foreach (XNode node in n.NodesAfterSelf())
{
XText t = node as XText;
if (t == null) break;
s += t.Value;
}
}
return s;
}
private static XmlNameTable CreateNameTable()
{
XmlNameTable nameTable = new NameTable();
nameTable.Add(string.Empty);
nameTable.Add(xmlnsPrefixNamespace);
nameTable.Add(xmlPrefixNamespace);
return nameTable;
}
private static bool IsContent(XContainer c, XNode n)
{
if (c.GetParent() != null || c is XElement)
{
return true;
}
return ((1 << (int)n.NodeType) & DocumentContentMask) != 0;
}
private static bool IsSamePosition(XNodeNavigator n1, XNodeNavigator n2)
{
return n1._source == n2._source && n1._source.GetParent() == n2._source.GetParent();
}
private static bool IsXmlNamespaceDeclaration(XAttribute a)
{
return (object)a == (object)GetXmlNamespaceDeclaration();
}
private static int GetElementContentMask(XPathNodeType type)
{
return s_ElementContentMasks[(int)type];
}
private static XAttribute GetFirstNamespaceDeclarationGlobal(XElement e)
{
do
{
XAttribute a = GetFirstNamespaceDeclarationLocal(e);
if (a != null)
{
return a;
}
e = e.Parent;
} while (e != null);
return null;
}
private static XAttribute GetFirstNamespaceDeclarationLocal(XElement e)
{
foreach (XAttribute attribute in e.Attributes())
{
if (attribute.IsNamespaceDeclaration)
{
return attribute;
}
}
return null;
}
private static XAttribute GetNextNamespaceDeclarationGlobal(XAttribute a)
{
XElement e = (XElement)a.GetParent();
if (e == null)
{
return null;
}
XAttribute next = GetNextNamespaceDeclarationLocal(a);
if (next != null)
{
return next;
}
e = e.Parent;
if (e == null)
{
return null;
}
return GetFirstNamespaceDeclarationGlobal(e);
}
private static XAttribute GetNextNamespaceDeclarationLocal(XAttribute a)
{
XElement e = a.Parent;
if (e == null)
{
return null;
}
a = a.NextAttribute;
while (a != null)
{
if (a.IsNamespaceDeclaration)
{
return a;
}
a = a.NextAttribute;
}
return null;
}
private static XAttribute GetXmlNamespaceDeclaration()
{
if (s_XmlNamespaceDeclaration == null)
{
System.Threading.Interlocked.CompareExchange(ref s_XmlNamespaceDeclaration, new XAttribute(XNamespace.Xmlns.GetName("xml"), xmlPrefixNamespace), null);
}
return s_XmlNamespaceDeclaration;
}
private static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e)
{
XName name = a.Name;
while (e != null && e != a.GetParent())
{
if (e.Attribute(name) != null)
{
return true;
}
e = e.Parent;
}
return false;
}
}
internal struct XPathEvaluator
{
public object Evaluate<T>(XNode node, string expression, IXmlNamespaceResolver resolver) where T : class
{
XPathNavigator navigator = node.CreateNavigator();
object result = navigator.Evaluate(expression, resolver);
XPathNodeIterator iterator = result as XPathNodeIterator;
if (iterator != null)
{
return EvaluateIterator<T>(iterator);
}
if (!(result is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, result.GetType()));
return (T)result;
}
private IEnumerable<T> EvaluateIterator<T>(XPathNodeIterator result)
{
foreach (XPathNavigator navigator in result)
{
object r = navigator.UnderlyingObject;
if (!(r is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, r.GetType()));
yield return (T)r;
XText t = r as XText;
if (t != null && t.GetParent() != null)
{
do
{
t = t.NextNode as XText;
if (t == null) break;
yield return (T)(object)t;
} while (t != t.GetParent().LastNode);
}
}
}
}
/// <summary>
/// Extension methods
/// </summary>
public static class Extensions
{
/// <summary>
/// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/>
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <returns>An <see cref="XPathNavigator"/></returns>
public static XPathNavigator CreateNavigator(this XNode node)
{
return node.CreateNavigator(null);
}
/// <summary>
/// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/>
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="nameTable">The <see cref="XmlNameTable"/> to be used by
/// the <see cref="XPathNavigator"/></param>
/// <returns>An <see cref="XPathNavigator"/></returns>
public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable nameTable)
{
if (node == null) throw new ArgumentNullException(nameof(node));
if (node is XDocumentType) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.DocumentType));
XText text = node as XText;
if (text != null)
{
if (text.GetParent() is XDocument) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.Whitespace));
node = CalibrateText(text);
}
return new XNodeNavigator(node, nameTable);
}
/// <summary>
/// Evaluates an XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>The result of evaluating the expression which can be typed as bool, double, string or
/// IEnumerable</returns>
public static object XPathEvaluate(this XNode node, string expression)
{
return node.XPathEvaluate(expression, null);
}
/// <summary>
/// Evaluates an XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"> for the namespace
/// prefixes used in the XPath expression</see></param>
/// <returns>The result of evaluating the expression which can be typed as bool, double, string or
/// IEnumerable</returns>
public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
if (node == null) throw new ArgumentNullException(nameof(node));
return new XPathEvaluator().Evaluate<object>(node, expression, resolver);
}
/// <summary>
/// Select an <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>An <see cref="XElement"> or null</see></returns>
public static XElement XPathSelectElement(this XNode node, string expression)
{
return node.XPathSelectElement(expression, null);
}
/// <summary>
/// Select an <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace
/// prefixes used in the XPath expression</param>
/// <returns>An <see cref="XElement"> or null</see></returns>
public static XElement XPathSelectElement(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
return node.XPathSelectElements(expression, resolver).FirstOrDefault();
}
/// <summary>
/// Select a set of <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>An <see cref="IEnumerable<XElement>"/> corresponding to the resulting set of elements</returns>
public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression)
{
return node.XPathSelectElements(expression, null);
}
/// <summary>
/// Select a set of <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace
/// prefixes used in the XPath expression</param>
/// <returns>An <see cref="IEnumerable<XElement>"/> corresponding to the resulting set of elements</returns>
public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
if (node == null) throw new ArgumentNullException(nameof(node));
return (IEnumerable<XElement>)new XPathEvaluator().Evaluate<XElement>(node, expression, resolver);
}
private static XText CalibrateText(XText n)
{
XContainer parentNode = n.GetParent();
if (parentNode == null)
{
return n;
}
foreach (XNode node in parentNode.Nodes())
{
XText t = node as XText;
bool isTextNode = t != null;
if (isTextNode && node == n)
{
return t;
}
}
System.Diagnostics.Debug.Fail("Parent node doesn't contain itself.");
return null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Vegvesen.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using MonoGame.Extended.Input.InputListeners;
namespace MonoGame.Extended.Gui.Controls
{
public sealed class TextBox : Control
{
public TextBox(string text = null)
{
Text = text ?? string.Empty;
HorizontalTextAlignment = HorizontalAlignment.Left;
}
public TextBox()
: this(null)
{
}
public int SelectionStart { get; set; }
public char? PasswordCharacter { get; set; }
private string _text;
public string Text
{
get { return _text; }
set
{
if (_text != value)
{
_text = value;
OnTextChanged();
}
}
}
private void OnTextChanged()
{
if (!string.IsNullOrEmpty(Text) && SelectionStart > Text.Length)
SelectionStart = Text.Length;
TextChanged?.Invoke(this, EventArgs.Empty);
}
public event EventHandler TextChanged;
public override IEnumerable<Control> Children { get; } = Enumerable.Empty<Control>();
public override Size GetContentSize(IGuiContext context)
{
var font = Font ?? context.DefaultFont;
var stringSize = (Size) font.MeasureString(Text ?? string.Empty);
return new Size(stringSize.Width,
stringSize.Height < font.LineHeight ? font.LineHeight : stringSize.Height);
}
//protected override Size2 CalculateDesiredSize(IGuiContext context, Size2 availableSize)
//{
// var font = Font ?? context.DefaultFont;
// return new Size2(Width + Padding.Left + Padding.Right, (Height <= 0.0f ? font.LineHeight + 2 : Height) + Padding.Top + Padding.Bottom);
//}
public override bool OnPointerDown(IGuiContext context, PointerEventArgs args)
{
SelectionStart = FindNearestGlyphIndex(context, args.Position);
_isCaretVisible = true;
//_selectionIndexes.Clear();
//_selectionIndexes.Push(SelectionStart);
//_startSelectionBox = Text.Length > 0;
return base.OnPointerDown(context, args);
}
//public override bool OnPointerMove(IGuiContext context, PointerEventArgs args)
//{
// if (_startSelectionBox)
// {
// var selection = FindNearestGlyphIndex(context, args.Position);
// if (selection != _selectionIndexes.Peek())
// {
// if (_selectionIndexes.Count == 1)
// {
// _selectionIndexes.Push(selection);
// }
// else if (_selectionIndexes.Last() < _selectionIndexes.Peek())
// {
// if (selection > _selectionIndexes.Peek()) _selectionIndexes.Pop();
// else _selectionIndexes.Push(selection);
// }
// else
// {
// if (selection < _selectionIndexes.Peek()) _selectionIndexes.Pop();
// else _selectionIndexes.Push(selection);
// }
// SelectionStart = selection;
// }
// }
// return base.OnPointerMove(context, args);
//}
//public override bool OnPointerLeave(IGuiContext context, PointerEventArgs args)
//{
// _startSelectionBox = false;
// return base.OnPointerLeave(context, args);
//}
//public override bool OnPointerUp(IGuiContext context, PointerEventArgs args)
//{
// _startSelectionBox = false;
// return base.OnPointerUp(context, args);
//}
private int FindNearestGlyphIndex(IGuiContext context, Point position)
{
var font = Font ?? context.DefaultFont;
var textInfo = GetTextInfo(context, Text, ContentRectangle, HorizontalTextAlignment, VerticalTextAlignment);
var i = 0;
foreach (var glyph in font.GetGlyphs(textInfo.Text, textInfo.Position))
{
var fontRegionWidth = glyph.FontRegion?.Width ?? 0;
var glyphMiddle = (int) (glyph.Position.X + fontRegionWidth * 0.5f);
if (position.X >= glyphMiddle)
{
i++;
continue;
}
return i;
}
return i;
}
public override bool OnKeyPressed(IGuiContext context, KeyboardEventArgs args)
{
switch (args.Key)
{
case Keys.Tab:
case Keys.Enter:
return true;
case Keys.Back:
if (Text.Length > 0)
{
if (SelectionStart > 0) // && _selectionIndexes.Count <= 1)
{
SelectionStart--;
Text = Text.Remove(SelectionStart, 1);
}
//else
//{
// var start = MathHelper.Min(_selectionIndexes.Last(), _selectionIndexes.Peek());
// var end = MathHelper.Max(_selectionIndexes.Last(), _selectionIndexes.Peek());
// Text = Text.Remove(start, end - start);
// _selectionIndexes.Clear();
//}
}
break;
case Keys.Delete:
if (SelectionStart < Text.Length) // && _selectionIndexes.Count <= 1)
{
Text = Text.Remove(SelectionStart, 1);
}
//else if (_selectionIndexes.Count > 1)
//{
// var start = MathHelper.Min(_selectionIndexes.Last(), _selectionIndexes.Peek());
// var end = MathHelper.Max(_selectionIndexes.Last(), _selectionIndexes.Peek());
// Text = Text.Remove(start, end - start);
// SelectionStart = 0; // yeah, nah.
// _selectionIndexes.Clear();
//}
break;
case Keys.Left:
if (SelectionStart > 0)
{
//if (_selectionIndexes.Count > 1)
//{
// if (_selectionIndexes.Last() < SelectionStart) SelectionStart = _selectionIndexes.Last();
// _selectionIndexes.Clear();
//}
//else
{
SelectionStart--;
}
}
break;
case Keys.Right:
if (SelectionStart < Text.Length)
{
//if (_selectionIndexes.Count > 1)
//{
// if (_selectionIndexes.Last() > SelectionStart) SelectionStart = _selectionIndexes.Last();
// _selectionIndexes.Clear();
//}
//else
{
SelectionStart++;
}
}
break;
case Keys.Home:
SelectionStart = 0;
//_selectionIndexes.Clear();
break;
case Keys.End:
SelectionStart = Text.Length;
//_selectionIndexes.Clear();
break;
default:
if (args.Character != null)
{
//if (_selectionIndexes.Count > 1)
//{
// var start = MathHelper.Min(_selectionIndexes.Last(), _selectionIndexes.Peek());
// var end = MathHelper.Max(_selectionIndexes.Last(), _selectionIndexes.Peek());
// Text = Text.Remove(start, end - start);
// _selectionIndexes.Clear();
//}
Text = Text.Insert(SelectionStart, args.Character.ToString());
SelectionStart++;
}
break;
}
_isCaretVisible = true;
return base.OnKeyPressed(context, args);
}
private const float _caretBlinkRate = 0.53f;
private float _nextCaretBlink = _caretBlinkRate;
private bool _isCaretVisible = true;
//private bool _startSelectionBox = false;
//private Stack<int> _selectionIndexes = new Stack<int>();
public override void Draw(IGuiContext context, IGuiRenderer renderer, float deltaSeconds)
{
base.Draw(context, renderer, deltaSeconds);
var text = PasswordCharacter.HasValue ? new string(PasswordCharacter.Value, Text.Length) : Text;
var textInfo = GetTextInfo(context, text, ContentRectangle, HorizontalTextAlignment, VerticalTextAlignment);
if (!string.IsNullOrWhiteSpace(textInfo.Text))
renderer.DrawText(textInfo.Font, textInfo.Text, textInfo.Position + TextOffset, textInfo.Color,
textInfo.ClippingRectangle);
if (IsFocused)
{
var caretRectangle = GetCaretRectangle(textInfo, SelectionStart);
if (_isCaretVisible)
renderer.DrawRectangle(caretRectangle, TextColor);
_nextCaretBlink -= deltaSeconds;
if (_nextCaretBlink <= 0)
{
_isCaretVisible = !_isCaretVisible;
_nextCaretBlink = _caretBlinkRate;
}
//if (_selectionIndexes.Count > 1)
//{
// var start = 0;
// var end = 0;
// var point = Point2.Zero;
// if (_selectionIndexes.Last() > _selectionIndexes.Peek())
// {
// start = _selectionIndexes.Peek();
// end = _selectionIndexes.Last();
// point = caretRectangle.Position;
// }
// else
// {
// start = _selectionIndexes.Last();
// end = _selectionIndexes.Peek();
// point = GetCaretRectangle(textInfo, start).Position;
// }
// var selectionRectangle = textInfo.Font.GetStringRectangle(textInfo.Text.Substring(start, end - start), point);
// renderer.FillRectangle((Rectangle)selectionRectangle, Color.Black * 0.25f);
//}
}
}
//protected override string CreateBoxText(string text, BitmapFont font, float width)
//{
// return text;
//}
private Rectangle GetCaretRectangle(TextInfo textInfo, int index)
{
var caretRectangle = textInfo.Font.GetStringRectangle(textInfo.Text.Substring(0, index), textInfo.Position);
// TODO: Finish the caret position stuff when it's outside the clipping rectangle
if (caretRectangle.Right > ClippingRectangle.Right)
textInfo.Position.X -= caretRectangle.Right - ClippingRectangle.Right;
caretRectangle.X = caretRectangle.Right < ClippingRectangle.Right
? caretRectangle.Right
: ClippingRectangle.Right;
caretRectangle.Width = 1;
if (caretRectangle.Left < ClippingRectangle.Left)
{
textInfo.Position.X += ClippingRectangle.Left - caretRectangle.Left;
caretRectangle.X = ClippingRectangle.Left;
}
return (Rectangle) caretRectangle;
}
}
}
| |
// Borrowed from the Papercut project: papercut.codeplex.com.
using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Net.Mime;
namespace SpecsFor.Mvc.Smtp.Mime
{
/// <summary>
/// This class adds a few internet mail headers not already exposed by the
/// System.Net.MailMessage. It also provides support to encapsulate the
/// nested mail attachments in the Children collection.
/// </summary>
public class MailMessageEx : MailMessage
{
private long _octets;
public long Octets
{
get { return _octets; }
set { _octets = value; }
}
private int _messageNumber;
/// <summary>
/// Gets or sets the message number of the MailMessage on the POP3 server.
/// </summary>
/// <value>The message number.</value>
public int MessageNumber
{
get { return _messageNumber; }
internal set { _messageNumber = value; }
}
private List<MailMessageEx> _children;
/// <summary>
/// Gets the children MailMessage attachments.
/// </summary>
/// <value>The children MailMessage attachments.</value>
public List<MailMessageEx> Children
{
get
{
return _children;
}
}
/// <summary>
/// Gets the delivery date.
/// </summary>
/// <value>The delivery date.</value>
public DateTime DeliveryDate
{
get
{
string date = GetHeader(MailHeaders.Date);
if (string.IsNullOrEmpty(date))
{
return DateTime.MinValue;
}
return Convert.ToDateTime(date);
}
}
/// <summary>
/// Gets the return address.
/// </summary>
/// <value>The return address.</value>
public MailAddress ReturnAddress
{
get
{
string replyTo = GetHeader(MailHeaders.ReplyTo);
if (string.IsNullOrEmpty(replyTo))
{
return null;
}
return CreateMailAddress(replyTo);
}
}
/// <summary>
/// Gets the routing.
/// </summary>
/// <value>The routing.</value>
public string Routing
{
get { return GetHeader(MailHeaders.Received); }
}
/// <summary>
/// Gets the message id.
/// </summary>
/// <value>The message id.</value>
public string MessageId
{
get { return GetHeader(MailHeaders.MessageId); }
}
public string ReplyToMessageId
{
get { return GetHeader(MailHeaders.InReplyTo, true); }
}
/// <summary>
/// Gets the MIME version.
/// </summary>
/// <value>The MIME version.</value>
public string MimeVersion
{
get { return GetHeader(MimeHeaders.MimeVersion); }
}
/// <summary>
/// Gets the content id.
/// </summary>
/// <value>The content id.</value>
public string ContentId
{
get { return GetHeader(MimeHeaders.ContentId); }
}
/// <summary>
/// Gets the content description.
/// </summary>
/// <value>The content description.</value>
public string ContentDescription
{
get { return GetHeader(MimeHeaders.ContentDescription); }
}
/// <summary>
/// Gets the content disposition.
/// </summary>
/// <value>The content disposition.</value>
public ContentDisposition ContentDisposition
{
get
{
string contentDisposition = GetHeader(MimeHeaders.ContentDisposition);
if (string.IsNullOrEmpty(contentDisposition))
{
return null;
}
return new ContentDisposition(contentDisposition);
}
}
/// <summary>
/// Gets the type of the content.
/// </summary>
/// <value>The type of the content.</value>
public ContentType ContentType
{
get
{
string contentType = GetHeader(MimeHeaders.ContentType);
if (string.IsNullOrEmpty(contentType))
{
return null;
}
return MimeReader.GetContentType(contentType);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MailMessageEx"/> class.
/// </summary>
public MailMessageEx()
: base()
{
_children = new List<MailMessageEx>();
}
/// <summary>
/// Gets the header.
/// </summary>
/// <param name="header">The header.</param>
/// <returns></returns>
private string GetHeader(string header)
{
return GetHeader(header, false);
}
private string GetHeader(string header, bool stripBrackets)
{
if (stripBrackets)
{
return MimeEntity.TrimBrackets(Headers[header]);
}
return Headers[header];
}
/// <summary>
/// Creates the mail message from entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns></returns>
public static MailMessageEx CreateMailMessageFromEntity(MimeEntity entity)
{
MailMessageEx message = new MailMessageEx();
string value;
foreach (string key in entity.Headers.AllKeys)
{
value = entity.Headers[key];
if (value.Equals(string.Empty))
{
value = " ";
}
message.Headers.Add(key.ToLowerInvariant(), value);
switch (key.ToLowerInvariant())
{
case MailHeaders.Bcc:
message.Bcc.Add(value);
break;
case MailHeaders.Cc:
message.CC.Add(value);
break;
case MailHeaders.From:
message.From = MailMessageEx.CreateMailAddress(value);
break;
case MailHeaders.ReplyTo:
message.ReplyTo = MailMessageEx.CreateMailAddress(value);
break;
case MailHeaders.Subject:
message.Subject = value;
break;
case MailHeaders.To:
message.To.Add(value);
break;
}
}
return message;
}
/// <summary>
/// Creates the mail address.
/// </summary>
/// <param name="address">The address.</param>
/// <returns></returns>
public static MailAddress CreateMailAddress(string address)
{
try
{
return new MailAddress(address.Trim('\t'));
}
catch (FormatException e)
{
throw new Exception("Unable to create mail address from provided string: " + address, e);
}
}
}
}
| |
using System;
using System.Text;
using System.Collections;
namespace Majestic12
{
/// <summary>
/// Type of parsed HTML chunk (token), each non-null returned chunk from HTMLparser will have oType set to
/// one of these values
/// </summary>
public enum HTMLchunkType
{
/// <summary>
/// Text data from HTML
/// </summary>
Text = 0,
/// <summary>
/// Open tag, possibly with attributes
/// </summary>
OpenTag = 1,
/// <summary>
/// Closed tag (it may still have attributes)
/// </summary>
CloseTag = 2,
/// <summary>
/// Comment tag (<!-- -->)depending on HTMLparser boolean flags you may have:
/// a) nothing to oHTML variable - for faster performance, call SetRawHTML function in parser
/// b) data BETWEEN tags (but not including comment tags themselves) - DEFAULT
/// c) complete RAW HTML representing data between tags and tags themselves (same as you get in a) when
/// you call SetRawHTML function)
///
/// Note: this can also be CDATA part of XML document - see sTag value to determine if its proper comment
/// or CDATA or (in the future) something else
/// </summary>
Comment = 3,
/// <summary>
/// Script tag (<!-- -->) depending on HTMLparser boolean flags
/// a) nothing to oHTML variable - for faster performance, call SetRawHTML function in parser
/// b) data BETWEEN tags (but not including comment tags themselves) - DEFAULT
/// c) complete RAW HTML representing data between tags and tags themselves (same as you get in a) when
/// you call SetRawHTML function)
/// </summary>
Script = 4,
};
/// <summary>
/// Parsed HTML token that is either text, comment, script, open or closed tag as indicated by the oType variable.
/// </summary>
public class HTMLchunk : IDisposable
{
/// <summary>
/// Maximum default capacity of buffer that will keep data
/// </summary>
/// <exclude/>
public static int TEXT_CAPACITY=1024*256;
/// <summary>
/// Maximum number of parameters in a tag - should be high enough to fit most sensible cases
/// </summary>
/// <exclude/>
public static int MAX_PARAMS=256;
/// <summary>
/// Chunk type showing whether its text, open or close tag, comments or script.
/// WARNING: if type is comments or script then you have to manually call Finalise(); method
/// in order to have actual text of comments/scripts in oHTML variable
/// </summary>
public HTMLchunkType oType;
/// <summary>
/// If true then tag params will be kept in a hash rather than in a fixed size arrays.
/// This will be slow down parsing, but make it easier to use.
/// </summary>
public bool bHashMode=true;
/// <summary>
/// For TAGS: it stores raw HTML that was parsed to generate thus chunk will be here UNLESS
/// HTMLparser was configured not to store it there as it can improve performance
/// <p>
/// For TEXT or COMMENTS: actual text or comments - you MUST call Finalise(); first.
/// </p>
/// </summary>
public string oHTML="";
/// <summary>
/// Offset in bHTML data array at which this chunk starts
/// </summary>
public int iChunkOffset=0;
/// <summary>
/// Length of the chunk in bHTML data array
/// </summary>
public int iChunkLength=0;
/// <summary>
/// If its open/close tag type then this is where lowercased Tag will be kept
/// </summary>
public string sTag="";
/// <summary>
/// If true then it must be closed tag
/// </summary>
/// <exclude/>
public bool bClosure=false;
/// <summary>
/// If true then it must be closed tag and closure sign / was at the END of tag, ie this is a SOLO
/// tag
/// </summary>
/// <exclude/>
public bool bEndClosure=false;
/// <summary>
/// If true then it must be comments tag
/// </summary>
/// <exclude/>
public bool bComments=false;
/// <summary>
/// True if entities were present (and transformed) in the original HTML
/// </summary>
/// <exclude/>
public bool bEntities=false;
/// <summary>
/// Set to true if < entity (tag start) was found
/// </summary>
/// <exclude/>
public bool bLtEntity=false;
/// <summary>
/// Hashtable with tag parameters: keys are param names and values are param values.
/// ONLY used if bHashMode is set to TRUE.
/// </summary>
public Hashtable oParams=null;
/// <summary>
/// Number of parameters and values stored in sParams array, OR in oParams hashtable if
/// bHashMode is true
/// </summary>
public int iParams=0;
/// <summary>
/// Param names will be stored here - actual number is in iParams.
/// ONLY used if bHashMode is set to FALSE.
/// </summary>
public string[] sParams=new string[MAX_PARAMS];
/// <summary>
/// Param values will be stored here - actual number is in iParams.
/// ONLY used if bHashMode is set to FALSE.
/// </summary>
public string[] sValues=new string[MAX_PARAMS];
/// <summary>
/// Character used to quote param's value: it is taken actually from parsed HTML
/// </summary>
public byte[] cParamChars=new byte[MAX_PARAMS];
/// <summary>
/// Encoder to be used for conversion of binary data into strings, Encoding.Default is used by default,
/// but it can be changed if top level user of the parser detects that encoding was different
/// </summary>
public Encoding oEnc=Encoding.Default;
bool bDisposed=false;
/// <summary>
/// This function will convert parameters stored in sParams/sValues arrays into oParams hash
/// Useful if generally parsing is done when bHashMode is FALSE. Hash operations are not the fastest, so
/// its best not to use this function.
/// </summary>
public void ConvertParamsToHash()
{
if(oParams!=null)
oParams.Clear();
else
oParams=new Hashtable();
for(int i=0; i<iParams; i++)
{
oParams[sParams[i]]=sValues[i];
}
}
/// <summary>
/// Sets encoding to be used for conversion of binary data into string
/// </summary>
/// <param name="p_oEnc">Encoding object</param>
public void SetEncoding(Encoding p_oEnc)
{
oEnc=p_oEnc;
}
/// <summary>
/// Generates HTML based on current chunk's data
/// Note: this is not a high performance method and if you want ORIGINAL HTML that was parsed to create
/// this chunk then use relevant HTMLparser method to obtain such HTML then you should use
/// function of parser: SetRawHTML
///
/// </summary>
/// <returns>HTML equivalent of this chunk</returns>
public string GenerateHTML()
{
string sHTML="";
switch(oType)
{
// matched open tag, ie <a href="">
case HTMLchunkType.OpenTag:
sHTML+="<"+sTag;
if(iParams>0)
sHTML+=" "+GenerateParamsHTML();
sHTML+=">";
break;
// matched close tag, ie </a>
case HTMLchunkType.CloseTag:
if(iParams>0 || bEndClosure)
{
sHTML+="<"+sTag;
if(iParams>0)
sHTML+=" "+GenerateParamsHTML();
sHTML+="/>";
}
else
sHTML+="</"+sTag+">";
break;
case HTMLchunkType.Script:
if(oHTML.Length==0)
sHTML="<script>n/a</script>";
else
sHTML=oHTML;
break;
case HTMLchunkType.Comment:
// note: we might have CDATA here that we treat as comments
if(sTag=="!--")
{
if(oHTML.Length==0)
sHTML="<!-- n/a -->";
else
sHTML="<!--"+oHTML+"-->";
}
else
{
// ref: http://www.w3schools.com/xml/xml_cdata.asp
if(sTag=="![CDATA[")
{
if(oHTML.Length==0)
sHTML="<![CDATA[ n/a \n]]>";
else
sHTML="<![CDATA["+oHTML+"]]>";
}
}
break;
// matched normal text
case HTMLchunkType.Text:
return oHTML;
};
return sHTML;
}
/// <summary>
/// Returns value of a parameter
/// </summary>
/// <param name="sParam">Parameter</param>
/// <returns>Parameter value or empty string</returns>
public string GetParamValue(string sParam)
{
if(!bHashMode)
{
for(int i=0; i<iParams; i++)
{
if(sParams[i]==sParam)
return sValues[i];
}
}
else
{
object oValue=oParams[sParam];
if(oValue!=null)
return (string)oValue;
}
return "";
}
/// <summary>
/// Generates HTML for params in this chunk
/// </summary>
/// <returns>String with HTML corresponding to params</returns>
public string GenerateParamsHTML()
{
string sParamHTML="";
if(bHashMode)
{
if(oParams.Count>0)
{
foreach(string sParam in oParams.Keys)
{
string sValue=(string)oParams[sParam];
if(sParamHTML.Length>0)
sParamHTML+=" ";
// FIXIT: this is really not correct as we do not use same char used
sParamHTML+=GenerateParamHTML(sParam,sValue,'\'');
}
}
}
else
{
// this is alternative method of getting params -- it may look less convinient
// but it saves a LOT of CPU ticks while parsing. It makes sense when you only need
// params for a few
if(iParams>0)
{
for(int i=0; i<iParams; i++)
{
if(sParamHTML.Length>0)
sParamHTML+=" ";
sParamHTML+=GenerateParamHTML(sParams[i],sValues[i],(char)cParamChars[i]);
}
}
}
return sParamHTML;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool bDisposing)
{
if(!bDisposed)
{
if(oParams!=null)
oParams=null;
sParams=null;
sValues=null;
}
bDisposed=true;
}
/// <summary>
/// Generates HTML for param/value pair
/// </summary>
/// <param name="sParam">Param</param>
/// <param name="sValue">Value (empty if not specified)</param>
/// <returns>String with HTML</returns>
public string GenerateParamHTML(string sParam,string sValue,char cParamChar)
{
if(sValue.Length>0)
{
// check param's value for whitespace or quote chars, if they are not present, then
// we can save 2 bytes by not generating quotes
if(sValue.Length>20)
return sParam+"="+cParamChar+MakeSafeParamValue(sValue,cParamChar)+cParamChar;
for(int i=0; i<sValue.Length; i++)
{
switch(sValue[i])
{
case ' ':
case '\t':
case '\'':
case '\"':
case '\n':
case '\r':
return sParam+"='"+MakeSafeParamValue(sValue,'\'')+"'";
default:
break;
};
}
return sParam+"="+sValue;
}
else
return sParam;
}
/// <summary>
/// Makes parameter value safe to be used in param - this will check for any conflicting quote chars,
/// but not full entity-encoding
/// </summary>
/// <param name="sLine">Line of text</param>
/// <param name="cQuoteChar">Quote char used in param - any such chars in text will be entity-encoded</param>
/// <returns>Safe text to be used as param's value</returns>
public static string MakeSafeParamValue(string sLine,char cQuoteChar)
{
// we speculatievly expect that in most cases we don't actually need to entity-encode string,
for(int i=0; i<sLine.Length; i++)
{
if(sLine[i]==cQuoteChar)
{
// have to restart here
StringBuilder oSB=new StringBuilder(sLine.Length+10);
oSB.Append(sLine.Substring(0,i));
for(int j=i; j<sLine.Length; j++)
{
char cChar=sLine[j];
if(cChar==cQuoteChar)
oSB.Append("&#"+((int)cChar).ToString()+";");
else
oSB.Append(cChar);
}
return oSB.ToString();
}
}
return sLine;
}
/// <summary>
/// Adds tag parameter to the chunk
/// </summary>
/// <param name="sParam">Parameter name (ie color)</param>
/// <param name="sValue">Value of the parameter (ie white)</param>
public void AddParam(string sParam,string sValue,byte cParamChar)
{
if(!bHashMode)
{
if(iParams<MAX_PARAMS)
{
sParams[iParams]=sParam;
sValues[iParams]=sValue;
cParamChars[iParams]=cParamChar;
iParams++;
}
}
else
{
iParams++;
oParams[sParam]=sValue;
}
}
/// <summary>
/// Clears chunk preparing it for
/// </summary>
public void Clear()
{
sTag=oHTML="";
bLtEntity=bEntities=bComments=bClosure=bEndClosure=false;
iParams=0;
if(bHashMode)
{
if(oParams!=null)
oParams.Clear();
}
}
/// <summary>
/// Initialises new HTMLchunk
/// </summary>
/// <param name="p_bHashMode">Sets <seealso cref="bHashMode"/></param>
public HTMLchunk(bool p_bHashMode)
{
bHashMode=p_bHashMode;
if(bHashMode)
oParams=new Hashtable();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BasicTests.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif
namespace Csla.Test.Basic
{
[TestClass]
public class BasicTests
{
[TestMethod]
public void TestNotUndoableField()
{
Csla.ApplicationContext.GlobalContext.Clear();
Csla.Test.DataBinding.ParentEntity p = Csla.Test.DataBinding.ParentEntity.NewParentEntity();
p.NotUndoable = "something";
p.Data = "data";
p.BeginEdit();
p.NotUndoable = "something else";
p.Data = "new data";
p.CancelEdit();
//NotUndoable property points to a private field marked with [NotUndoable()]
//so its state is never copied when BeginEdit() is called
Assert.AreEqual("something else", p.NotUndoable);
//the Data property points to a field that is undoable, so it reverts
Assert.AreEqual("data", p.Data);
}
[TestMethod]
public void TestReadOnlyList()
{
//ReadOnlyList list = ReadOnlyList.GetReadOnlyList();
// Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["ReadOnlyList"]);
}
[TestMethod]
public void TestNameValueList()
{
NameValueListObj nvList = NameValueListObj.GetNameValueListObj();
Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["NameValueListObj"]);
Assert.AreEqual("element_1", nvList[1].Value);
//won't work, because IsReadOnly is set to true after object is populated in the for
//loop in DataPortal_Fetch
//NameValueListObj.NameValuePair newPair = new NameValueListObj.NameValuePair(45, "something");
//nvList.Add(newPair);
//Assert.AreEqual("something", nvList[45].Value);
}
[TestMethod]
public void TestCommandBase()
{
Csla.ApplicationContext.GlobalContext.Clear();
CommandObject obj = new CommandObject();
Assert.AreEqual("Executed", obj.ExecuteServerCode().AProperty);
}
[TestMethod]
public void CreateGenRoot()
{
Csla.ApplicationContext.GlobalContext.Clear();
GenRoot root;
root = GenRoot.NewRoot();
Assert.IsNotNull(root);
Assert.AreEqual("<new>", root.Data);
Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["GenRoot"]);
Assert.AreEqual(true, root.IsNew);
Assert.AreEqual(false, root.IsDeleted);
Assert.AreEqual(true, root.IsDirty);
}
[TestMethod]
public void InheritanceUndo()
{
Csla.ApplicationContext.GlobalContext.Clear();
GenRoot root;
root = GenRoot.NewRoot();
root.BeginEdit();
root.Data = "abc";
root.CancelEdit();
Csla.ApplicationContext.GlobalContext.Clear();
root = GenRoot.NewRoot();
root.BeginEdit();
root.Data = "abc";
root.ApplyEdit();
}
[TestMethod]
public void CreateRoot()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root;
root = Csla.Test.Basic.Root.NewRoot();
Assert.IsNotNull(root);
Assert.AreEqual("<new>", root.Data);
Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["Root"]);
Assert.AreEqual(true, root.IsNew);
Assert.AreEqual(false, root.IsDeleted);
Assert.AreEqual(true, root.IsDirty);
}
[TestMethod]
public void AddChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
Assert.AreEqual(1, root.Children.Count);
Assert.AreEqual("1", root.Children[0].Data);
}
[TestMethod]
public void AddRemoveChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.Children.Remove(root.Children[0]);
Assert.AreEqual(0, root.Children.Count);
}
[TestMethod]
public void AddRemoveAddChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Add("2");
root.CancelEdit();
Assert.AreEqual(1, root.Children.Count);
Assert.AreEqual("1", root.Children[0].Data);
}
[TestMethod]
public void AddGrandChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
Child child = root.Children[0];
child.GrandChildren.Add("1");
Assert.AreEqual(1, child.GrandChildren.Count);
Assert.AreEqual("1", child.GrandChildren[0].Data);
}
[TestMethod]
public void AddRemoveGrandChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
Child child = root.Children[0];
child.GrandChildren.Add("1");
child.GrandChildren.Remove(child.GrandChildren[0]);
Assert.AreEqual(0, child.GrandChildren.Count);
}
[TestMethod]
public void ClearChildList()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("A");
root.Children.Add("B");
root.Children.Add("C");
root.Children.Clear();
Assert.AreEqual(0, root.Children.Count, "Count should be 0");
Assert.AreEqual(3, root.Children.DeletedCount, "Deleted count should be 3");
}
[TestMethod]
public void NestedAddAcceptchild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.BeginEdit();
root.Children.Add("A");
root.BeginEdit();
root.Children.Add("B");
root.BeginEdit();
root.Children.Add("C");
root.ApplyEdit();
root.ApplyEdit();
root.ApplyEdit();
Assert.AreEqual(3, root.Children.Count);
}
[TestMethod]
public void NestedAddDeleteAcceptChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.BeginEdit();
root.Children.Add("A");
root.BeginEdit();
root.Children.Add("B");
root.BeginEdit();
root.Children.Add("C");
Child childC = root.Children[2];
Assert.AreEqual(true, root.Children.Contains(childC), "Child should be in collection");
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
Assert.AreEqual(false, root.Children.Contains(childC), "Child should not be in collection");
Assert.AreEqual(true, root.Children.ContainsDeleted(childC), "Deleted child should be in deleted collection");
root.ApplyEdit();
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after first applyedit");
root.ApplyEdit();
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after ApplyEdit");
root.ApplyEdit();
Assert.AreEqual(0, root.Children.Count, "No children should remain");
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after third applyedit");
}
[TestMethod]
public void BasicEquality()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root r1 = Root.NewRoot();
r1.Data = "abc";
Assert.AreEqual(true, r1.Equals(r1), "objects should be equal on instance compare");
Assert.AreEqual(true, Equals(r1, r1), "objects should be equal on static compare");
Csla.ApplicationContext.GlobalContext.Clear();
Root r2 = Root.NewRoot();
r2.Data = "xyz";
Assert.AreEqual(false, r1.Equals(r2), "objects should not be equal");
Assert.AreEqual(false, Equals(r1, r2), "objects should not be equal");
Assert.AreEqual(false, r1.Equals(null), "Objects should not be equal");
Assert.AreEqual(false, Equals(r1, null), "Objects should not be equal");
Assert.AreEqual(false, Equals(null, r2), "Objects should not be equal");
}
[TestMethod]
public void ChildEquality()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Root.NewRoot();
root.Children.Add("abc");
root.Children.Add("xyz");
root.Children.Add("123");
Child c1 = root.Children[0];
Child c2 = root.Children[1];
Child c3 = root.Children[2];
root.Children.Remove(c3);
Assert.AreEqual(true, c1.Equals(c1), "objects should be equal");
Assert.AreEqual(true, Equals(c1, c1), "objects should be equal");
Assert.AreEqual(false, c1.Equals(c2), "objects should not be equal");
Assert.AreEqual(false, Equals(c1, c2), "objects should not be equal");
Assert.AreEqual(false, c1.Equals(null), "objects should not be equal");
Assert.AreEqual(false, Equals(c1, null), "objects should not be equal");
Assert.AreEqual(false, Equals(null, c2), "objects should not be equal");
Assert.AreEqual(true, root.Children.Contains(c1), "Collection should contain c1");
Assert.AreEqual(true, root.Children.Contains(c2), "collection should contain c2");
Assert.AreEqual(false, root.Children.Contains(c3), "collection should not contain c3");
Assert.AreEqual(true, root.Children.ContainsDeleted(c3), "Deleted collection should contain c3");
}
[TestMethod]
public void DeletedListTest()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.Children.Add("2");
root.Children.Add("3");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
root.ApplyEdit();
Root copy = root.Clone();
var deleted = copy.Children.GetDeletedList();
Assert.AreEqual(2, deleted.Count);
Assert.AreEqual("1", deleted[0].Data);
Assert.AreEqual("2", deleted[1].Data);
Assert.AreEqual(1, root.Children.Count);
}
[TestMethod]
public void DeletedListTestWithCancel()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.Children.Add("2");
root.Children.Add("3");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
Root copy = root.Clone();
var deleted = copy.Children.GetDeletedList();
Assert.AreEqual(2, deleted.Count);
Assert.AreEqual("1", deleted[0].Data);
Assert.AreEqual("2", deleted[1].Data);
Assert.AreEqual(1, root.Children.Count);
root.CancelEdit();
deleted = root.Children.GetDeletedList();
Assert.AreEqual(0, deleted.Count);
Assert.AreEqual(3, root.Children.Count);
}
[TestMethod]
public void SuppressListChangedEventsDoNotRaiseCollectionChanged()
{
bool changed = false;
var obj = new RootList();
obj.ListChanged += (o, e) =>
{
changed = true;
};
var child = new RootListChild(); // object is marked as child
Assert.IsTrue(obj.RaiseListChangedEvents);
using (obj.SuppressListChangedEvents)
{
Assert.IsFalse(obj.RaiseListChangedEvents);
obj.Add(child);
}
Assert.IsFalse(changed, "Should not raise ListChanged event");
Assert.IsTrue(obj.RaiseListChangedEvents);
Assert.AreEqual(child, obj[0]);
}
[TestMethod]
public async Task ChildEditLevelClone()
{
var list = await Csla.DataPortal.CreateAsync<RootList>();
list.BeginEdit();
list.AddNew();
var clone = (RootList)((ICloneable)list).Clone();
clone.ApplyEdit();
}
[TestMethod]
public async Task ChildEditLevelDeleteClone()
{
var list = await Csla.DataPortal.CreateAsync<RootList>();
list.BeginEdit();
list.AddNew();
list.RemoveAt(0);
var clone = (RootList)((ICloneable)list).Clone();
clone.ApplyEdit();
}
[TestMethod]
public async Task UndoStateStack()
{
var obj = await Csla.DataPortal.CreateAsync<Root>(new Root.Criteria(""));
Assert.AreEqual("", obj.Data);
obj.BeginEdit();
obj.Data = "1";
obj.BeginEdit();
obj.Data = "2";
Assert.AreEqual("2", obj.Data);
obj.CancelEdit();
Assert.AreEqual("1", obj.Data);
obj.BeginEdit();
obj.Data = "2";
Assert.AreEqual(2, obj.GetEditLevel());
var clone = obj.Clone();
Assert.AreEqual(2, clone.GetEditLevel());
Assert.AreEqual("2", clone.Data);
clone.CancelEdit();
Assert.AreEqual("1", clone.Data);
clone.CancelEdit();
Assert.AreEqual("", clone.Data);
}
[TestCleanup]
public void ClearContextsAfterEachTest()
{
Csla.ApplicationContext.GlobalContext.Clear();
}
}
public class FormSimulator
{
private readonly Core.BusinessBase _obj;
public FormSimulator(Core.BusinessBase obj)
{
this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Obj_IsDirtyChanged);
this._obj = obj;
}
private void Obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{ }
}
[Serializable()]
public class SerializableListener
{
private readonly Core.BusinessBase _obj;
public SerializableListener(Core.BusinessBase obj)
{
this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Obj_IsDirtyChanged);
this._obj = obj;
}
public void Obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{ }
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudsearch-2013-01-01.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.CloudSearch.Model;
namespace Amazon.CloudSearch
{
/// <summary>
/// Interface for accessing CloudSearch
///
/// Amazon CloudSearch Configuration Service
/// <para>
/// You use the Amazon CloudSearch configuration service to create, configure, and manage
/// search domains. Configuration service requests are submitted using the AWS Query protocol.
/// AWS Query requests are HTTP or HTTPS requests submitted via HTTP GET or POST with
/// a query parameter named Action.
/// </para>
///
/// <para>
/// The endpoint for configuration service requests is region-specific: cloudsearch.<i>region</i>.amazonaws.com.
/// For example, cloudsearch.us-east-1.amazonaws.com. For a current list of supported
/// regions and endpoints, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#cloudsearch_region"
/// target="_blank">Regions and Endpoints</a>.
/// </para>
/// </summary>
public partial interface IAmazonCloudSearch : IDisposable
{
#region BuildSuggesters
/// <summary>
/// Initiates the asynchronous execution of the BuildSuggesters operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the BuildSuggesters operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<BuildSuggestersResponse> BuildSuggestersAsync(BuildSuggestersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateDomain
/// <summary>
/// Initiates the asynchronous execution of the CreateDomain operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateDomain operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateDomainResponse> CreateDomainAsync(CreateDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DefineAnalysisScheme
/// <summary>
/// Initiates the asynchronous execution of the DefineAnalysisScheme operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DefineAnalysisScheme operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DefineAnalysisSchemeResponse> DefineAnalysisSchemeAsync(DefineAnalysisSchemeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DefineExpression
/// <summary>
/// Initiates the asynchronous execution of the DefineExpression operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DefineExpression operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DefineExpressionResponse> DefineExpressionAsync(DefineExpressionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DefineIndexField
/// <summary>
/// Initiates the asynchronous execution of the DefineIndexField operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DefineIndexField operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DefineIndexFieldResponse> DefineIndexFieldAsync(DefineIndexFieldRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DefineSuggester
/// <summary>
/// Initiates the asynchronous execution of the DefineSuggester operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DefineSuggester operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DefineSuggesterResponse> DefineSuggesterAsync(DefineSuggesterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteAnalysisScheme
/// <summary>
/// Initiates the asynchronous execution of the DeleteAnalysisScheme operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteAnalysisScheme operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteAnalysisSchemeResponse> DeleteAnalysisSchemeAsync(DeleteAnalysisSchemeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteDomain
/// <summary>
/// Initiates the asynchronous execution of the DeleteDomain operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteDomain operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteDomainResponse> DeleteDomainAsync(DeleteDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteExpression
/// <summary>
/// Initiates the asynchronous execution of the DeleteExpression operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteExpression operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteExpressionResponse> DeleteExpressionAsync(DeleteExpressionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteIndexField
/// <summary>
/// Initiates the asynchronous execution of the DeleteIndexField operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteIndexField operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteIndexFieldResponse> DeleteIndexFieldAsync(DeleteIndexFieldRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteSuggester
/// <summary>
/// Initiates the asynchronous execution of the DeleteSuggester operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteSuggester operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteSuggesterResponse> DeleteSuggesterAsync(DeleteSuggesterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeAnalysisSchemes
/// <summary>
/// Initiates the asynchronous execution of the DescribeAnalysisSchemes operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeAnalysisSchemes operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeAnalysisSchemesResponse> DescribeAnalysisSchemesAsync(DescribeAnalysisSchemesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeAvailabilityOptions
/// <summary>
/// Initiates the asynchronous execution of the DescribeAvailabilityOptions operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeAvailabilityOptions operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeAvailabilityOptionsResponse> DescribeAvailabilityOptionsAsync(DescribeAvailabilityOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeDomains
/// <summary>
/// Gets information about the search domains owned by this account. Can be limited to
/// specific domains. Shows all domains by default. To get the number of searchable documents
/// in a domain, use the console or submit a <code>matchall</code> request to your domain's
/// search endpoint: <code>q=matchall&amp;q.parser=structured&amp;size=0</code>.
/// For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-domain-info.html"
/// target="_blank">Getting Information about a Search Domain</a> in the <i>Amazon CloudSearch
/// Developer Guide</i>.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeDomains service method, as returned by CloudSearch.</returns>
/// <exception cref="Amazon.CloudSearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
/// <exception cref="Amazon.CloudSearch.Model.InternalException">
/// An internal error occurred while processing the request. If this problem persists,
/// report an issue from the <a href="http://status.aws.amazon.com/" target="_blank">Service
/// Health Dashboard</a>.
/// </exception>
Task<DescribeDomainsResponse> DescribeDomainsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the DescribeDomains operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeDomains operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeDomainsResponse> DescribeDomainsAsync(DescribeDomainsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeExpressions
/// <summary>
/// Initiates the asynchronous execution of the DescribeExpressions operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeExpressions operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeExpressionsResponse> DescribeExpressionsAsync(DescribeExpressionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeIndexFields
/// <summary>
/// Initiates the asynchronous execution of the DescribeIndexFields operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeIndexFields operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeIndexFieldsResponse> DescribeIndexFieldsAsync(DescribeIndexFieldsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeScalingParameters
/// <summary>
/// Initiates the asynchronous execution of the DescribeScalingParameters operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeScalingParameters operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeScalingParametersResponse> DescribeScalingParametersAsync(DescribeScalingParametersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeServiceAccessPolicies
/// <summary>
/// Initiates the asynchronous execution of the DescribeServiceAccessPolicies operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeServiceAccessPolicies operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeServiceAccessPoliciesResponse> DescribeServiceAccessPoliciesAsync(DescribeServiceAccessPoliciesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeSuggesters
/// <summary>
/// Initiates the asynchronous execution of the DescribeSuggesters operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeSuggesters operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeSuggestersResponse> DescribeSuggestersAsync(DescribeSuggestersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region IndexDocuments
/// <summary>
/// Initiates the asynchronous execution of the IndexDocuments operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the IndexDocuments operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<IndexDocumentsResponse> IndexDocumentsAsync(IndexDocumentsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListDomainNames
/// <summary>
/// Lists all search domains owned by an account.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListDomainNames service method, as returned by CloudSearch.</returns>
/// <exception cref="Amazon.CloudSearch.Model.BaseException">
/// An error occurred while processing the request.
/// </exception>
Task<ListDomainNamesResponse> ListDomainNamesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the ListDomainNames operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListDomainNames operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListDomainNamesResponse> ListDomainNamesAsync(ListDomainNamesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdateAvailabilityOptions
/// <summary>
/// Initiates the asynchronous execution of the UpdateAvailabilityOptions operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateAvailabilityOptions operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UpdateAvailabilityOptionsResponse> UpdateAvailabilityOptionsAsync(UpdateAvailabilityOptionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdateScalingParameters
/// <summary>
/// Initiates the asynchronous execution of the UpdateScalingParameters operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateScalingParameters operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UpdateScalingParametersResponse> UpdateScalingParametersAsync(UpdateScalingParametersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdateServiceAccessPolicies
/// <summary>
/// Initiates the asynchronous execution of the UpdateServiceAccessPolicies operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateServiceAccessPolicies operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UpdateServiceAccessPoliciesResponse> UpdateServiceAccessPoliciesAsync(UpdateServiceAccessPoliciesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
}
| |
// Author: ts_matt@hotmail.com
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace ObjectGUI
{
/// <summary>
/// Defines the area for the GUI and the placement of the hidden toggle button
/// Collects all the Monobehaviours defined in the ObjectGUI on this GameObject and draws them
///
/// </summary>
public class ObjectGUIManager : SingletonBehaviour<ObjectGUIManager>
{
/// <summary>
/// Array of objects to be drawn collected on this gameobject
/// </summary>
private ObjectGUI[] objects;
/// <summary>
/// The user can specify hi and low res skins according to the resolution of the device
/// Skins are optional and can be left empty
/// </summary>
public GUISkin LowResSkin, HiResSkin;
/// <summary>
/// Rectangle area of the GUI
/// </summary>
public Rect rectArea = new Rect (0, 0, Screen.width, Screen.height);
/// <summary>
/// Rectangle area of the hidden toggle button
/// </summary>
public Rect hiddenButtonArea = new Rect (0, Screen.height * .9f, Screen.width * .1f, Screen.height * .1f);
/// <summary>
/// Used for indenting while drawing
/// </summary>
private int indent = 0;
private bool lowRes = true;
/// <summary>
/// Dictionary that stores the propertydrawers for all supported types
/// </summary>
private Dictionary<System.Type, IPropertyDrawer> propertyDrawers = new Dictionary<System.Type, IPropertyDrawer> (){
{ typeof(int), new IntPropertyDrawer() },
{ typeof(float), new FloatPropertyDrawer() },
{ typeof(bool), new BoolPropertyDrawer() },
{ typeof(Vector2), new Vector2PropertyDrawer() },
{ typeof(Vector3), new Vector3PropertyDrawer() },
{ typeof(Vector4), new Vector4PropertyDrawer() },
{ typeof(Color), new ColorPropertyDrawer() },
};
/// <summary>
/// Shows the GUI if true
/// </summary>
public bool showGUI = false;
public Rect Area {
get { return rectArea; }
set { rectArea = value; }
}
#region Monobehaviour Methods
void Start ()
{
objects = GetComponents<ObjectGUI> ();
}
void OnGUI ()
{
GUI.skin.button.normal.background = null;
if (GUI.Button (hiddenButtonArea, ""))
showGUI = !showGUI;
if (showGUI)
DrawObjects ();
}
#endregion
#region Drawing methods
/// <summary>
/// Draws all the objects
/// </summary>
void DrawObjects ()
{
// set the skin
if (Screen.width <= 1024)
GUI.skin = LowResSkin;
else
GUI.skin = HiResSkin;
GUILayout.BeginArea (rectArea);
foreach (var obj in objects) {
indent = 0;
DrawObject (obj.targetBehaviour);
}
GUILayout.EndArea ();
}
void DrawObject (MonoBehaviour obj)
{
GUILayout.BeginVertical ();
GUILayout.Space (indent);
GUI.skin.label.fontStyle = FontStyle.Bold;
GUILayout.Label (string.Format ("{0} - {1}", obj.name, obj.GetType ().ToString ()));
GUI.skin.label.fontStyle = FontStyle.Normal;
FieldInfo [] fields = obj.GetType ().GetFields (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (FieldInfo fi in fields) {
GUILayout.BeginHorizontal ();
GUILayout.Space (indent);
if (propertyDrawers.ContainsKey (fi.FieldType))
propertyDrawers [fi.FieldType].Draw (obj, fi);
GUILayout.EndHorizontal ();
} // foreach field
GUILayout.EndVertical ();
}
#endregion
}
public interface IPropertyDrawer
{
void Draw (object obj, FieldInfo fi);
}
public class Vector2PropertyDrawer : IPropertyDrawer
{
public void Draw (object obj, FieldInfo fi)
{
Vector2 retV = (Vector2)fi.GetValue (obj);
GUILayout.Label (fi.Name);
string retX = GUILayout.TextField (retV.x.ToString ());
string retY = GUILayout.TextField (retV.y.ToString ());
if (float.TryParse (retX, out retV.x) && float.TryParse (retY, out retV.y))
fi.SetValue (obj, retV);
}
}
public class Vector3PropertyDrawer : IPropertyDrawer
{
public void Draw (object obj, FieldInfo fi)
{
Vector3 retV = (Vector3)fi.GetValue (obj);
GUILayout.Label (fi.Name);
string retX = GUILayout.TextField (retV.x.ToString ());
string retY = GUILayout.TextField (retV.y.ToString ());
string retZ = GUILayout.TextField (retV.z.ToString ());
if (float.TryParse (retX, out retV.x) && float.TryParse (retY, out retV.y) && float.TryParse (retZ, out retV.z))
fi.SetValue (obj, retV);
}
}
public class Vector4PropertyDrawer : IPropertyDrawer
{
public void Draw (object obj, FieldInfo fi)
{
Vector4 retV = (Vector4)fi.GetValue (obj);
GUILayout.Label (fi.Name);
string retX = GUILayout.TextField (retV.x.ToString ());
string retY = GUILayout.TextField (retV.y.ToString ());
string retZ = GUILayout.TextField (retV.z.ToString ());
string retW = GUILayout.TextField (retV.w.ToString ());
if (float.TryParse (retX, out retV.x) && float.TryParse (retY, out retV.y) && float.TryParse (retZ, out retV.z) && float.TryParse (retW, out retV.w))
fi.SetValue (obj, retV);
}
}
public class ColorPropertyDrawer : IPropertyDrawer
{
public void Draw (object obj, FieldInfo fi)
{
Color retV = (Color)fi.GetValue (obj);
GUILayout.Label (fi.Name);
string retR = GUILayout.TextField (retV.r.ToString ());
string retG = GUILayout.TextField (retV.g.ToString ());
string retB = GUILayout.TextField (retV.b.ToString ());
string retA = GUILayout.TextField (retV.a.ToString ());
if (float.TryParse (retR, out retV.r) && float.TryParse (retG, out retV.g) && float.TryParse (retB, out retV.b) && float.TryParse (retA, out retV.a))
fi.SetValue (obj, retV);
}
}
public class StringPropertyDrawer : IPropertyDrawer
{
public void Draw (object obj, FieldInfo fi)
{
GUILayout.Label (fi.Name);
string ret = GUILayout.TextField (fi.GetValue (obj).ToString ());
fi.SetValue (obj, ret);
}
}
public class BoolPropertyDrawer : IPropertyDrawer
{
public void Draw (object obj, FieldInfo fi)
{
bool ret = GUILayout.Toggle ((bool)fi.GetValue (obj), fi.Name);
fi.SetValue (obj, ret);
}
}
public class IntPropertyDrawer : IPropertyDrawer
{
public void Draw (object obj, FieldInfo fi)
{
GUILayout.Label (fi.Name);
GUILayout.Label (fi.GetValue (obj).ToString ());
int intVal;
var ranges = fi.GetCustomAttributes (typeof(RangeAttribute), false);
if (ranges.Length > 0) {
RangeAttribute r = ranges [0] as RangeAttribute;
intVal = (int)GUILayout.HorizontalSlider ((int)fi.GetValue (obj), (int)r.min, (int)r.max);
} else {
int.TryParse (GUILayout.TextField (fi.GetValue (obj).ToString ()), out intVal);
}
fi.SetValue (obj, intVal);
}
}
public class FloatPropertyDrawer : IPropertyDrawer
{
public void Draw (object obj, FieldInfo fi)
{
GUILayout.Label (fi.Name);
GUILayout.Label (fi.GetValue (obj).ToString ());
float fVal;
var ranges = fi.GetCustomAttributes (typeof(RangeAttribute), false);
if (ranges.Length > 0) {
RangeAttribute r = ranges [0] as RangeAttribute;
fVal = GUILayout.HorizontalSlider ((float)fi.GetValue (obj), r.min, r.max);
fi.SetValue (obj, fVal);
} else {
if (float.TryParse (GUILayout.TextField (fi.GetValue (obj).ToString ()), out fVal))
fi.SetValue (obj, fVal);
}
}
}
}
| |
using sys = System.IO;
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using WixSharp.CommonTasks;
using System.Text;
namespace WixSharp.Bootstrapper
{
//Useful stuff to have a look at:
//http://neilsleightholm.blogspot.com.au/2012/05/wix-burn-tipstricks.html
//https://wixwpf.codeplex.com/
/// <summary>
/// Class for defining a WiX standard Burn-based bootstrapper. By default the bootstrapper is using WiX default WiX bootstrapper UI.
/// </summary>
/// <example>The following is an example of defining a bootstrapper for two msi files and .NET Web setup.
/// <code>
/// var bootstrapper =
/// new Bundle("My Product",
/// new PackageGroupRef("NetFx40Web"),
/// new MsiPackage("productA.msi"),
/// new MsiPackage("productB.msi"));
///
/// bootstrapper.AboutUrl = "https://wixsharp.codeplex.com/";
/// bootstrapper.IconFile = "app_icon.ico";
/// bootstrapper.Version = new Version("1.0.0.0");
/// bootstrapper.UpgradeCode = new Guid("6f330b47-2577-43ad-9095-1861bb25889b");
/// bootstrapper.Application.LogoFile = "logo.png";
///
/// bootstrapper.Build();
/// </code>
/// </example>
public partial class Bundle : WixProject
{
/// <summary>
/// Initializes a new instance of the <see cref="Bootstrapper"/> class.
/// </summary>
public Bundle()
{
WixExtensions.Add("WiXNetFxExtension");
WixExtensions.Add("WiXBalExtension");
}
/// <summary>
/// Initializes a new instance of the <see cref="Bootstrapper" /> class.
/// </summary>
/// <param name="name">The name of the project. Typically it is the name of the product to be installed.</param>
/// <param name="items">The project installable items (e.g. directories, files, registry keys, Custom Actions).</param>
public Bundle(string name, params ChainItem[] items)
{
WixExtensions.Add("WiXNetFxExtension");
WixExtensions.Add("WiXBalExtension");
Name = name;
Chain.AddRange(items);
}
/// <summary>
/// The disable rollbackSpecifies whether the bundle will attempt to rollback packages executed in the chain.
/// If "true" is specified then when a vital package fails to install only that package will rollback and the chain will stop with the error.
/// The default is "false" which indicates all packages executed during the chain will be rolldback to their previous state when a vital package fails.
/// </summary>
public bool? DisableRollback;
/// <summary>
/// Specifies whether the bundle will attempt to create a system restore point when executing the chain. If "true" is specified then a system restore
/// point will not be created. The default is "false" which indicates a system restore point will be created when the bundle is installed, uninstalled,
/// repaired, modified, etc. If the system restore point cannot be created, the bundle will log the issue and continue.
/// </summary>
public bool? DisableSystemRestore;
/// <summary>
/// Specifies whether the bundle will start installing packages while other packages are still being cached.
/// If "true", packages will start executing when a rollback boundary is encountered. The default is "false"
/// which dictates all packages must be cached before any packages will start to be installed.
/// </summary>
public bool? ParallelCache;
/// <summary>
/// The legal copyright found in the version resources of final bundle executable.
/// If this attribute is not provided the copyright will be set to "Copyright (c) [Bundle/@Manufacturer]. All rights reserved.".
/// </summary>
[Xml]
public string Copyright;
/// <summary>
/// A URL for more information about the bundle to display in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml]
public string AboutUrl;
/// <summary>
/// Whether Packages and Payloads not assigned to a container should be added to the default attached container or if they
/// should be external. The default is yes.
/// </summary>
[Xml]
public bool? Compressed;
/// <summary>
/// The condition of the bundle. If the condition is not met, the bundle will refuse to run. Conditions are checked before the
/// bootstrapper application is loaded (before detect), and thus can only reference built-in variables such as variables which
/// indicate the version of the OS.
/// </summary>
[Xml]
public string Condition;
/// <summary>
/// Determines whether the bundle can be removed via the Programs and Features (also known as Add/Remove Programs). If the value is
/// "yes" then the "Uninstall" button will not be displayed. The default is "no" which ensures there is an "Uninstall" button to remove
/// the bundle. If the "DisableModify" attribute is also "yes" or "button" then the bundle will not be displayed in Progams and
/// Features and another mechanism (such as registering as a related bundle addon) must be used to ensure the bundle can be removed.
/// </summary>
[Xml]
public bool? DisableRemove;
/// <summary>
/// Determines whether the bundle can be modified via the Programs and Features (also known as Add/Remove Programs). If the value is
/// "button" then Programs and Features will show a single "Uninstall/Change" button. If the value is "yes" then Programs and Features
/// will only show the "Uninstall" button". If the value is "no", the default, then a "Change" button is shown. See the DisableRemove
/// attribute for information how to not display the bundle in Programs and Features.
/// </summary>
[Xml]
public string DisableModify;
/// <summary>
/// A telephone number for help to display in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml]
public string HelpTelephone;
/// <summary>
/// A URL to the help for the bundle to display in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml]
public string HelpUrl;
/// <summary>
/// Path to an icon that will replace the default icon in the final Bundle executable. This icon will also be displayed in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml(Name = "IconSourceFile")]
public string IconFile;
/// <summary>
/// The publisher of the bundle to display in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml]
public string Manufacturer;
/// <summary>
/// The name of the parent bundle to display in Installed Updates (also known as Add/Remove Programs). This name is used to nest or group bundles that will appear as updates. If the
/// parent name does not actually exist, a virtual parent is created automatically.
/// </summary>
[Xml]
public string ParentName;
/// <summary>
/// Path to a bitmap that will be shown as the bootstrapper application is being loaded. If this attribute is not specified, no splash screen will be displayed.
/// </summary>
[Xml(Name = "SplashScreenSourceFile")]
public string SplashScreenSource;
/// <summary>
/// Set this string to uniquely identify this bundle to its own BA, and to related bundles. The value of this string only matters to the BA, and its value has no direct
/// effect on engine functionality.
/// </summary>
[Xml]
public string Tag;
/// <summary>
/// A URL for updates of the bundle to display in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml]
public string UpdateUrl;
/// <summary>
/// Unique identifier for a family of bundles. If two bundles have the same UpgradeCode the bundle with the highest version will be installed.
/// </summary>
[Xml]
public Guid UpgradeCode = Guid.NewGuid();
/// <summary>
/// The suppress auto insertion of WixMbaPrereq* variables in the bundle definition (WixMbaPrereqPackageId and WixMbaPrereqLicenseUrl).
/// <para>BA is relying on two internal variables that reflect .NET version (and licence) that BA requires at runtime. If user defines
/// custom Wix# based BA the required variables are inserted automatically, similarly to the standards WiX/Burn BA. However some other
/// bundle packages (e.g. new PackageGroupRef("NetFx40Web")) may also define these variables so some duplication/collision is possible.
/// To avoid this you can suppress variables auto-insertion and define them manually as needed.</para>
///<example>The following is an example of suppressing auto-insertion:
/// <code>
/// var bootstrapper = new Bundle("My Product Suite",
/// new PackageGroupRef("NetFx40Web"),
/// new MsiPackage(productMsi)
/// {
/// Id = "MyProductPackageId",
/// DisplayInternalUI = true
/// });
///
/// bootstrapper.SuppressWixMbaPrereqVars = true;
/// </code>
/// </example>
/// </summary>
public bool SuppressWixMbaPrereqVars = false;
/// <summary>
/// The version of the bundle. Newer versions upgrade earlier versions of the bundles with matching UpgradeCodes. If the bundle is registered in Programs and Features then this attribute will be displayed in the Programs and Features user interface.
/// </summary>
[Xml]
public Version Version;
/// <summary>
/// The sequence of the packages to be installed
/// </summary>
public List<ChainItem> Chain = new List<ChainItem>();
/// <summary>
/// The instance of the Bootstrapper application class application. By default it is a LicenseBootstrapperApplication object.
/// </summary>
public WixStandardBootstrapperApplication Application = new LicenseBootstrapperApplication();
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public XContainer[] ToXml()
{
var result = new List<XContainer>();
var root = new XElement("Bundle",
new XAttribute("Name", Name));
root.AddAttributes(this.Attributes);
root.Add(this.MapToXmlAttributes());
if (Application is ManagedBootstrapperApplication)
{
var app = Application as ManagedBootstrapperApplication;
if (app.PrimaryPackageId == null)
{
var lastPackage = Chain.OfType<WixSharp.Bootstrapper.Package>().LastOrDefault();
if (lastPackage != null)
{
lastPackage.EnsureId();
app.PrimaryPackageId = lastPackage.Id;
}
}
//addresses https://wixsharp.codeplex.com/workitem/149
if (!SuppressWixMbaPrereqVars)
{
WixVariables["WixMbaPrereqPackageId"] = "Netfx4Full";
WixVariables.Add("WixMbaPrereqLicenseUrl", "NetfxLicense.rtf");
}
}
//important to call AutoGenerateSources after PrimaryPackageId is set
Application.AutoGenerateSources(this.OutDir);
root.Add(Application.ToXml());
string variabes = this.StringVariablesDefinition + ";" + Application.StringVariablesDefinition;
Compiler.ProcessWixVariables(this, root);
foreach (var entry in variabes.ToDictionary())
{
root.AddElement("Variable", "Name=" + entry.Key + ";Value=" + entry.Value + ";Persisted=yes;Type=string");
}
var xChain = root.AddElement("Chain");
foreach (var item in this.Chain)
xChain.Add(item.ToXml());
xChain.SetAttribute("DisableRollback", DisableRollback);
xChain.SetAttribute("DisableSystemRestore", DisableSystemRestore);
xChain.SetAttribute("ParallelCache", ParallelCache);
result.Add(root);
return result.ToArray();
}
/// <summary>
/// The Bundle string variables.
/// </summary>
/// <para>The variables are defined as a named values map.</para>
/// <para>If you need to access the variable value from the Package
/// you will need to add the MsiProperty mapped to this variable.
/// </para>
/// <example>
/// <code>
/// new ManagedBootstrapperApplication("ManagedBA.dll")
/// {
/// StringVariablesDefinition = "FullInstall=Yes; Silent=No"
/// }
/// ...
/// new MsiPackage(msiFile) { MsiProperties = "FULL=[FullInstall]" },
/// </code>
/// </example>
public string StringVariablesDefinition = "";
/// <summary>
/// Builds WiX Bootstrapper application from the specified <see cref="Bundle" /> project instance.
/// </summary>
/// <param name="path">The path to the bootstrapper to be build.</param>
/// <returns></returns>
public string Build(string path = null)
{
var output = new StringBuilder();
Action<string> collect = line => output.AppendLine(line);
Compiler.OutputWriteLine += collect;
try
{
if (Compiler.ClientAssembly.IsEmpty())
Compiler.ClientAssembly = System.Reflection.Assembly.GetCallingAssembly().GetLocation();
if (path == null)
return Compiler.Build(this);
else
return Compiler.Build(this, path);
}
finally
{
ValidateCompileOutput(output.ToString());
Compiler.OutputWriteLine -= collect;
}
}
void ValidateCompileOutput(string output)
{
if (!this.SuppressWixMbaPrereqVars && output.Contains("'WixMbaPrereqPackageId' is declared in more than one location."))
{
Compiler.OutputWriteLine("======================================================");
Compiler.OutputWriteLine("");
Compiler.OutputWriteLine("WARNING: It looks like one of the packages defines "+
"WixMbaPrereqPackageId/WixMbaPrereqLicenseUrl in addition to the definition "+
"auto-inserted by Wix# managed BA. If it is the case set your Bundle project "+
"SuppressWixMbaPrereqVars to 'true' to fix the problem.");
Compiler.OutputWriteLine("");
Compiler.OutputWriteLine("======================================================");
}
else if (this.SuppressWixMbaPrereqVars && output.Contains("The Windows Installer XML variable !(wix.WixMbaPrereqPackageId) is unknown."))
{
Compiler.OutputWriteLine("======================================================");
Compiler.OutputWriteLine("");
Compiler.OutputWriteLine("WARNING: It looks like generation of WixMbaPrereqPackageId/WixMbaPrereqLicenseUrl "+
"was suppressed while none of other packages defines it. "+
"If it is the case set your Bundle project SuppressWixMbaPrereqVars to false to fix the problem.");
Compiler.OutputWriteLine("");
Compiler.OutputWriteLine("======================================================");
}
}
/// <summary>
/// Builds the WiX source file and generates batch file capable of building
/// WiX/MSI bootstrapper with WiX toolset.
/// </summary>
/// <param name="path">The path to the batch file to be created.</param>
/// <returns></returns>
public string BuildCmd(string path = null)
{
if (Compiler.ClientAssembly.IsEmpty())
Compiler.ClientAssembly = System.Reflection.Assembly.GetCallingAssembly().GetLocation();
if (path == null)
return Compiler.BuildCmd(this);
else
return Compiler.BuildCmd(this, path);
}
/// <summary>
/// Validates this Bundle project packages.
/// </summary>
public void Validate()
{
var msiPackages = this.Chain.Where(x => (x is MsiPackage) && (x as MsiPackage).DisplayInternalUI == true);
foreach (MsiPackage item in msiPackages)
{
try
{
if (Tasks.IsEmbeddedUIPackage(item.SourceFile))
{
Compiler.OutputWriteLine("");
Compiler.OutputWriteLine("WARNING: You have selected enabled DisplayInternalUI for EmbeddedUI-based '"
+ sys.Path.GetFileName(item.SourceFile) + "'. Currently Burn (WiX) " +
"doesn't support integration with EmbeddedUI packages. Read more here: https://wixsharp.codeplex.com/discussions/645838");
Compiler.OutputWriteLine("");
}
}
catch { }
}
}
}
/*
<Bundle Name="My Product"
Version="1.0.0.0"
Manufacturer="OSH"
AboutUrl="https://wixsharp.codeplex.com/"
IconSourceFile="app_icon.ico"
UpgradeCode="acaa3540-97e0-44e4-ae7a-28c20d410a60">
<BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense">
<bal:WixStandardBootstrapperApplication LicenseFile="readme.txt" LocalizationFile="" LogoFile="app_icon.ico" />
</BootstrapperApplicationRef>
<Chain>
<!-- Install .Net 4 Full -->
<PackageGroupRef Id="NetFx40Web"/>
<!--<ExePackage
Id="Netfx4FullExe"
Cache="no"
Compressed="no"
PerMachine="yes"
Permanent="yes"
Vital="yes"
SourceFile="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\DotNetFX40\dotNetFx40_Full_x86_x64.exe"
InstallCommand="/q /norestart /ChainingPackage FullX64Bootstrapper"
DetectCondition="NETFRAMEWORK35='#1'"
DownloadUrl="http://go.microsoft.com/fwlink/?LinkId=164193" />-->
<RollbackBoundary />
<MsiPackage SourceFile="E:\Galos\Projects\WixSharp\src\WixSharp.Samples\Wix# Samples\Managed Setup\ManagedSetup.msi" Vital="yes" />
</Chain>
</Bundle>
*/
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Design;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms.VisualStyles;
namespace CloudBox.Controller
{
[Designer(typeof(TreeListViewDesigner))]
public class TreeListView : Control, ISupportInitialize
{
public event TreeViewEventHandler AfterSelect;
protected virtual void OnAfterSelect(Node node)
{
raiseAfterSelect(node);
}
protected virtual void raiseAfterSelect(Node node)
{
if (AfterSelect != null)
AfterSelect(this, new TreeViewEventArgs(null));
}
public delegate void NotifyBeforeExpandHandler(Node node, bool isExpanding);
public event NotifyBeforeExpandHandler NotifyBeforeExpand;
public virtual void OnNotifyBeforeExpand(Node node, bool isExpanding)
{
raiseNotifyBeforeExpand(node, isExpanding);
}
protected virtual void raiseNotifyBeforeExpand(Node node, bool isExpanding)
{
if (NotifyBeforeExpand != null)
NotifyBeforeExpand(node, isExpanding);
}
public delegate void NotifyAfterHandler(Node node, bool isExpanding);
public event NotifyAfterHandler NotifyAfterExpand;
public virtual void OnNotifyAfterExpand(Node node, bool isExpanded)
{
raiseNotifyAfterExpand(node, isExpanded);
}
protected virtual void raiseNotifyAfterExpand(Node node, bool isExpanded)
{
if (NotifyAfterExpand != null)
NotifyAfterExpand(node, isExpanded);
}
TreeListViewNodes m_nodes;
TreeListColumnCollection m_columns;
TreeList.RowSetting m_rowSetting;
TreeList.ViewSetting m_viewSetting;
[Category("Columns")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TreeListColumnCollection Columns
{
get { return m_columns; }
}
[Category("Options")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TreeList.CollumnSetting ColumnsOptions
{
get { return m_columns.Options; }
}
[Category("Options")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TreeList.RowSetting RowOptions
{
get { return m_rowSetting; }
}
[Category("Options")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TreeList.ViewSetting ViewOptions
{
get { return m_viewSetting; }
}
[Category("Behavior")]
[DefaultValue(typeof(bool), "True")]
public bool MultiSelect
{
get { return m_multiSelect; }
set { m_multiSelect = value; }
}
[DefaultValue(typeof(Color), "Window")]
public new Color BackColor
{
get { return base.BackColor; }
set { base.BackColor = value; }
}
public ImageList Images
{
get { return m_images; }
set { m_images = value; }
}
//[Browsable(false)]
public TreeListViewNodes Nodes
{
get { return m_nodes; }
}
public TreeListView()
{
this.DoubleBuffered = true;
this.BackColor = SystemColors.Window;
this.TabStop = true;
m_rowPainter = new RowPainter();
m_cellPainter = new CellPainter(this);
m_nodes = new TreeListViewNodes(this);
m_columns = new TreeListColumnCollection(this);
m_rowSetting = new TreeList.RowSetting(this);
m_viewSetting = new TreeList.ViewSetting(this);
AddScroolBars();
}
public void RecalcLayout()
{
if (m_firstVisibleNode == null)
m_firstVisibleNode = Nodes.FirstNode;
if (Nodes.Count == 0)
m_firstVisibleNode = null;
UpdateScrollBars();
int vscroll = VScrollValue();
if (vscroll == 0)
m_firstVisibleNode = Nodes.FirstNode;
else
m_firstVisibleNode = NodeCollection.GetNextNode(Nodes.FirstNode, vscroll);
Invalidate();
}
void AddScroolBars()
{
// I was not able to get the wanted behavior by using ScrollableControl with AutoScroll enabled.
// horizontal scrolling is ok to do it by pixels, but for vertical I want to maintain the headers
// and only scroll the rows.
// I was not able to manually overwrite the vscroll bar handling to get this behavior, instead I opted for
// custom implementation of scrollbars
// to get the 'filler' between hscroll and vscroll I dock scroll + filler in a panel
m_hScroll = new HScrollBar();
m_hScroll.Scroll += new ScrollEventHandler(OnHScroll);
m_hScroll.Dock = DockStyle.Fill;
m_vScroll = new VScrollBar();
m_vScroll.Scroll += new ScrollEventHandler(OnVScroll);
m_vScroll.Dock = DockStyle.Right;
m_hScrollFiller = new Panel();
m_hScrollFiller.BackColor = Color.Transparent;
m_hScrollFiller.Size = new Size(m_vScroll.Width-1, m_hScroll.Height);
m_hScrollFiller.Dock = DockStyle.Right;
Controls.Add(m_vScroll);
m_hScrollPanel = new Panel();
m_hScrollPanel.Height = m_hScroll.Height;
m_hScrollPanel.Dock = DockStyle.Bottom;
m_hScrollPanel.Controls.Add(m_hScroll);
m_hScrollPanel.Controls.Add(m_hScrollFiller);
Controls.Add(m_hScrollPanel);
}
VScrollBar m_vScroll;
HScrollBar m_hScroll;
Panel m_hScrollFiller;
Panel m_hScrollPanel;
bool m_multiSelect = true;
Node m_firstVisibleNode = null;
ImageList m_images = null;
RowPainter m_rowPainter;
CellPainter m_cellPainter;
[Browsable(false)]
public CellPainter CellPainter
{
get { return m_cellPainter; }
set { m_cellPainter = value; }
}
TreeListColumn m_resizingColumn;
int m_resizingColumnScrollOffset;
NodesSelection m_nodesSelection = new NodesSelection();
Node m_focusedNode = null;
[Browsable(false)]
public NodesSelection NodesSelection
{
get { return m_nodesSelection; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Node FocusedNode
{
get { return m_focusedNode; }
set
{
Node curNode = FocusedNode;
if (object.ReferenceEquals(curNode, value))
return;
if (MultiSelect == false)
NodesSelection.Clear();
int oldrow = NodeCollection.GetVisibleNodeIndex(curNode);
int newrow = NodeCollection.GetVisibleNodeIndex(value);
m_focusedNode = value;
OnAfterSelect(value);
InvalidateRow(oldrow);
InvalidateRow(newrow);
EnsureVisible(m_focusedNode);
}
}
public void EnsureVisible(Node node)
{
int screenvisible = MaxVisibleRows() - 1;
int visibleIndex = NodeCollection.GetVisibleNodeIndex(node);
if (visibleIndex < VScrollValue())
{
SetVScrollValue(visibleIndex);
}
if (visibleIndex > VScrollValue() + screenvisible)
{
SetVScrollValue(visibleIndex - screenvisible);
}
}
public Node CalcHitNode(Point mousepoint)
{
int hitrow = CalcHitRow(mousepoint);
if (hitrow < 0)
return null;
return NodeCollection.GetNextNode(m_firstVisibleNode, hitrow);
}
public Node GetHitNode()
{
return CalcHitNode(PointToClient(Control.MousePosition));
}
public CloudBox.Controller.HitInfo CalcColumnHit(Point mousepoint)
{
return Columns.CalcHitInfo(mousepoint, HScrollValue());
}
public bool HitTestScrollbar(Point mousepoint)
{
if (m_hScroll.Visible && mousepoint.Y >= ClientRectangle.Height - m_hScroll.Height)
return true;
return false;
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
if (ClientRectangle.Width > 0 && ClientRectangle.Height > 0)
{
Columns.RecalcVisibleColumsRect();
UpdateScrollBars();
}
}
protected virtual void BeforeShowContextMenu()
{
}
protected void InvalidateRow(int absoluteRowIndex)
{
int visibleRowIndex = absoluteRowIndex - VScrollValue();
Rectangle r = CalcRowRecangle(visibleRowIndex);
if (r != Rectangle.Empty)
{
r.Inflate(1,1);
Invalidate(r);
}
}
void OnVScroll(object sender, ScrollEventArgs e)
{
int diff = e.NewValue - e.OldValue;
//assumedScrollPos += diff;
if (e.NewValue == 0)
{
m_firstVisibleNode = Nodes.FirstNode;
diff = 0;
}
m_firstVisibleNode = NodeCollection.GetNextNode(m_firstVisibleNode, diff);
Invalidate();
}
void OnHScroll(object sender, ScrollEventArgs e)
{
Invalidate();
}
void SetVScrollValue(int value)
{
if (value < 0)
value = 0;
int max = m_vScroll.Maximum - m_vScroll.LargeChange + 1;
if (value > max)
value = max;
if ((value >= 0 && value <= max) && (value != m_vScroll.Value))
{
ScrollEventArgs e = new ScrollEventArgs(ScrollEventType.ThumbPosition, m_vScroll.Value, value, ScrollOrientation.VerticalScroll);
// setting the scroll value does not cause a Scroll event
m_vScroll.Value = value;
// so we have to fake it
OnVScroll(m_vScroll, e);
}
}
int VScrollValue()
{
if (m_vScroll.Visible == false)
return 0;
return m_vScroll.Value;
}
int HScrollValue()
{
if (m_hScroll.Visible == false)
return 0;
return m_hScroll.Value;
}
void UpdateScrollBars()
{
if (ClientRectangle.Width < 0)
return;
int maxvisiblerows = MaxVisibleRows();
int totalrows = Nodes.VisibleNodeCount;
if (maxvisiblerows > totalrows)
{
m_vScroll.Visible = false;
SetVScrollValue(0);
}
else
{
m_vScroll.Visible = true;
m_vScroll.SmallChange = 1;
m_vScroll.LargeChange = maxvisiblerows;
m_vScroll.Minimum = 0;
m_vScroll.Maximum = totalrows-1;
int maxscrollvalue = m_vScroll.Maximum - m_vScroll.LargeChange;
if (maxscrollvalue < m_vScroll.Value)
SetVScrollValue(maxscrollvalue);
}
if (ClientRectangle.Width > MinWidth())
{
m_hScrollPanel.Visible = false;
m_hScroll.Value = 0;
}
else
{
m_hScroll.Minimum = 0;
m_hScroll.Maximum = MinWidth();
m_hScroll.SmallChange = 5;
m_hScroll.LargeChange = ClientRectangle.Width;
m_hScrollFiller.Visible = m_vScroll.Visible;
m_hScrollPanel.Visible = true;
}
}
int m_hotrow = -1;
int CalcHitRow(Point mousepoint)
{
if (mousepoint.Y <= Columns.Options.HeaderHeight)
return -1;
return (mousepoint.Y - Columns.Options.HeaderHeight) / RowOptions.ItemHeight;
}
int VisibleRowToYPoint(int visibleRowIndex)
{
return Columns.Options.HeaderHeight + (visibleRowIndex * RowOptions.ItemHeight);
}
Rectangle CalcRowRecangle(int visibleRowIndex)
{
Rectangle r = ClientRectangle;
r.Y = VisibleRowToYPoint(visibleRowIndex);
if (r.Top < Columns.Options.HeaderHeight || r.Top > ClientRectangle.Height)
return Rectangle.Empty;
r.Height = RowOptions.ItemHeight;
return r;
}
void MultiSelectAdd(Node clickedNode, Keys modifierKeys)
{
if (Control.ModifierKeys == Keys.None)
{
foreach (Node node in NodesSelection)
{
int newrow = NodeCollection.GetVisibleNodeIndex(node);
InvalidateRow(newrow);
}
NodesSelection.Clear();
NodesSelection.Add(clickedNode);
}
if (Control.ModifierKeys == Keys.Shift)
{
if (NodesSelection.Count == 0)
NodesSelection.Add(clickedNode);
else
{
int startrow = NodeCollection.GetVisibleNodeIndex(NodesSelection[0]);
int currow = NodeCollection.GetVisibleNodeIndex(clickedNode);
if (currow > startrow)
{
Node startingNode = NodesSelection[0];
NodesSelection.Clear();
foreach (Node node in NodeCollection.ForwardNodeIterator(startingNode, clickedNode, true))
NodesSelection.Add(node);
Invalidate();
}
if (currow < startrow)
{
Node startingNode = NodesSelection[0];
NodesSelection.Clear();
foreach (Node node in NodeCollection.ReverseNodeIterator(startingNode, clickedNode, true))
NodesSelection.Add(node);
Invalidate();
}
}
}
if (Control.ModifierKeys == Keys.Control)
{
if (NodesSelection.Contains(clickedNode))
NodesSelection.Remove(clickedNode);
else
NodesSelection.Add(clickedNode);
}
InvalidateRow(NodeCollection.GetVisibleNodeIndex(clickedNode));
FocusedNode = clickedNode;
}
internal event MouseEventHandler AfterResizingColumn;
protected override void OnMouseClick(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point mousePoint = new Point(e.X, e.Y);
Node clickedNode = CalcHitNode(mousePoint);
if (clickedNode != null && Columns.Count > 0)
{
int clickedRow = CalcHitRow(mousePoint);
Rectangle glyphRect = GetPlusMinusRectangle(clickedNode, Columns.VisibleColumns[0], clickedRow);
if (clickedNode.HasChildren && glyphRect != Rectangle.Empty && glyphRect.Contains(mousePoint))
clickedNode.Expanded = !clickedNode.Expanded;
if (MultiSelect)
{
MultiSelectAdd(clickedNode, Control.ModifierKeys);
}
else
FocusedNode = clickedNode;
}
}
base.OnMouseClick(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (m_resizingColumn != null)
{
int left = m_resizingColumn.CalculatedRect.Left - m_resizingColumnScrollOffset;
int width = e.X - left;
if (width < 10)
width = 10;
m_resizingColumn.Width = width;
Columns.RecalcVisibleColumsRect(true);
Invalidate();
return;
}
TreeListColumn hotcol = null;
CloudBox.Controller.HitInfo info = Columns.CalcHitInfo(new Point(e.X, e.Y), HScrollValue());
if ((int)(info.HitType & HitInfo.eHitType.kColumnHeader) > 0)
hotcol = info.Column;
if ((int)(info.HitType & HitInfo.eHitType.kColumnHeaderResize) > 0)
Cursor = Cursors.VSplit;
else
Cursor = Cursors.Arrow;
SetHotColumn(hotcol, true);
int vScrollOffset = VScrollValue();
int newhotrow = -1;
if (hotcol == null)
{
int row = (e.Y - Columns.Options.HeaderHeight) / RowOptions.ItemHeight;
newhotrow = row + vScrollOffset;
}
if (newhotrow != m_hotrow)
{
InvalidateRow(m_hotrow);
m_hotrow = newhotrow;
InvalidateRow(m_hotrow);
}
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
SetHotColumn(null, false);
}
protected override void OnMouseWheel(MouseEventArgs e)
{
int value = m_vScroll.Value - (e.Delta * SystemInformation.MouseWheelScrollLines / 120);
if (m_vScroll.Visible)
SetVScrollValue(value);
base.OnMouseWheel(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
this.Focus();
if (e.Button == MouseButtons.Right)
{
Point mousePoint = new Point(e.X, e.Y);
Node clickedNode = CalcHitNode(mousePoint);
if (clickedNode != null)
{
// if multi select the selection is cleard if clicked node is not in selection
if (MultiSelect)
{
if (NodesSelection.Contains(clickedNode) == false)
MultiSelectAdd(clickedNode, Control.ModifierKeys);
}
FocusedNode = clickedNode;
Invalidate();
}
BeforeShowContextMenu();
}
if (e.Button == MouseButtons.Left)
{
CloudBox.Controller.HitInfo info = Columns.CalcHitInfo(new Point(e.X, e.Y), HScrollValue());
if ((int)(info.HitType & HitInfo.eHitType.kColumnHeaderResize) > 0)
{
m_resizingColumn = info.Column;
m_resizingColumnScrollOffset = HScrollValue();
return;
}
}
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (m_resizingColumn != null)
{
m_resizingColumn = null;
Columns.RecalcVisibleColumsRect();
UpdateScrollBars();
Invalidate();
if (AfterResizingColumn != null)
AfterResizingColumn(this, e);
}
base.OnMouseUp(e);
}
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
base.OnMouseDoubleClick(e);
Point mousePoint = new Point(e.X, e.Y);
Node clickedNode = CalcHitNode(mousePoint);
if (clickedNode != null && clickedNode.HasChildren)
clickedNode.Expanded = !clickedNode.Expanded;
}
// Somewhere I read that it could be risky to do any handling in GetFocus / LostFocus.
// The reason is that it will throw exception incase you make a call which recreates the windows handle (e.g.
// change the border style. Instead one should always use OnEnter and OnLeave instead. That is why I'm using
// OnEnter and OnLeave instead, even though I'm only doing Invalidate.
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
Invalidate();
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
Invalidate();
}
void SetHotColumn(TreeListColumn col, bool ishot)
{
int scrolloffset = HScrollValue();
if (col != m_hotColumn)
{
if (m_hotColumn != null)
{
m_hotColumn.ishot = false;
Rectangle r = m_hotColumn.CalculatedRect;
r.X -= scrolloffset;
Invalidate(r);
}
m_hotColumn = col;
if (m_hotColumn != null)
{
m_hotColumn.ishot = ishot;
Rectangle r = m_hotColumn.CalculatedRect;
r.X -= scrolloffset;
Invalidate(r);
}
}
}
internal int RowHeaderWidth()
{
if (RowOptions.ShowHeader)
return RowOptions.HeaderWidth;
return 0;
}
int MinWidth()
{
return RowHeaderWidth() + Columns.ColumnsWidth;
}
int MaxVisibleRows(out int remainder)
{
remainder = 0;
if (ClientRectangle.Height < 0)
return 0;
int height = ClientRectangle.Height - Columns.Options.HeaderHeight;
//return (int) Math.Ceiling((double)(ClientRectangle.Height - Columns.HeaderHeight) / (double)Nodes.ItemHeight);
remainder = (ClientRectangle.Height - Columns.Options.HeaderHeight) % RowOptions.ItemHeight ;
return (ClientRectangle.Height - Columns.Options.HeaderHeight) / RowOptions.ItemHeight ;
}
int MaxVisibleRows()
{
int unused;
return MaxVisibleRows(out unused);
}
public void BeginUpdate()
{
m_nodes.BeginUpdate();
}
public void EndUpdate()
{
m_nodes.EndUpdate();
RecalcLayout();
}
protected override CreateParams CreateParams
{
get
{
CreateParams p = base.CreateParams;
p.Style &= ~(int)CloudBox.Controller.WinUtil.WS_BORDER;
p.ExStyle &= ~(int)CloudBox.Controller.WinUtil.WS_EX_CLIENTEDGE;
switch (ViewOptions.BorderStyle)
{
case BorderStyle.Fixed3D:
p.ExStyle |= (int)CloudBox.Controller.WinUtil.WS_EX_CLIENTEDGE;
break;
case BorderStyle.FixedSingle:
p.Style |= (int)CloudBox.Controller.WinUtil.WS_BORDER;
break;
default:
break;
}
return p;
}
}
TreeListColumn m_hotColumn = null;
object GetDataDesignMode(Node node, TreeListColumn column)
{
string id = string.Empty;
while (node != null)
{
id = node.Owner.GetNodeIndex(node).ToString() + ":" + id;
node = node.Parent;
}
return "<temp>" + id;
}
protected virtual object GetData(Node node, TreeListColumn column)
{
if (node[column.Index] != null)
return node[column.Index];
return null;
}
public new Rectangle ClientRectangle
{
get
{
Rectangle r = base.ClientRectangle;
if (m_vScroll.Visible)
r.Width -= m_vScroll.Width+1;
if (m_hScroll.Visible)
r.Height -= m_hScroll.Height+1;
return r;
}
}
protected virtual CloudBox.Controller.TreeList.TextFormatting GetFormatting(CloudBox.Controller.Node node, CloudBox.Controller.TreeListColumn column)
{
return column.CellFormat;
}
protected virtual void PaintCell(Graphics dc, Rectangle cellRect, Node node, TreeListColumn column)
{
if (this.DesignMode)
CellPainter.PaintCell(dc, cellRect, node, column, GetFormatting(node, column), GetDataDesignMode(node, column));
else
CellPainter.PaintCell(dc, cellRect, node, column, GetFormatting(node, column), GetData(node, column));
}
protected virtual void PaintImage(Graphics dc, Rectangle imageRect, Node node, Image image)
{
if (image != null)
dc.DrawImageUnscaled(image, imageRect);
}
protected virtual void PaintNode(Graphics dc, Rectangle rowRect, Node node, TreeListColumn[] visibleColumns, int visibleRowIndex)
{
CellPainter.DrawSelectionBackground(dc, rowRect, node);
foreach (TreeListColumn col in visibleColumns)
{
if (col.CalculatedRect.Right - HScrollValue() < RowHeaderWidth())
continue;
Rectangle cellRect = rowRect;
cellRect.X = col.CalculatedRect.X - HScrollValue();
cellRect.Width = col.CalculatedRect.Width;
if (col.VisibleIndex == 0)
{
int lineindet = 10;
// add left margin
cellRect.X += Columns.Options.LeftMargin;
cellRect.Width -= Columns.Options.LeftMargin;
// add indent size
int indentSize = GetIndentSize(node) + 5;
cellRect.X += indentSize;
cellRect.Width -= indentSize;
if (ViewOptions.ShowLine)
PaintLines(dc, cellRect, node);
cellRect.X += lineindet;
cellRect.Width -= lineindet;
Rectangle glyphRect = GetPlusMinusRectangle(node, col, visibleRowIndex);
if (glyphRect != Rectangle.Empty && ViewOptions.ShowPlusMinus)
CellPainter.PaintCellPlusMinus(dc, glyphRect, node);
if (!ViewOptions.ShowLine && !ViewOptions.ShowPlusMinus)
{
cellRect.X -= (lineindet + 5);
cellRect.Width += (lineindet + 5);
}
Image icon = GetNodeBitmap(node);
if (icon != null)
{
// center the image vertically
glyphRect.Y = cellRect.Y + (cellRect.Height / 2) - (icon.Height / 2);
glyphRect.X = cellRect.X;
glyphRect.Width = icon.Width;
glyphRect.Height = icon.Height;
PaintImage(dc, glyphRect, node, icon);
cellRect.X += (glyphRect.Width + 2);
cellRect.Width -= (glyphRect.Width + 2);
}
PaintCell(dc, cellRect, node, col);
}
else
{
PaintCell(dc, cellRect, node, col);
}
}
}
protected virtual void PaintLines(Graphics dc, Rectangle cellRect, Node node)
{
Pen pen = new Pen(Color.Gray);
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
int halfPoint = cellRect.Top + (cellRect.Height / 2);
// line should start from center at first root node
if (node.Parent == null && node.PrevSibling == null)
{
cellRect.Y += (cellRect.Height / 2);
cellRect.Height -= (cellRect.Height / 2);
}
if (node.NextSibling != null) // draw full height line
dc.DrawLine(pen, cellRect.X, cellRect.Top, cellRect.X, cellRect.Bottom);
else
dc.DrawLine(pen, cellRect.X, cellRect.Top, cellRect.X, halfPoint);
dc.DrawLine(pen, cellRect.X, halfPoint, cellRect.X + 8, halfPoint);
// now draw the lines for the parents sibling
Node parent = node.Parent;
while (parent != null)
{
cellRect.X -= ViewOptions.Indent;
if (parent.NextSibling != null)
dc.DrawLine(pen, cellRect.X, cellRect.Top, cellRect.X, cellRect.Bottom);
parent = parent.Parent;
}
pen.Dispose();
}
protected virtual int GetIndentSize(Node node)
{
int indent = 0;
Node parent = node.Parent;
while (parent != null)
{
indent += ViewOptions.Indent;
parent = parent.Parent;
}
return indent;
}
protected virtual Rectangle GetPlusMinusRectangle(Node node, TreeListColumn firstColumn, int visibleRowIndex)
{
if (node.HasChildren == false)
return Rectangle.Empty;
int hScrollOffset = HScrollValue();
if (firstColumn.CalculatedRect.Right - hScrollOffset < RowHeaderWidth())
return Rectangle.Empty;
System.Diagnostics.Debug.Assert(firstColumn.VisibleIndex == 0);
Rectangle glyphRect = firstColumn.CalculatedRect;
glyphRect.X -= hScrollOffset;
glyphRect.X += GetIndentSize(node);
glyphRect.X += Columns.Options.LeftMargin;
glyphRect.Width = 10;
glyphRect.Y = VisibleRowToYPoint(visibleRowIndex);
glyphRect.Height = RowOptions.ItemHeight;
return glyphRect;
}
protected virtual Image GetNodeBitmap(Node node)
{
if (Images != null && node.ImageId >= 0 && node.ImageId < Images.Images.Count)
return Images.Images[node.ImageId];
return null;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int hScrollOffset = HScrollValue();
int remainder = 0;
int visiblerows = MaxVisibleRows(out remainder);
if (remainder > 0)
visiblerows++;
bool drawColumnHeaders = true;
// draw columns
if (drawColumnHeaders)
{
Rectangle headerRect = e.ClipRectangle;
Columns.Draw(e.Graphics, headerRect, hScrollOffset);
}
// draw vertical grid lines
if (ViewOptions.ShowGridLines)
{
// visible row count
int remainRows = Nodes.VisibleNodeCount - m_vScroll.Value;
if (visiblerows > remainRows)
visiblerows = remainRows;
Rectangle fullRect = ClientRectangle;
if (drawColumnHeaders)
fullRect.Y += Columns.Options.HeaderHeight;
fullRect.Height = visiblerows * RowOptions.ItemHeight;
Columns.Painter.DrawVerticalGridLines(Columns, e.Graphics, fullRect, hScrollOffset);
}
int visibleRowIndex = 0;
TreeListColumn[] visibleColumns = this.Columns.VisibleColumns;
int columnsWidth = Columns.ColumnsWidth;
foreach (Node node in NodeCollection.ForwardNodeIterator(m_firstVisibleNode, true))
{
Rectangle rowRect = CalcRowRecangle(visibleRowIndex);
if (rowRect == Rectangle.Empty || rowRect.Bottom <= e.ClipRectangle.Top || rowRect.Top >= e.ClipRectangle.Bottom)
{
if (visibleRowIndex > visiblerows)
break;
visibleRowIndex++;
continue;
}
rowRect.X = RowHeaderWidth() - hScrollOffset;
rowRect.Width = columnsWidth;
// draw horizontal grid line for current node
if (ViewOptions.ShowGridLines)
{
Rectangle r = rowRect;
r.X = RowHeaderWidth();
r.Width = columnsWidth - hScrollOffset;
m_rowPainter.DrawHorizontalGridLine(e.Graphics, r);
}
// draw the current node
PaintNode(e.Graphics, rowRect, node, visibleColumns, visibleRowIndex);
// drow row header for current node
Rectangle headerRect = rowRect;
headerRect.X = 0;
headerRect.Width = RowHeaderWidth();
int absoluteRowIndex = visibleRowIndex + VScrollValue();
headerRect.Width = RowHeaderWidth();
m_rowPainter.DrawHeader(e.Graphics, headerRect, absoluteRowIndex == m_hotrow);
visibleRowIndex++;
}
}
protected override bool IsInputKey(Keys keyData)
{
if ((int)(keyData & Keys.Shift) > 0)
return true;
switch (keyData)
{
case Keys.Left:
case Keys.Right:
case Keys.Down:
case Keys.Up:
case Keys.PageUp:
case Keys.PageDown:
case Keys.Home:
case Keys.End:
return true;
}
return false;
}
protected override void OnKeyDown(KeyEventArgs e)
{
Node newnode = null;
if (e.KeyCode == Keys.PageUp)
{
int remainder = 0;
int diff = MaxVisibleRows(out remainder)-1;
newnode = NodeCollection.GetNextNode(FocusedNode, -diff);
if (newnode == null)
newnode = Nodes.FirstVisibleNode();
}
if (e.KeyCode == Keys.PageDown)
{
int remainder = 0;
int diff = MaxVisibleRows(out remainder)-1;
newnode = NodeCollection.GetNextNode(FocusedNode, diff);
if (newnode == null)
newnode = Nodes.LastVisibleNode(true);
}
if (e.KeyCode == Keys.Down)
{
newnode = NodeCollection.GetNextNode(FocusedNode, 1);
}
if (e.KeyCode == Keys.Up)
{
newnode = NodeCollection.GetNextNode(FocusedNode, -1);
}
if (e.KeyCode == Keys.Home)
{
newnode = Nodes.FirstNode;
}
if (e.KeyCode == Keys.End)
{
newnode = Nodes.LastVisibleNode(true);
}
if (e.KeyCode == Keys.Left)
{
if (FocusedNode != null)
{
if (FocusedNode.Expanded)
{
FocusedNode.Collapse();
EnsureVisible(FocusedNode);
return;
}
if (FocusedNode.Parent != null)
{
FocusedNode = FocusedNode.Parent;
EnsureVisible(FocusedNode);
}
}
}
if (e.KeyCode == Keys.Right)
{
if (FocusedNode != null)
{
if (FocusedNode.Expanded == false && FocusedNode.HasChildren)
{
FocusedNode.Expand();
EnsureVisible(FocusedNode);
return;
}
if (FocusedNode.Expanded == true && FocusedNode.HasChildren)
{
FocusedNode = FocusedNode.Nodes.FirstNode;
EnsureVisible(FocusedNode);
}
}
}
if (newnode != null)
{
if (MultiSelect)
{
// tree behavior is
// keys none, the selected node is added as the focused and selected node
// keys control, only focused node is moved, the selected nodes collection is not modified
// keys shift, selection from first selected node to current node is done
if (Control.ModifierKeys == Keys.Control)
FocusedNode = newnode;
else
MultiSelectAdd(newnode, Control.ModifierKeys);
}
else
FocusedNode = newnode;
EnsureVisible(FocusedNode);
}
base.OnKeyDown(e);
}
internal void internalUpdateStyles()
{
base.UpdateStyles();
}
#region ISupportInitialize Members
public void BeginInit()
{
Columns.BeginInit();
}
public void EndInit()
{
Columns.EndInit();
}
#endregion
internal new bool DesignMode
{
get { return base.DesignMode; }
}
}
public class TreeListViewNodes : NodeCollection
{
TreeListView m_tree;
bool m_isUpdating = false;
public void BeginUpdate()
{
m_isUpdating = true;
}
public void EndUpdate()
{
m_isUpdating = false;
}
public TreeListViewNodes(TreeListView owner) : base(null)
{
m_tree = owner;
}
protected override void UpdateNodeCount(int oldvalue, int newvalue)
{
base.UpdateNodeCount(oldvalue, newvalue);
if (!m_isUpdating)
m_tree.RecalcLayout();
}
public override void Clear()
{
base.Clear();
m_tree.RecalcLayout();
}
public override void NodetifyBeforeExpand(Node nodeToExpand, bool expanding)
{
if (!m_tree.DesignMode)
m_tree.OnNotifyBeforeExpand(nodeToExpand, expanding);
}
public override void NodetifyAfterExpand(Node nodeToExpand, bool expanded)
{
m_tree.OnNotifyAfterExpand(nodeToExpand, expanded);
}
protected override int GetFieldIndex(string fieldname)
{
TreeListColumn col = m_tree.Columns[fieldname];
if (col != null)
return col.Index;
return -1;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Permissions
{
using System;
using System.IO;
using System.Security.Util;
using System.Text;
using System.Threading;
using System.Runtime.Remoting;
using System.Security;
using System.Runtime.Serialization;
using System.Reflection;
using System.Globalization;
using System.Diagnostics.Contracts;
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
#if !FEATURE_CAS_POLICY
// The csharp compiler requires these types to be public, but they are not used elsewhere.
[Obsolete("SecurityPermissionFlag is no longer accessible to application code.")]
#endif
public enum SecurityPermissionFlag
{
NoFlags = 0x00,
/* The following enum value is used in the EE (ASSERT_PERMISSION in security.cpp)
* Should this value change, make corresponding changes there
*/
Assertion = 0x01,
UnmanagedCode = 0x02, // Update vm\Security.h if you change this !
SkipVerification = 0x04, // Update vm\Security.h if you change this !
Execution = 0x08,
ControlThread = 0x10,
ControlEvidence = 0x20,
ControlPolicy = 0x40,
SerializationFormatter = 0x80,
ControlDomainPolicy = 0x100,
ControlPrincipal = 0x200,
ControlAppDomain = 0x400,
RemotingConfiguration = 0x800,
Infrastructure = 0x1000,
BindingRedirects = 0x2000,
AllFlags = 0x3fff,
}
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
sealed public class SecurityPermission
: CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
{
#pragma warning disable 618
private SecurityPermissionFlag m_flags;
#pragma warning restore 618
//
// Public Constructors
//
public SecurityPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
{
SetUnrestricted( true );
}
else if (state == PermissionState.None)
{
SetUnrestricted( false );
Reset();
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
}
// SecurityPermission
//
#pragma warning disable 618
public SecurityPermission(SecurityPermissionFlag flag)
#pragma warning restore 618
{
VerifyAccess(flag);
SetUnrestricted(false);
m_flags = flag;
}
//------------------------------------------------------
//
// PRIVATE AND PROTECTED MODIFIERS
//
//------------------------------------------------------
private void SetUnrestricted(bool unrestricted)
{
if (unrestricted)
{
#pragma warning disable 618
m_flags = SecurityPermissionFlag.AllFlags;
#pragma warning restore 618
}
}
private void Reset()
{
#pragma warning disable 618
m_flags = SecurityPermissionFlag.NoFlags;
#pragma warning restore 618
}
#pragma warning disable 618
public SecurityPermissionFlag Flags
#pragma warning restore 618
{
set
{
VerifyAccess(value);
m_flags = value;
}
get
{
return m_flags;
}
}
//
// CodeAccessPermission methods
//
/*
* IPermission interface implementation
*/
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
{
return m_flags == 0;
}
SecurityPermission operand = target as SecurityPermission;
if (operand != null)
{
return (((int)this.m_flags) & ~((int)operand.m_flags)) == 0;
}
else
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
}
public override IPermission Union(IPermission target) {
if (target == null) return(this.Copy());
if (!VerifyType(target)) {
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
SecurityPermission sp_target = (SecurityPermission) target;
if (sp_target.IsUnrestricted() || IsUnrestricted()) {
return(new SecurityPermission(PermissionState.Unrestricted));
}
#pragma warning disable 618
SecurityPermissionFlag flag_union = (SecurityPermissionFlag)(m_flags | sp_target.m_flags);
#pragma warning restore 618
return(new SecurityPermission(flag_union));
}
public override IPermission Intersect(IPermission target)
{
if (target == null)
return null;
else if (!VerifyType(target))
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
SecurityPermission operand = (SecurityPermission)target;
#pragma warning disable 618
SecurityPermissionFlag isectFlags = SecurityPermissionFlag.NoFlags;
#pragma warning restore 618
if (operand.IsUnrestricted())
{
if (this.IsUnrestricted())
return new SecurityPermission(PermissionState.Unrestricted);
else
#pragma warning disable 618
isectFlags = (SecurityPermissionFlag)this.m_flags;
#pragma warning restore 618
}
else if (this.IsUnrestricted())
{
#pragma warning disable 618
isectFlags = (SecurityPermissionFlag)operand.m_flags;
#pragma warning restore 618
}
else
{
#pragma warning disable 618
isectFlags = (SecurityPermissionFlag)m_flags & (SecurityPermissionFlag)operand.m_flags;
#pragma warning restore 618
}
if (isectFlags == 0)
return null;
else
return new SecurityPermission(isectFlags);
}
public override IPermission Copy()
{
if (IsUnrestricted())
return new SecurityPermission(PermissionState.Unrestricted);
else
#pragma warning disable 618
return new SecurityPermission((SecurityPermissionFlag)m_flags);
#pragma warning restore 618
}
public bool IsUnrestricted()
{
#pragma warning disable 618
return m_flags == SecurityPermissionFlag.AllFlags;
#pragma warning restore 618
}
private
#pragma warning disable 618
void VerifyAccess(SecurityPermissionFlag type)
#pragma warning restore 618
{
#pragma warning disable 618
if ((type & ~SecurityPermissionFlag.AllFlags) != 0)
#pragma warning restore 618
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type));
Contract.EndContractBlock();
}
#if FEATURE_CAS_POLICY
//------------------------------------------------------
//
// PUBLIC ENCODING METHODS
//
//------------------------------------------------------
private const String _strHeaderAssertion = "Assertion";
private const String _strHeaderUnmanagedCode = "UnmanagedCode";
private const String _strHeaderExecution = "Execution";
private const String _strHeaderSkipVerification = "SkipVerification";
private const String _strHeaderControlThread = "ControlThread";
private const String _strHeaderControlEvidence = "ControlEvidence";
private const String _strHeaderControlPolicy = "ControlPolicy";
private const String _strHeaderSerializationFormatter = "SerializationFormatter";
private const String _strHeaderControlDomainPolicy = "ControlDomainPolicy";
private const String _strHeaderControlPrincipal = "ControlPrincipal";
private const String _strHeaderControlAppDomain = "ControlAppDomain";
public override SecurityElement ToXml()
{
SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SecurityPermission" );
if (!IsUnrestricted())
{
esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( SecurityPermissionFlag ), m_flags ) );
}
else
{
esd.AddAttribute( "Unrestricted", "true" );
}
return esd;
}
public override void FromXml(SecurityElement esd)
{
CodeAccessPermission.ValidateElement( esd, this );
if (XMLUtil.IsUnrestricted( esd ))
{
m_flags = SecurityPermissionFlag.AllFlags;
return;
}
Reset () ;
SetUnrestricted (false) ;
String flags = esd.Attribute( "Flags" );
if (flags != null)
m_flags = (SecurityPermissionFlag)Enum.Parse( typeof( SecurityPermissionFlag ), flags );
}
#endif // FEATURE_CAS_POLICY
//
// Object Overrides
//
#if ZERO // Do not remove this code, usefull for debugging
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("SecurityPermission(");
if (IsUnrestricted())
{
sb.Append("Unrestricted");
}
else
{
if (GetFlag(SecurityPermissionFlag.Assertion))
sb.Append("Assertion; ");
if (GetFlag(SecurityPermissionFlag.UnmanagedCode))
sb.Append("UnmangedCode; ");
if (GetFlag(SecurityPermissionFlag.SkipVerification))
sb.Append("SkipVerification; ");
if (GetFlag(SecurityPermissionFlag.Execution))
sb.Append("Execution; ");
if (GetFlag(SecurityPermissionFlag.ControlThread))
sb.Append("ControlThread; ");
if (GetFlag(SecurityPermissionFlag.ControlEvidence))
sb.Append("ControlEvidence; ");
if (GetFlag(SecurityPermissionFlag.ControlPolicy))
sb.Append("ControlPolicy; ");
if (GetFlag(SecurityPermissionFlag.SerializationFormatter))
sb.Append("SerializationFormatter; ");
if (GetFlag(SecurityPermissionFlag.ControlDomainPolicy))
sb.Append("ControlDomainPolicy; ");
if (GetFlag(SecurityPermissionFlag.ControlPrincipal))
sb.Append("ControlPrincipal; ");
}
sb.Append(")");
return sb.ToString();
}
#endif
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
return SecurityPermission.GetTokenIndex();
}
internal static int GetTokenIndex()
{
return BuiltInPermissionIndex.SecurityPermissionIndex;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using VotingInfo.Database.Contracts;
using VotingInfo.Database.Contracts.Data;
///////////////////////////////////////////////////////////
//Do not modify this file. Use a partial class to extend.//
///////////////////////////////////////////////////////////
// This file contains static implementations of the ElectionLevelLogic
// Add your own static methods by making a new partial class.
// You cannot override static methods, instead override the methods
// located in ElectionLevelLogicBase by making a partial class of ElectionLevelLogic
// and overriding the base methods.
namespace VotingInfo.Database.Logic.Data
{
public partial class ElectionLevelLogic
{
//Put your code in a separate file. This is auto generated.
/// <summary>
/// Run ElectionLevel_Insert.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="fldElectionLevelTitle">Value for ElectionLevelTitle</param>
public static int? InsertNow(int fldContentInspectionId
, string fldElectionLevelTitle
)
{
return (new ElectionLevelLogic()).Insert(fldContentInspectionId
, fldElectionLevelTitle
);
}
/// <summary>
/// Run ElectionLevel_Insert.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="fldElectionLevelTitle">Value for ElectionLevelTitle</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
public static int? InsertNow(int fldContentInspectionId
, string fldElectionLevelTitle
, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).Insert(fldContentInspectionId
, fldElectionLevelTitle
, connection, transaction);
}
/// <summary>
/// Insert by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public static int InsertNow(ElectionLevelContract row)
{
return (new ElectionLevelLogic()).Insert(row);
}
/// <summary>
/// Insert by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int InsertNow(ElectionLevelContract row, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).Insert(row, connection, transaction);
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <returns>The number of rows affected.</returns>
public static int InsertAllNow(List<ElectionLevelContract> rows)
{
return (new ElectionLevelLogic()).InsertAll(rows);
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int InsertAllNow(List<ElectionLevelContract> rows, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).InsertAll(rows, connection, transaction);
}
/// <summary>
/// Run ElectionLevel_Update.
/// </summary>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="fldElectionLevelTitle">Value for ElectionLevelTitle</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateNow(int fldElectionLevelId
, int fldContentInspectionId
, string fldElectionLevelTitle
)
{
return (new ElectionLevelLogic()).Update(fldElectionLevelId
, fldContentInspectionId
, fldElectionLevelTitle
);
}
/// <summary>
/// Run ElectionLevel_Update.
/// </summary>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="fldElectionLevelTitle">Value for ElectionLevelTitle</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateNow(int fldElectionLevelId
, int fldContentInspectionId
, string fldElectionLevelTitle
, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).Update(fldElectionLevelId
, fldContentInspectionId
, fldElectionLevelTitle
, connection, transaction);
}
/// <summary>
/// Update by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateNow(ElectionLevelContract row)
{
return (new ElectionLevelLogic()).Update(row);
}
/// <summary>
/// Update by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateNow(ElectionLevelContract row, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).Update(row, connection, transaction);
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateAllNow(List<ElectionLevelContract> rows)
{
return (new ElectionLevelLogic()).UpdateAll(rows);
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int UpdateAllNow(List<ElectionLevelContract> rows, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).UpdateAll(rows, connection, transaction);
}
/// <summary>
/// Run ElectionLevel_Delete.
/// </summary>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteNow(int fldElectionLevelId
)
{
return (new ElectionLevelLogic()).Delete(fldElectionLevelId
);
}
/// <summary>
/// Run ElectionLevel_Delete.
/// </summary>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteNow(int fldElectionLevelId
, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).Delete(fldElectionLevelId
, connection, transaction);
}
/// <summary>
/// Delete by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteNow(ElectionLevelContract row)
{
return (new ElectionLevelLogic()).Delete(row);
}
/// <summary>
/// Delete by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteNow(ElectionLevelContract row, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).Delete(row, connection, transaction);
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteAllNow(List<ElectionLevelContract> rows)
{
return (new ElectionLevelLogic()).DeleteAll(rows);
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int DeleteAllNow(List<ElectionLevelContract> rows, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).DeleteAll(rows, connection, transaction);
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <returns>True, if the values exist, or false.</returns>
public static bool ExistsNow(int fldElectionLevelId
)
{
return (new ElectionLevelLogic()).Exists(fldElectionLevelId
);
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>True, if the values exist, or false.</returns>
public static bool ExistsNow(int fldElectionLevelId
, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).Exists(fldElectionLevelId
, connection, transaction);
}
/// <summary>
/// Run ElectionLevel_Search, and return results as a list of ElectionLevelRow.
/// </summary>
/// <param name="fldElectionLevelTitle">Value for ElectionLevelTitle</param>
/// <returns>A collection of ElectionLevelRow.</returns>
public static List<ElectionLevelContract> SearchNow(string fldElectionLevelTitle
)
{
var driver = new ElectionLevelLogic();
driver.Search(fldElectionLevelTitle
);
return driver.Results;
}
/// <summary>
/// Run ElectionLevel_Search, and return results as a list of ElectionLevelRow.
/// </summary>
/// <param name="fldElectionLevelTitle">Value for ElectionLevelTitle</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ElectionLevelRow.</returns>
public static List<ElectionLevelContract> SearchNow(string fldElectionLevelTitle
, SqlConnection connection, SqlTransaction transaction)
{
var driver = new ElectionLevelLogic();
driver.Search(fldElectionLevelTitle
, connection, transaction);
return driver.Results;
}
/// <summary>
/// Run ElectionLevel_SelectAll, and return results as a list of ElectionLevelRow.
/// </summary>
/// <returns>A collection of ElectionLevelRow.</returns>
public static List<ElectionLevelContract> SelectAllNow()
{
var driver = new ElectionLevelLogic();
driver.SelectAll();
return driver.Results;
}
/// <summary>
/// Run ElectionLevel_SelectAll, and return results as a list of ElectionLevelRow.
/// </summary>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ElectionLevelRow.</returns>
public static List<ElectionLevelContract> SelectAllNow(SqlConnection connection, SqlTransaction transaction)
{
var driver = new ElectionLevelLogic();
driver.SelectAll(connection, transaction);
return driver.Results;
}
/// <summary>
/// Run ElectionLevel_List, and return results as a list.
/// </summary>
/// <param name="fldElectionLevelTitle">Value for ElectionLevelTitle</param>
/// <returns>A collection of __ListItemRow.</returns>
public static List<ListItemContract> ListNow(string fldElectionLevelTitle
)
{
return (new ElectionLevelLogic()).List(fldElectionLevelTitle
);
}
/// <summary>
/// Run ElectionLevel_List, and return results as a list.
/// </summary>
/// <param name="fldElectionLevelTitle">Value for ElectionLevelTitle</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of __ListItemRow.</returns>
public static List<ListItemContract> ListNow(string fldElectionLevelTitle
, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).List(fldElectionLevelTitle
, connection, transaction);
}
/// <summary>
/// Run ElectionLevel_SelectBy_ElectionLevelId, and return results as a list of ElectionLevelRow.
/// </summary>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <returns>A collection of ElectionLevelRow.</returns>
public static List<ElectionLevelContract> SelectBy_ElectionLevelIdNow(int fldElectionLevelId
)
{
var driver = new ElectionLevelLogic();
driver.SelectBy_ElectionLevelId(fldElectionLevelId
);
return driver.Results;
}
/// <summary>
/// Run ElectionLevel_SelectBy_ElectionLevelId, and return results as a list of ElectionLevelRow.
/// </summary>
/// <param name="fldElectionLevelId">Value for ElectionLevelId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ElectionLevelRow.</returns>
public static List<ElectionLevelContract> SelectBy_ElectionLevelIdNow(int fldElectionLevelId
, SqlConnection connection, SqlTransaction transaction)
{
var driver = new ElectionLevelLogic();
driver.SelectBy_ElectionLevelId(fldElectionLevelId
, connection, transaction);
return driver.Results;
}
/// <summary>
/// Run ElectionLevel_SelectBy_ContentInspectionId, and return results as a list of ElectionLevelRow.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <returns>A collection of ElectionLevelRow.</returns>
public static List<ElectionLevelContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId
)
{
var driver = new ElectionLevelLogic();
driver.SelectBy_ContentInspectionId(fldContentInspectionId
);
return driver.Results;
}
/// <summary>
/// Run ElectionLevel_SelectBy_ContentInspectionId, and return results as a list of ElectionLevelRow.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ElectionLevelRow.</returns>
public static List<ElectionLevelContract> SelectBy_ContentInspectionIdNow(int fldContentInspectionId
, SqlConnection connection, SqlTransaction transaction)
{
var driver = new ElectionLevelLogic();
driver.SelectBy_ContentInspectionId(fldContentInspectionId
, connection, transaction);
return driver.Results;
}
/// <summary>
/// Read all ElectionLevel rows from the provided reader into the list structure of ElectionLevelRows
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
/// <returns>A populated ElectionLevelRows or an empty ElectionLevelRows if there are no results.</returns>
public static List<ElectionLevelContract> ReadAllNow(SqlDataReader reader)
{
var driver = new ElectionLevelLogic();
driver.ReadAll(reader);
return driver.Results;
}
/// <summary>");
/// Advance one, and read values into a ElectionLevel
/// </summary>
/// <param name="reader">The result of running a sql command.</param>");
/// <returns>A ElectionLevel or null if there are no results.</returns>
public static ElectionLevelContract ReadOneNow(SqlDataReader reader)
{
var driver = new ElectionLevelLogic();
return driver.ReadOne(reader) ? driver.Results[0] : null;
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <returns>The number of rows affected.</returns>
public static int SaveNow(ElectionLevelContract row)
{
if(row.ElectionLevelId == null)
{
return InsertNow(row);
}
else
{
return UpdateNow(row);
}
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int SaveNow(ElectionLevelContract row, SqlConnection connection, SqlTransaction transaction)
{
if(row.ElectionLevelId == null)
{
return InsertNow(row, connection, transaction);
}
else
{
return UpdateNow(row, connection, transaction);
}
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <returns>The number of rows affected.</returns>
public static int SaveAllNow(List<ElectionLevelContract> rows)
{
return (new ElectionLevelLogic()).SaveAll(rows);
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public static int SaveAllNow(List<ElectionLevelContract> rows, SqlConnection connection, SqlTransaction transaction)
{
return (new ElectionLevelLogic()).SaveAll(rows, connection, transaction);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Reflection;
using Microsoft.Win32;
namespace System.Diagnostics.Tracing
{
public partial class EventSource
{
// ActivityID support (see also WriteEventWithRelatedActivityIdCore)
/// <summary>
/// When a thread starts work that is on behalf of 'something else' (typically another
/// thread or network request) it should mark the thread as working on that other work.
/// This API marks the current thread as working on activity 'activityID'. This API
/// should be used when the caller knows the thread's current activity (the one being
/// overwritten) has completed. Otherwise, callers should prefer the overload that
/// return the oldActivityThatWillContinue (below).
///
/// All events created with the EventSource on this thread are also tagged with the
/// activity ID of the thread.
///
/// It is common, and good practice after setting the thread to an activity to log an event
/// with a 'start' opcode to indicate that precise time/thread where the new activity
/// started.
/// </summary>
/// <param name="activityId">A Guid that represents the new activity with which to mark
/// the current thread</param>
[System.Security.SecuritySafeCritical]
public static void SetCurrentThreadActivityId(Guid activityId)
{
if (TplEtwProvider.Log != null)
TplEtwProvider.Log.SetActivityId(activityId);
#if FEATURE_MANAGED_ETW
#if FEATURE_ACTIVITYSAMPLING
Guid newId = activityId;
#endif // FEATURE_ACTIVITYSAMPLING
// We ignore errors to keep with the convention that EventSources do not throw errors.
// Note we can't access m_throwOnWrites because this is a static method.
if (UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID,
ref activityId) == 0)
{
#if FEATURE_ACTIVITYSAMPLING
var activityDying = s_activityDying;
if (activityDying != null && newId != activityId)
{
if (activityId == Guid.Empty)
{
activityId = FallbackActivityId;
}
// OutputDebugString(string.Format("Activity dying: {0} -> {1}", activityId, newId));
activityDying(activityId); // This is actually the OLD activity ID.
}
#endif // FEATURE_ACTIVITYSAMPLING
}
#endif // FEATURE_MANAGED_ETW
}
/// <summary>
/// When a thread starts work that is on behalf of 'something else' (typically another
/// thread or network request) it should mark the thread as working on that other work.
/// This API marks the current thread as working on activity 'activityID'. It returns
/// whatever activity the thread was previously marked with. There is a convention that
/// callers can assume that callees restore this activity mark before the callee returns.
/// To encourage this this API returns the old activity, so that it can be restored later.
///
/// All events created with the EventSource on this thread are also tagged with the
/// activity ID of the thread.
///
/// It is common, and good practice after setting the thread to an activity to log an event
/// with a 'start' opcode to indicate that precise time/thread where the new activity
/// started.
/// </summary>
/// <param name="activityId">A Guid that represents the new activity with which to mark
/// the current thread</param>
/// <param name="oldActivityThatWillContinue">The Guid that represents the current activity
/// which will continue at some point in the future, on the current thread</param>
[System.Security.SecuritySafeCritical]
public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue)
{
oldActivityThatWillContinue = activityId;
#if FEATURE_MANAGED_ETW
// We ignore errors to keep with the convention that EventSources do not throw errors.
// Note we can't access m_throwOnWrites because this is a static method.
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID,
ref oldActivityThatWillContinue);
#endif // FEATURE_MANAGED_ETW
// We don't call the activityDying callback here because the caller has declared that
// it is not dying.
if (TplEtwProvider.Log != null)
TplEtwProvider.Log.SetActivityId(activityId);
}
/// <summary>
/// Retrieves the ETW activity ID associated with the current thread.
/// </summary>
public static Guid CurrentThreadActivityId
{
[System.Security.SecuritySafeCritical]
get
{
// We ignore errors to keep with the convention that EventSources do not throw
// errors. Note we can't access m_throwOnWrites because this is a static method.
Guid retVal = new Guid();
#if FEATURE_MANAGED_ETW
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID,
ref retVal);
#endif // FEATURE_MANAGED_ETW
return retVal;
}
}
private int GetParameterCount(EventMetadata eventData)
{
return eventData.Parameters.Length;
}
private Type GetDataType(EventMetadata eventData, int parameterId)
{
return eventData.Parameters[parameterId].ParameterType;
}
private static string GetResourceString(string key, params object[] args)
{
return Environment.GetResourceString(key, args);
}
private static readonly bool m_EventSourcePreventRecursion = false;
}
internal partial class ManifestBuilder
{
private string GetTypeNameHelper(Type type)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
return "win:Boolean";
case TypeCode.Byte:
return "win:UInt8";
case TypeCode.Char:
case TypeCode.UInt16:
return "win:UInt16";
case TypeCode.UInt32:
return "win:UInt32";
case TypeCode.UInt64:
return "win:UInt64";
case TypeCode.SByte:
return "win:Int8";
case TypeCode.Int16:
return "win:Int16";
case TypeCode.Int32:
return "win:Int32";
case TypeCode.Int64:
return "win:Int64";
case TypeCode.String:
return "win:UnicodeString";
case TypeCode.Single:
return "win:Float";
case TypeCode.Double:
return "win:Double";
case TypeCode.DateTime:
return "win:FILETIME";
default:
if (type == typeof(Guid))
return "win:GUID";
else if (type == typeof(IntPtr))
return "win:Pointer";
else if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte))
return "win:Binary";
ManifestError(Environment.GetResourceString("EventSource_UnsupportedEventTypeInManifest", type.Name), true);
return string.Empty;
}
}
}
internal partial class EventProvider
{
[System.Security.SecurityCritical]
internal unsafe int SetInformation(
UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass,
IntPtr data,
uint dataSize)
{
int status = UnsafeNativeMethods.ManifestEtw.ERROR_NOT_SUPPORTED;
if (!m_setInformationMissing)
{
try
{
status = UnsafeNativeMethods.ManifestEtw.EventSetInformation(
m_regHandle,
eventInfoClass,
(void *)data,
(int)dataSize);
}
catch (TypeLoadException)
{
m_setInformationMissing = true;
}
}
return status;
}
}
internal static class Resources
{
internal static string GetResourceString(string key, params object[] args)
{
return Environment.GetResourceString(key, args);
}
}
}
| |
#region Using directives
using SimpleFramework.Xml;
using System.Collections.Generic;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
public class MethodScannerDefaultTest : TestCase {
[Default(DefaultType.PROPERTY)]
public static class NoAnnotations {
private String[] array;
private Map<String, String> map;
private List<String> list;
private Date date;
private String customer;
private String name;
private int price;
public Date Date {
get {
return date;
}
set {
this.date = value;
}
}
//public Date GetDate() {
// return date;
//}
this.array = array;
}
public String[] Array {
get {
return array;
}
}
//public String[] GetArray() {
// return array;
//}
this.map = map;
}
public Map<String, String> getMap() {
return map;
}
public List<String> List {
set {
this.list = value;
}
}
//public void SetList(List<String> list) {
// this.list = list;
//}
return list;
}
//public void SetDate(Date date) {
// this.date = date;
//}
return customer;
}
public String Customer {
set {
this.customer = value;
}
}
//public void SetCustomer(String customer) {
// this.customer = customer;
//}
return name;
}
public String Name {
set {
this.name = value;
}
}
//public void SetName(String name) {
// this.name = name;
//}
return price;
}
public int Price {
set {
this.price = value;
}
}
//public void SetPrice(int price) {
// this.price = price;
//}
[Default(DefaultType.PROPERTY)]
public static class MixedAnnotations {
private String[] array;
private Map<String, String> map;
private String name;
private int value;
[Attribute]
public String Name {
get {
return name;
}
set {
this.name = value;
}
}
//public String GetName() {
// return name;
//}
//public void SetName(String name) {
// this.name = name;
//}
public int Value {
get {
return value;
}
set {
this.value = _value;
}
}
//public int GetValue() {
// return value;
//}
//public void SetValue(int value) {
// this.value = value;
//}
this.array = array;
}
public String[] Array {
get {
return array;
}
}
//public String[] GetArray() {
// return array;
//}
this.map = map;
}
public Map<String, String> getMap() {
return map;
}
}
public static class ExtendedAnnotations : MixedAnnotations {
[Element]
public String[] Array {
get {
return super.Array;
}
set {
super.Array = array;
}
}
//public String[] GetArray() {
// return super.Array;
//}
//public void SetArray(String[] array) {
// super.Array = array;
//}
public void TestNoAnnotationsWithNoDefaults() {
Map<String, Contact> map = getContacts(NoAnnotations.class, null);
assertTrue(map.isEmpty());
}
public void TestMixedAnnotationsWithNoDefaults() {
Map<String, Contact> map = getContacts(MixedAnnotations.class, null);
AssertEquals(map.size(), 2);
assertFalse(map.get("name").isReadOnly());
assertFalse(map.get("value").isReadOnly());
AssertEquals(int.class, map.get("value").getType());
AssertEquals(String.class, map.get("name").getType());
AssertEquals(Attribute.class, map.get("name").getAnnotation().annotationType());
AssertEquals(Element.class, map.get("value").getAnnotation().annotationType());
AssertEquals(Attribute.class, map.get("name").getAnnotation(Attribute.class).annotationType());
AssertEquals(Element.class, map.get("value").getAnnotation(Element.class).annotationType());
AssertNull(map.get("name").getAnnotation(Root.class));
AssertNull(map.get("value").getAnnotation(Root.class));
}
public void TestExtendedAnnotations() {
Map<String, Contact> map = getContacts(ExtendedAnnotations.class, DefaultType.PROPERTY);
assertFalse(map.get("array").isReadOnly());
assertFalse(map.get("map").isReadOnly());
assertFalse(map.get("name").isReadOnly());
assertFalse(map.get("value").isReadOnly());
AssertEquals(String[].class, map.get("array").getType());
AssertEquals(Map.class, map.get("map").getType());
AssertEquals(int.class, map.get("value").getType());
AssertEquals(String.class, map.get("name").getType());
AssertEquals(Attribute.class, map.get("name").getAnnotation().annotationType());
AssertEquals(Element.class, map.get("value").getAnnotation().annotationType());
AssertEquals(ElementMap.class, map.get("map").getAnnotation().annotationType());
AssertEquals(Element.class, map.get("array").getAnnotation().annotationType());
AssertEquals(Attribute.class, map.get("name").getAnnotation(Attribute.class).annotationType());
AssertEquals(Element.class, map.get("value").getAnnotation(Element.class).annotationType());
AssertEquals(ElementMap.class, map.get("map").getAnnotation(ElementMap.class).annotationType());
AssertEquals(Element.class, map.get("array").getAnnotation(Element.class).annotationType());
AssertNull(map.get("name").getAnnotation(Root.class));
AssertNull(map.get("value").getAnnotation(Root.class));
AssertNull(map.get("map").getAnnotation(Root.class));
AssertNull(map.get("array").getAnnotation(Root.class));
}
public void TestMixedAnnotations() {
Map<String, Contact> map = getContacts(MixedAnnotations.class, DefaultType.PROPERTY);
assertFalse(map.get("array").isReadOnly());
assertFalse(map.get("map").isReadOnly());
assertFalse(map.get("name").isReadOnly());
assertFalse(map.get("value").isReadOnly());
AssertEquals(String[].class, map.get("array").getType());
AssertEquals(Map.class, map.get("map").getType());
AssertEquals(int.class, map.get("value").getType());
AssertEquals(String.class, map.get("name").getType());
AssertEquals(Attribute.class, map.get("name").getAnnotation().annotationType());
AssertEquals(Element.class, map.get("value").getAnnotation().annotationType());
AssertEquals(ElementMap.class, map.get("map").getAnnotation().annotationType());
AssertEquals(ElementArray.class, map.get("array").getAnnotation().annotationType());
AssertEquals(Attribute.class, map.get("name").getAnnotation(Attribute.class).annotationType());
AssertEquals(Element.class, map.get("value").getAnnotation(Element.class).annotationType());
AssertEquals(ElementMap.class, map.get("map").getAnnotation(ElementMap.class).annotationType());
AssertEquals(ElementArray.class, map.get("array").getAnnotation(ElementArray.class).annotationType());
AssertNull(map.get("name").getAnnotation(Root.class));
AssertNull(map.get("value").getAnnotation(Root.class));
AssertNull(map.get("map").getAnnotation(Root.class));
AssertNull(map.get("array").getAnnotation(Root.class));
}
public void TestNoAnnotations() {
Map<String, Contact> map = getContacts(NoAnnotations.class, DefaultType.PROPERTY);
assertFalse(map.get("date").isReadOnly());
assertFalse(map.get("customer").isReadOnly());
assertFalse(map.get("name").isReadOnly());
assertFalse(map.get("price").isReadOnly());
assertFalse(map.get("list").isReadOnly());
assertFalse(map.get("map").isReadOnly());
assertFalse(map.get("array").isReadOnly());
AssertEquals(Date.class, map.get("date").getType());
AssertEquals(String.class, map.get("customer").getType());
AssertEquals(String.class, map.get("name").getType());
AssertEquals(int.class, map.get("price").getType());
AssertEquals(List.class, map.get("list").getType());
AssertEquals(Map.class, map.get("map").getType());
AssertEquals(String[].class, map.get("array").getType());
AssertEquals(Element.class, map.get("date").getAnnotation().annotationType());
AssertEquals(Element.class, map.get("customer").getAnnotation().annotationType());
AssertEquals(Element.class, map.get("name").getAnnotation().annotationType());
AssertEquals(Element.class, map.get("price").getAnnotation().annotationType());
AssertEquals(ElementList.class, map.get("list").getAnnotation().annotationType());
AssertEquals(ElementMap.class, map.get("map").getAnnotation().annotationType());
AssertEquals(ElementArray.class, map.get("array").getAnnotation().annotationType());
AssertEquals(Element.class, map.get("date").getAnnotation(Element.class).annotationType());
AssertEquals(Element.class, map.get("customer").getAnnotation(Element.class).annotationType());
AssertEquals(Element.class, map.get("name").getAnnotation(Element.class).annotationType());
AssertEquals(Element.class, map.get("price").getAnnotation(Element.class).annotationType());
AssertEquals(ElementList.class, map.get("list").getAnnotation(ElementList.class).annotationType());
AssertEquals(ElementMap.class, map.get("map").getAnnotation(ElementMap.class).annotationType());
AssertEquals(ElementArray.class, map.get("array").getAnnotation(ElementArray.class).annotationType());
AssertNull(map.get("date").getAnnotation(Root.class));
AssertNull(map.get("customer").getAnnotation(Root.class));
AssertNull(map.get("name").getAnnotation(Root.class));
AssertNull(map.get("price").getAnnotation(Root.class));
AssertNull(map.get("list").getAnnotation(Root.class));
AssertNull(map.get("map").getAnnotation(Root.class));
AssertNull(map.get("array").getAnnotation(Root.class));
}
private static Map<String, Contact> getContacts(Class type, DefaultType defaultType) {
MethodScanner scanner = new MethodScanner(type, defaultType);
Map<String, Contact> map = new HashMap<String, Contact>();
for(Contact contact : scanner) {
map.put(contact.Name, contact);
}
return map;
}
}
}
| |
using System;
using System.IO;
using NUnit.Framework;
using Raksha.Asn1;
using Raksha.Asn1.Cms;
using Raksha.Utilities;
using Raksha.Utilities.Encoders;
using Raksha.Utilities.IO;
using Raksha.Tests.Utilities;
namespace Raksha.Tests.Asn1
{
[TestFixture]
public class CmsTest
: ITest
{
//
// compressed data object
//
private static readonly byte[] compData = Base64.Decode(
"MIAGCyqGSIb3DQEJEAEJoIAwgAIBADANBgsqhkiG9w0BCRADCDCABgkqhkiG9w0BBwGggCSABIIC"
+ "Hnic7ZRdb9owFIbvK/k/5PqVYPFXGK12YYyboVFASSp1vQtZGiLRACZE49/XHoUW7S/0tXP8Efux"
+ "fU5ivWnasml72XFb3gb5druui7ytN803M570nii7C5r8tfwR281hy/p/KSM3+jzH5s3+pbQ90xSb"
+ "P3VT3QbLusnt8WPIuN5vN/vaA2+DulnXTXkXvNTr8j8ouZmkCmGI/UW+ZS/C8zP0bz2dz0zwLt+1"
+ "UEk2M8mlaxjRMByAhZTj0RGYg4TvogiRASROsZgjpVcJCb1KV6QzQeDJ1XkoQ5Jm+C5PbOHZZGRi"
+ "v+ORAcshOGeCcdFJyfgFxdtCdEcmOrbinc/+BBMzRThEYpwl+jEBpciSGWQkI0TSlREmD/eOHb2D"
+ "SGLuESm/iKUFt1y4XHBO2a5oq0IKJKWLS9kUZTA7vC5LSxYmgVL46SIWxIfWBQd6AdrnjLmH94UT"
+ "vGxVibLqRCtIpp4g2qpdtqK1LiOeolpVK5wVQ5P7+QjZAlrh0cePYTx/gNZuB9Vhndtgujl9T/tg"
+ "W9ogK+3rnmg3YWygnTuF5GDS+Q/jIVLnCcYZFc6Kk/+c80wKwZjwdZIqDYWRH68MuBQSXLgXYXj2"
+ "3CAaYOBNJMliTl0X7eV5DnoKIFSKYdj3cRpD/cK/JWTHJRe76MUXnfBW8m7Hd5zhQ4ri2NrVF/WL"
+ "+kV1/3AGSlJ32bFPd2BsQD8uSzIx6lObkjdz95c0AAAAAAAAAAAAAAAA");
//
// enveloped data
//
private static readonly byte[] envDataKeyTrns = Base64.Decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQAxgcQwgcECAQAwKjAlMRYwFAYDVQQKEw1Cb3Vu"
+ "Y3kgQ2FzdGxlMQswCQYDVQQGEwJBVQIBCjANBgkqhkiG9w0BAQEFAASBgC5vdGrB"
+ "itQSGwifLf3KwPILjaB4WEXgT/IIO1KDzrsbItCJsMA0Smq2y0zptxT0pSRL6JRg"
+ "NMxLk1ySnrIrvGiEPLMR1zjxlT8yQ6VLX+kEoK43ztd1aaLw0oBfrcXcLN7BEpZ1"
+ "TIdjlBfXIOx1S88WY1MiYqJJFc3LMwRUaTEDMIAGCSqGSIb3DQEHATAdBglghkgB"
+ "ZQMEARYEEAfxLMWeaBOTTZQwUq0Y5FuggAQgwOJhL04rjSZCBCSOv5i5XpFfGsOd"
+ "YSHSqwntGpFqCx4AAAAAAAAAAAAA");
private static readonly byte[] envDataKEK = Base64.Decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQIxUqJQAgEEMAcEBQECAwQFMBAGCyqGSIb3DQEJE"
+ "AMHAgE6BDC7G/HyUPilIrin2Yeajqmj795VoLWETRnZAAFcAiQdoQWyz+oCh6WY/H"
+ "jHHi+0y+cwgAYJKoZIhvcNAQcBMBQGCCqGSIb3DQMHBAiY3eDBBbF6naCABBiNdzJb"
+ "/v6+UZB3XXKipxFDUpz9GyjzB+gAAAAAAAAAAAAA");
private static readonly byte[] envDataNestedNDEF = Base64.Decode(
"MIAGCSqGSIb3DQEHA6CAMIACAQAxge8wgewCAQAwgZUwgY8xKDAmBgNVBAoMH1RoZSBMZWdpb24g"
+ "b2YgdGhlIEJvdW5jeSBDYXN0bGUxLzAtBgkqhkiG9w0BCQEWIGZlZWRiYWNrLWNyeXB0b0Bib3Vu"
+ "Y3ljYXN0bGUub3JnMREwDwYDVQQIDAhWaWN0b3JpYTESMBAGA1UEBwwJTWVsYm91cm5lMQswCQYD"
+ "VQQGEwJBVQIBATANBgkqhkiG9w0BAQEFAARABIXMd8xiTyWDKO/LQfvdGYTPW3I9oSQWwtm4OIaN"
+ "VINpfY2lfwTvbmE6VXiLKeALC0dMBV8z7DEM9hE0HVmvLDCABgkqhkiG9w0BBwEwHQYJYIZIAWUD"
+ "BAECBBB32ko6WrVxDTqwUYEpV6IUoIAEggKgS6RowrhNlmWWI13zxD/lryxkZ5oWXPUfNiUxYX/P"
+ "r5iscW3s8VKJKUpJ4W5SNA7JGL4l/5LmSnJ4Qu/xzxcoH4r4vmt75EDE9p2Ob2Xi1NuSFAZubJFc"
+ "Zlnp4e05UHKikmoaz0PbiAi277sLQlK2FcVsntTYVT00y8+IwuuQu0ATVqkXC+VhfjV/sK6vQZnw"
+ "2rQKedZhLB7B4dUkmxCujb/UAq4lgSpLMXg2P6wMimTczXyQxRiZxPeI4ByCENjkafXbfcJft2eD"
+ "gv1DEDdYM5WrW9Z75b4lmJiOJ/xxDniHCvum7KGXzpK1d1mqTlpzPC2xoz08/MO4lRf5Mb0bYdq6"
+ "CjMaYqVwGsYryp/2ayX+d8H+JphEG+V9Eg8uPcDoibwhDI4KkoyGHstPw5bxcy7vVFt7LXUdNjJc"
+ "K1wxaUKEXDGKt9Vj93FnBTLMX0Pc9HpueV5o1ipX34dn/P3HZB9XK8ScbrE38B1VnIgylStnhVFO"
+ "Cj9s7qSVqI2L+xYHJRHsxaMumIRnmRuOqdXDfIo28EZAnFtQ/b9BziMGVvAW5+A8h8s2oazhSmK2"
+ "23ftV7uv98ScgE8fCd3PwT1kKJM83ThTYyBzokvMfPYCCvsonMV+kTWXhWcwjYTS4ukrpR452ZdW"
+ "l3aJqDnzobt5FK4T8OGciOj+1PxYFZyRmCuafm2Dx6o7Et2Tu/T5HYvhdY9jHyqtDl2PXH4CTnVi"
+ "gA1YOAArjPVmsZVwAM3Ml46uyXXhcsXwQ1X0Tv4D+PSa/id4UQ2cObOw8Cj1eW2GB8iJIZVqkZaU"
+ "XBexqgWYOIoxjqODSeoZKiBsTK3c+oOUBqBDueY1i55swE2o6dDt95FluX6iyr/q4w2wLt3upY1J"
+ "YL+TuvZxAKviuAczMS1bAAAAAAAAAAAAAA==");
//
// signed data
//
private static readonly byte[] signedData = Base64.Decode(
"MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAaCA"
+ "JIAEDEhlbGxvIFdvcmxkIQAAAAAAAKCCBGIwggINMIIBdqADAgECAgEBMA0GCSqG"
+ "SIb3DQEBBAUAMCUxFjAUBgNVBAoTDUJvdW5jeSBDYXN0bGUxCzAJBgNVBAYTAkFV"
+ "MB4XDTA0MTAyNDA0MzA1OFoXDTA1MDIwMTA0MzA1OFowJTEWMBQGA1UEChMNQm91"
+ "bmN5IENhc3RsZTELMAkGA1UEBhMCQVUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ"
+ "AoGBAJj3OAshAOgDmPcYZ1jdNSuhOHRH9VhC/PG17FdiInVGc2ulJhEifEQga/uq"
+ "ZCpSd1nHsJUZKm9k1bVneWzC0941i9Znfxgb2jnXXsa5kwB2KEVESrOWsRjSRtnY"
+ "iLgqBG0rzpaMn5A5ntu7N0406EesBhe19cjZAageEHGZDbufAgMBAAGjTTBLMB0G"
+ "A1UdDgQWBBR/iHNKOo6f4ByWFFywRNZ65XSr1jAfBgNVHSMEGDAWgBR/iHNKOo6f"
+ "4ByWFFywRNZ65XSr1jAJBgNVHRMEAjAAMA0GCSqGSIb3DQEBBAUAA4GBAFMJJ7QO"
+ "pHo30bnlQ4Ny3PCnK+Se+Gw3TpaYGp84+a8fGD9Dme78G6NEsgvpFGTyoLxvJ4CB"
+ "84Kzys+1p2HdXzoZiyXAer5S4IwptE3TxxFwKyj28cRrM6dK47DDyXUkV0qwBAMN"
+ "luwnk/no4K7ilzN2MZk5l7wXyNa9yJ6CHW6dMIICTTCCAbagAwIBAgIBAjANBgkq"
+ "hkiG9w0BAQQFADAlMRYwFAYDVQQKEw1Cb3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJB"
+ "VTAeFw0wNDEwMjQwNDMwNTlaFw0wNTAyMDEwNDMwNTlaMGUxGDAWBgNVBAMTD0Vy"
+ "aWMgSC4gRWNoaWRuYTEkMCIGCSqGSIb3DQEJARYVZXJpY0Bib3VuY3ljYXN0bGUu"
+ "b3JnMRYwFAYDVQQKEw1Cb3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJBVTCBnzANBgkq"
+ "hkiG9w0BAQEFAAOBjQAwgYkCgYEAm+5CnGU6W45iUpCsaGkn5gDruZv3j/o7N6ag"
+ "mRZhikaLG2JF6ECaX13iioVJfmzBsPKxAACWwuTXCoSSXG8viK/qpSHwJpfQHYEh"
+ "tcC0CxIqlnltv3KQAGwh/PdwpSPvSNnkQBGvtFq++9gnXDBbynfP8b2L2Eis0X9U"
+ "2y6gFiMCAwEAAaNNMEswHQYDVR0OBBYEFEAmOksnF66FoQm6IQBVN66vJo1TMB8G"
+ "A1UdIwQYMBaAFH+Ic0o6jp/gHJYUXLBE1nrldKvWMAkGA1UdEwQCMAAwDQYJKoZI"
+ "hvcNAQEEBQADgYEAEeIjvNkKMPU/ZYCu1TqjGZPEqi+glntg2hC/CF0oGyHFpMuG"
+ "tMepF3puW+uzKM1s61ar3ahidp3XFhr/GEU/XxK24AolI3yFgxP8PRgUWmQizTQX"
+ "pWUmhlsBe1uIKVEfNAzCgtYfJQ8HJIKsUCcdWeCKVKs4jRionsek1rozkPExggEv"
+ "MIIBKwIBATAqMCUxFjAUBgNVBAoTDUJvdW5jeSBDYXN0bGUxCzAJBgNVBAYTAkFV"
+ "AgECMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqG"
+ "SIb3DQEJBTEPFw0wNDEwMjQwNDMwNTlaMCMGCSqGSIb3DQEJBDEWBBQu973mCM5U"
+ "BOl9XwQvlfifHCMocTANBgkqhkiG9w0BAQEFAASBgGHbe3/jcZu6b/erRhc3PEji"
+ "MUO8mEIRiNYBr5/vFNhkry8TrGfOpI45m7gu1MS0/vdas7ykvidl/sNZfO0GphEI"
+ "UaIjMRT3U6yuTWF4aLpatJbbRsIepJO/B2kdIAbV5SCbZgVDJIPOR2qnruHN2wLF"
+ "a+fEv4J8wQ8Xwvk0C8iMAAAAAAAA");
private static void Touch(object o)
{
}
private ITestResult CompressionTest()
{
try
{
ContentInfo info = ContentInfo.GetInstance(
Asn1Object.FromByteArray(compData));
CompressedData data = CompressedData.GetInstance(info.Content);
data = new CompressedData(data.CompressionAlgorithmIdentifier, data.EncapContentInfo);
info = new ContentInfo(CmsObjectIdentifiers.CompressedData, data);
if (!Arrays.AreEqual(info.GetEncoded(), compData))
{
return new SimpleTestResult(false, Name + ": CMS compression failed to re-encode");
}
return new SimpleTestResult(true, Name + ": Okay");
}
catch (Exception e)
{
return new SimpleTestResult(false, Name + ": CMS compression failed - " + e.ToString(), e);
}
}
private ITestResult EnvelopedTest()
{
try
{
// Key trans
ContentInfo info = ContentInfo.GetInstance(
Asn1Object.FromByteArray(envDataKeyTrns));
EnvelopedData envData = EnvelopedData.GetInstance(info.Content);
Asn1Set s = envData.RecipientInfos;
if (s.Count != 1)
{
return new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong number of recipients");
}
RecipientInfo recip = RecipientInfo.GetInstance(s[0]);
if (recip.Info is KeyTransRecipientInfo)
{
KeyTransRecipientInfo inf = KeyTransRecipientInfo.GetInstance(recip.Info);
inf = new KeyTransRecipientInfo(inf.RecipientIdentifier, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);
s = new DerSet(new RecipientInfo(inf));
}
else
{
return new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong recipient type");
}
envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
info = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);
if (!Arrays.AreEqual(info.GetEncoded(), envDataKeyTrns))
{
return new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped failed to re-encode");
}
// KEK
info = ContentInfo.GetInstance(
Asn1Object.FromByteArray(envDataKEK));
envData = EnvelopedData.GetInstance(info.Content);
s = envData.RecipientInfos;
if (s.Count != 1)
{
return new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong number of recipients");
}
recip = RecipientInfo.GetInstance(s[0]);
if (recip.Info is KekRecipientInfo)
{
KekRecipientInfo inf = KekRecipientInfo.GetInstance(recip.Info);
inf = new KekRecipientInfo(inf.KekID, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);
s = new DerSet(new RecipientInfo(inf));
}
else
{
return new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong recipient type");
}
envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
info = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);
if (!Arrays.AreEqual(info.GetEncoded(), envDataKEK))
{
return new SimpleTestResult(false, Name + ": CMS KEK enveloped failed to re-encode");
}
// Nested NDEF problem
Asn1StreamParser asn1In = new Asn1StreamParser(new MemoryStream(envDataNestedNDEF, false));
ContentInfoParser ci = new ContentInfoParser((Asn1SequenceParser)asn1In.ReadObject());
EnvelopedDataParser ed = new EnvelopedDataParser((Asn1SequenceParser)ci
.GetContent(Asn1Tags.Sequence));
Touch(ed.Version);
ed.GetOriginatorInfo();
ed.GetRecipientInfos().ToAsn1Object();
EncryptedContentInfoParser eci = ed.GetEncryptedContentInfo();
Touch(eci.ContentType);
Touch(eci.ContentEncryptionAlgorithm);
Stream dataIn = ((Asn1OctetStringParser)eci.GetEncryptedContent(Asn1Tags.OctetString))
.GetOctetStream();
Streams.Drain(dataIn);
dataIn.Close();
// Test data doesn't have unprotected attrs, bug was being thrown by this call
Asn1SetParser upa = ed.GetUnprotectedAttrs();
if (upa != null)
{
upa.ToAsn1Object();
}
return new SimpleTestResult(true, Name + ": Okay");
}
catch (Exception e)
{
return new SimpleTestResult(false, Name + ": CMS enveloped failed - " + e.ToString(), e);
}
}
private ITestResult SignedTest()
{
try
{
ContentInfo info = ContentInfo.GetInstance(
Asn1Object.FromByteArray(signedData));
SignedData sData = SignedData.GetInstance(info.Content);
sData = new SignedData(sData.DigestAlgorithms, sData.EncapContentInfo, sData.Certificates, sData.CRLs, sData.SignerInfos);
info = new ContentInfo(CmsObjectIdentifiers.SignedData, sData);
if (!Arrays.AreEqual(info.GetEncoded(), signedData))
{
return new SimpleTestResult(false, Name + ": CMS signed failed to re-encode");
}
return new SimpleTestResult(true, Name + ": Okay");
}
catch (Exception e)
{
return new SimpleTestResult(false, Name + ": CMS signed failed - " + e.ToString(), e);
}
}
public ITestResult Perform()
{
ITestResult res = CompressionTest();
if (!res.IsSuccessful())
{
return res;
}
res = EnvelopedTest();
if (!res.IsSuccessful())
{
return res;
}
return SignedTest();
}
public string Name
{
get { return "CMS"; }
}
public static void Main(
string[] args)
{
ITest test = new CmsTest();
ITestResult result = test.Perform();
Console.WriteLine(result);
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
using System;
namespace Versioning
{
public class HeaderData : Sage_Container, IData, IMove, IFindFirstNext
{
/* Autogenerated by sage_wrapper_generator.pl */
SageDataObject110.HeaderData hd11;
SageDataObject120.HeaderData hd12;
SageDataObject130.HeaderData hd13;
SageDataObject140.HeaderData hd14;
SageDataObject150.HeaderData hd15;
SageDataObject160.HeaderData hd16;
SageDataObject170.HeaderData hd17;
public HeaderData(object inner, int version)
: base(version) {
switch (m_version) {
case 11: {
hd11 = (SageDataObject110.HeaderData)inner;
m_fields = new Fields(hd11.Fields, m_version);
return;
}
case 12: {
hd12 = (SageDataObject120.HeaderData)inner;
m_fields = new Fields(hd12.Fields, m_version);
return;
}
case 13: {
hd13 = (SageDataObject130.HeaderData)inner;
m_fields = new Fields(hd13.Fields, m_version);
return;
}
case 14: {
hd14 = (SageDataObject140.HeaderData)inner;
m_fields = new Fields(hd14.Fields, m_version);
return;
}
case 15: {
hd15 = (SageDataObject150.HeaderData)inner;
m_fields = new Fields(hd15.Fields, m_version);
return;
}
case 16: {
hd16 = (SageDataObject160.HeaderData)inner;
m_fields = new Fields(hd16.Fields, m_version);
return;
}
case 17: {
hd17 = (SageDataObject170.HeaderData)inner;
m_fields = new Fields(hd17.Fields, m_version);
return;
}
default: throw new InvalidOperationException("m_version");
}
}
/* Autogenerated with data_generator.pl */
const string ACCOUNT_REF = "ACCOUNT_REF";
const string HEADERDATA = "HeaderData";
public bool Open(OpenMode mode) {
bool ret;
switch (m_version) {
case 11: {
ret = hd11.Open((SageDataObject110.OpenMode)mode);
break;
}
case 12: {
ret = hd12.Open((SageDataObject120.OpenMode)mode);
break;
}
case 13: {
ret = hd13.Open((SageDataObject130.OpenMode)mode);
break;
}
case 14: {
ret = hd14.Open((SageDataObject140.OpenMode)mode);
break;
}
case 15: {
ret = hd15.Open((SageDataObject150.OpenMode)mode);
break;
}
case 16: {
ret = hd16.Open((SageDataObject160.OpenMode)mode);
break;
}
case 17: {
ret = hd17.Open((SageDataObject170.OpenMode)mode);
break;
}
default: throw new InvalidOperationException("m_version");
}
return ret;
}
public void Close() {
switch (m_version) {
case 11: {
hd11.Close();
break;
}
case 12: {
hd12.Close();
break;
}
case 13: {
hd13.Close();
break;
}
case 14: {
hd14.Close();
break;
}
case 15: {
hd15.Close();
break;
}
case 16: {
hd16.Close();
break;
}
case 17: {
hd17.Close();
break;
}
default: throw new InvalidOperationException("m_version");
}
}
public bool Read(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = hd11.Read(IRecNo);
break;
}
case 12: {
ret = hd12.Read(IRecNo);
break;
}
case 13: {
ret = hd13.Read(IRecNo);
break;
}
case 14: {
ret = hd14.Read(IRecNo);
break;
}
case 15: {
ret = hd15.Read(IRecNo);
break;
}
case 16: {
ret = hd16.Read(IRecNo);
break;
}
case 17: {
ret = hd17.Read(IRecNo);
break;
}
default: throw new InvalidOperationException("m_version");
}
return ret;
}
public bool Write(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = hd11.Write(IRecNo);
break;
}
case 12: {
ret = hd12.Write(IRecNo);
break;
}
case 13: {
ret = hd13.Write(IRecNo);
break;
}
case 14: {
ret = hd14.Write(IRecNo);
break;
}
case 15: {
ret = hd15.Write(IRecNo);
break;
}
case 16: {
ret = hd16.Write(IRecNo);
break;
}
case 17: {
ret = hd17.Write(IRecNo);
break;
}
default: throw new InvalidOperationException("m_version");
}
return ret;
}
public bool Seek(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = hd11.Seek(IRecNo);
break;
}
case 12: {
ret = hd12.Seek(IRecNo);
break;
}
case 13: {
ret = hd13.Seek(IRecNo);
break;
}
case 14: {
ret = hd14.Seek(IRecNo);
break;
}
case 15: {
ret = hd15.Seek(IRecNo);
break;
}
case 16: {
ret = hd16.Seek(IRecNo);
break;
}
case 17: {
ret = hd17.Seek(IRecNo);
break;
}
default: throw new InvalidOperationException("m_version");
}
return ret;
}
public bool Lock(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = hd11.Lock(IRecNo);
break;
}
case 12: {
ret = hd12.Lock(IRecNo);
break;
}
case 13: {
ret = hd13.Lock(IRecNo);
break;
}
case 14: {
ret = hd14.Lock(IRecNo);
break;
}
case 15: {
ret = hd15.Lock(IRecNo);
break;
}
case 16: {
ret = hd16.Lock(IRecNo);
break;
}
case 17: {
ret = hd17.Lock(IRecNo);
break;
}
default: throw new InvalidOperationException("m_version");
}
return ret;
}
public bool Unlock(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = hd11.Unlock(IRecNo);
break;
}
case 12: {
ret = hd12.Unlock(IRecNo);
break;
}
case 13: {
ret = hd13.Unlock(IRecNo);
break;
}
case 14: {
ret = hd14.Unlock(IRecNo);
break;
}
case 15: {
ret = hd15.Unlock(IRecNo);
break;
}
case 16: {
ret = hd16.Unlock(IRecNo);
break;
}
case 17: {
ret = hd17.Unlock(IRecNo);
break;
}
default: throw new InvalidOperationException("m_version");
}
return ret;
}
public bool FindFirst(object varField, object varSearch) {
bool ret;
switch (m_version) {
case 11: {
ret = hd11.FindFirst(varField, varSearch);
break;
}
case 12: {
ret = hd12.FindFirst(varField, varSearch);
break;
}
case 13: {
ret = hd13.FindFirst(varField, varSearch);
break;
}
case 14: {
ret = hd14.FindFirst(varField, varSearch);
break;
}
case 15: {
ret = hd15.FindFirst(varField, varSearch);
break;
}
case 16: {
ret = hd16.FindFirst(varField, varSearch);
break;
}
case 17: {
ret = hd17.FindFirst(varField, varSearch);
break;
}
default: throw new InvalidOperationException("m_version");
}
return ret;
}
public bool FindNext(object varField, object varSearch) {
bool ret;
switch (m_version) {
case 11: {
ret = hd11.FindNext(varField, varSearch);
break;
}
case 12: {
ret = hd12.FindNext(varField, varSearch);
break;
}
case 13: {
ret = hd13.FindNext(varField, varSearch);
break;
}
case 14: {
ret = hd14.FindNext(varField, varSearch);
break;
}
case 15: {
ret = hd15.FindNext(varField, varSearch);
break;
}
case 16: {
ret = hd16.FindNext(varField, varSearch);
break;
}
case 17: {
ret = hd17.FindNext(varField, varSearch);
break;
}
default: throw new InvalidOperationException("m_version");
}
return ret;
}
public int Count {
get {
int ret;
switch (m_version) {
case 11: {
ret = hd11.Count;
break;
}
case 12: {
ret = hd12.Count;
break;
}
case 13: {
ret = hd13.Count;
break;
}
case 14: {
ret = hd14.Count;
break;
}
case 15: {
ret = hd15.Count;
break;
}
case 16: {
ret = hd16.Count;
break;
}
case 17: {
ret = hd17.Count;
break;
}
default: throw new InvalidOperationException("m_version");
}
return ret;
}
}
public bool MoveFirst() {
switch (m_version) {
case 11:
return hd11.MoveFirst();
case 12:
return hd12.MoveFirst();
case 13:
return hd13.MoveFirst();
case 14:
return hd14.MoveFirst();
case 15:
return hd15.MoveFirst();
case 16:
return hd16.MoveFirst();
case 17:
return hd17.MoveFirst();
}
throw new InvalidOperationException();
}
public bool MoveNext() {
switch (m_version) {
case 11:
return hd11.MoveNext();
case 12:
return hd12.MoveNext();
case 13:
return hd13.MoveNext();
case 14:
return hd14.MoveNext();
case 15:
return hd15.MoveNext();
case 16:
return hd16.MoveNext();
case 17:
return hd17.MoveNext();
}
throw new InvalidOperationException();
}
public bool MoveLast() {
switch (m_version) {
case 11:
return hd11.MoveLast();
case 12:
return hd12.MoveLast();
case 13:
return hd13.MoveLast();
case 14:
return hd14.MoveLast();
case 15:
return hd15.MoveLast();
case 16:
return hd16.MoveLast();
case 17:
return hd17.MoveLast();
}
throw new InvalidOperationException();
}
public bool MovePrev() {
switch (m_version) {
case 11:
return hd11.MovePrev();
case 12:
return hd12.MovePrev();
case 13:
return hd13.MovePrev();
case 14:
return hd14.MovePrev();
case 15:
return hd15.MovePrev();
case 16:
return hd16.MovePrev();
case 17:
return hd17.MovePrev();
}
throw new InvalidOperationException();
}
public SplitData Link {
get {
object obj;
switch (m_version) {
case 11:
obj = hd11.Link; break;
case 12:
obj = hd12.Link; break;
case 13:
obj = hd13.Link; break;
case 14:
obj = hd14.Link; break;
case 15:
obj = hd15.Link; break;
case 16:
obj = hd16.Link; break;
case 17:
obj = hd17.Link; break;
default:
throw new InvalidOperationException();
}
return new SplitData(obj, m_version);
}
}
}
}
| |
// * **************************************************************************
// * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C.
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// * **************************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using FluentAssert;
using JetBrains.Annotations;
using NUnit.Framework;
namespace MvbaCore.Tests.Extensions
{
[UsedImplicitly]
public class IEnumerableTExtensionsTest
{
public class OtherItem : ITestItem
{
public int KeyId { get; set; }
public string Name { get; set; }
}
public abstract class SelectWhereNotInOtherTestBase<TListAType, TListBType>
where TListAType : ITestItem, new()
where TListBType : ITestItem, new()
{
protected abstract IEnumerable<TListAType> CallExtension(IEnumerable<TListAType> listA, IEnumerable<TListBType> listB);
[Test]
public void Should_return_empty_if_the_list_being_selected_from_is_empty()
{
var listA = new List<TListAType>();
var listB = new List<TListBType>
{
new TListBType()
};
var result = CallExtension(listA, listB);
Assert.IsNotNull(result);
Assert.IsFalse(result.Any());
}
[Test]
public void Should_return_only_the_items_in_list_being_selected_from_that_are_not_in_the_other_list()
{
var itemA1 = new TListAType
{
KeyId = 1,
Name = "A"
};
var itemA2 = new TListAType
{
KeyId = 2,
Name = "A & B"
};
var itemA3 = new TListAType
{
KeyId = 3,
Name = "A & B"
};
var itemB2 = new TListBType
{
KeyId = 2,
Name = "A & B"
};
var itemB3 = new TListBType
{
KeyId = 3,
Name = "A & B"
};
var itemB4 = new TListBType
{
KeyId = 4,
Name = "B"
};
var listA = new List<TListAType>
{
itemA1,
itemA2,
itemA3
};
var listB = new List<TListBType>
{
itemB2,
itemB3,
itemB4
};
var result = CallExtension(listA, listB).ToList();
Assert.IsNotNull(result);
Assert.IsTrue(result.Any());
Assert.IsTrue(result.All(item => item.Name == "A"));
}
[Test]
public void Should_return_the_list_being_selected_from_if_the_other_list_is_empty()
{
var listA = new List<TListAType>
{
new TListAType()
};
var listB = new List<TListBType>();
var result = CallExtension(listA, listB);
Assert.IsNotNull(result);
Assert.IsTrue(result.Any());
}
[Test]
public void Should_return_the_list_being_selected_from_if_the_other_list_is_null()
{
var listA = new List<TListAType>
{
new TListAType()
};
const List<TListBType> listB = null;
var result = CallExtension(listA, listB);
Assert.IsNotNull(result);
Assert.IsTrue(result.Any());
}
[Test]
public void Should_throw_an_exception_if_the_list_being_selected_from_is_null()
{
const List<TListAType> listA = null;
var listB = new List<TListBType>();
Assert.Throws<ArgumentNullException>(() => CallExtension(listA, listB));
}
}
public class TestItem : ITestItem
{
public int KeyId { get; set; }
public string Name { get; set; }
}
[TestFixture]
public class When_asked_if_an_IEnumerable_T_IsNullOrEmpty
{
[Test]
public void Should_return_false_if_the_input_contains_items()
{
IList<int> input = new List<int>
{
6
};
input.IsNullOrEmpty().ShouldBeFalse();
}
[Test]
public void Should_return_true_if_the_input_is_empty()
{
IList<int> input = new List<int>();
input.IsNullOrEmpty().ShouldBeTrue();
}
[Test]
public void Should_return_true_if_the_input_is_null()
{
const IList<int> input = null;
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
input.IsNullOrEmpty().ShouldBeTrue();
}
}
[TestFixture]
public class When_asked_to_SelectWhereInOther
{
[Test]
public void Should_return_empty_if_the_list_being_selected_from_is_empty()
{
var itemA = new List<TestItem>();
var itemB = new List<TestItem>
{
new TestItem()
};
var result = itemA.Intersect(itemB, a => a.KeyId);
Assert.IsNotNull(result);
Assert.IsFalse(result.Any());
}
[Test]
public void Should_return_empty_if_the_other_list_is_empty()
{
var itemA = new List<TestItem>
{
new TestItem()
};
var itemB = new List<TestItem>();
var result = itemA.Intersect(itemB, a => a.KeyId);
Assert.IsNotNull(result);
Assert.IsFalse(result.Any());
}
[Test]
public void Should_return_empty_if_the_other_list_is_null()
{
var itemA = new List<TestItem>
{
new TestItem()
};
const List<TestItem> itemB = null;
var result = itemA.Intersect(itemB, a => a.KeyId);
Assert.IsNotNull(result);
Assert.IsFalse(result.Any());
}
[Test]
public void Should_return_only_the_items_in_list_being_selected_from_that_are_also_in_the_other_list()
{
var item1 = new TestItem
{
KeyId = 1,
Name = "A"
};
var item2 = new TestItem
{
KeyId = 2,
Name = "A & B"
};
var item3 = new TestItem
{
KeyId = 3,
Name = "A & B"
};
var item4 = new TestItem
{
KeyId = 4,
Name = "B"
};
var itemA = new List<TestItem>
{
item1,
item2,
item3
};
var itemB = new List<TestItem>
{
item2,
item3,
item4
};
var result = itemA.Intersect(itemB, a => a.KeyId).ToList();
Assert.IsNotNull(result);
Assert.IsTrue(result.Any());
Assert.IsTrue(result.All(item => item.Name == "A & B"));
}
[Test]
public void Should_throw_an_exception_if_the_list_being_selected_from_is_null()
{
const List<TestItem> itemA = null;
var itemB = new List<TestItem>();
// ReSharper disable once AssignNullToNotNullAttribute
Assert.Throws<ArgumentNullException>(() => itemA.Intersect(itemB, a => a.KeyId));
}
}
[TestFixture]
public class When_asked_to_SelectWhereNotInOther_where_T_is_class : SelectWhereNotInOtherTestBase<TestItem, TestItem>
{
protected override IEnumerable<TestItem> CallExtension(IEnumerable<TestItem> listA, IEnumerable<TestItem> listB)
{
return listA.Except(listB, a => a.KeyId);
}
}
[TestFixture]
public class When_asked_to_SelectWhereNotInOther_where_lists_contain_different_types :
SelectWhereNotInOtherTestBase<TestItem, OtherItem>
{
protected override IEnumerable<TestItem> CallExtension(IEnumerable<TestItem> listA, IEnumerable<OtherItem> listB)
{
return listA.Except(listB, a => a.KeyId, b => b.KeyId, b => b == null);
}
}
[TestFixture]
public class When_asked_to_SelectWhereNotInOther_where_lists_contain_the_same_type :
SelectWhereNotInOtherTestBase<TestItem, TestItem>
{
protected override IEnumerable<TestItem> CallExtension(IEnumerable<TestItem> listA, IEnumerable<TestItem> listB)
{
return listA.Except(listB, a => a.KeyId, a => a == null);
}
}
[TestFixture]
public class When_asked_to_convert_an_enumerable_list_of_items_to_page_sets
{
private int _firstPageSize;
private List<int> _listOfItems;
private int _nthPageSize;
[SetUp]
public void SetUp()
{
_listOfItems = new List<int>();
_firstPageSize = 3;
_nthPageSize = 5;
}
[Test]
public void Should_return_a_set_of_pages()
{
var pageSets = _listOfItems.ToPageSets(_firstPageSize, _nthPageSize);
pageSets.ShouldNotBeNull();
}
[Test]
public void Should_return_an_empty_set_of_pages_when_the_list_is_null()
{
_listOfItems = null;
var pageSets = _listOfItems.ToPageSets(_firstPageSize, _nthPageSize);
pageSets.ShouldNotBeNull();
}
[Test]
public void Should_return_multiple_pages_when_the_list_is_longer_than_the__firstPageSize()
{
_listOfItems = new List<int>
{
1,
2,
3,
4,
5,
6,
7,
8,
9
};
var pageSets = _listOfItems.ToPageSets(_firstPageSize, _nthPageSize);
pageSets.Count().ShouldBeGreaterThan(1);
}
[Test]
public void Should_return_multiple_pages_with_the_last_page_size_equal_to___nthPageSize()
{
_listOfItems = new List<int>
{
1,
2,
3,
4,
5,
6,
7,
8
};
var pageSets = _listOfItems.ToPageSets(_firstPageSize, _nthPageSize);
var last = pageSets.Last().ToList();
last.Count.ShouldBeEqualTo(_nthPageSize);
last[0].ShouldBeEqualTo(_listOfItems[3]);
last[1].ShouldBeEqualTo(_listOfItems[4]);
last[2].ShouldBeEqualTo(_listOfItems[5]);
last[3].ShouldBeEqualTo(_listOfItems[6]);
last[4].ShouldBeEqualTo(_listOfItems[7]);
}
[Test]
public void Should_return_multiple_pages_with_the_last_page_size_equal_to_the_remaining_elements_in_the_list()
{
_listOfItems = new List<int>
{
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
};
var pageSets = _listOfItems.ToPageSets(_firstPageSize, _nthPageSize);
pageSets.Last().Count.ShouldBeEqualTo(_listOfItems.Count - (_firstPageSize + _nthPageSize));
}
[Test]
public void Should_return_multiple_pages_with_the_pages_other_than_first_and_last_page_equal_to__nthPageSize()
{
_listOfItems = new List<int>
{
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
};
var pageSets = _listOfItems.ToPageSets(_firstPageSize, _nthPageSize);
pageSets.Skip(1).First().Count.ShouldBeEqualTo(_nthPageSize);
}
[Test]
public void Should_return_one_page_if_the_length_of_the_list_is_equal_to__firstPageSize()
{
_listOfItems = new List<int>
{
1,
2,
3
};
var pageSets = _listOfItems.ToPageSets(_firstPageSize, _nthPageSize).ToList();
pageSets.First().Count.ShouldBeEqualTo(_firstPageSize);
var first = pageSets.First().ToList();
first.Count.ShouldBeEqualTo(_firstPageSize);
first[0].ShouldBeEqualTo(_listOfItems[0]);
first[1].ShouldBeEqualTo(_listOfItems[1]);
first[2].ShouldBeEqualTo(_listOfItems[2]);
}
[Test]
public void Should_return_one_page_if_the_length_of_the_list_is_less_than__firstPageSize()
{
_listOfItems = new List<int>
{
1,
2
};
var pageSets = _listOfItems.ToPageSets(_firstPageSize, _nthPageSize);
pageSets.First().Count.ShouldBeEqualTo(_listOfItems.Count);
}
}
[TestFixture]
public class When_asked_to_flatten_ranges
{
private List<Range<string>> _ranges;
private List<KeyValuePair<int, string>> _result;
[Test]
public void Given_a_list_with_1_range_having_end_equal_to_start_plus_1_should_return_2_results()
{
Test.Verify(
with_a_list_of_ranges,
that_has_one_range,
having_end_equal_to_start_plus_1,
when_asked_to_flatten,
should_return_2_result,
first_result_should_have_key_equal_to_range_start,
last_result_should_have_key_equal_to_range_end,
all_results_should_have_value_equal_to_range_payload
);
}
[Test]
public void Given_a_list_with_1_range_having_end_equal_to_start_should_return_1_result()
{
Test.Verify(
with_a_list_of_ranges,
that_has_one_range,
having_end_equal_to_start,
when_asked_to_flatten,
should_return_1_result,
first_result_should_have_key_equal_to_range_start,
all_results_should_have_value_equal_to_range_payload
);
}
[Test]
public void Given_an_empty_list_of_ranges_should_return_empty_result()
{
Test.Verify(
with_a_list_of_ranges,
that_is_empty,
when_asked_to_flatten,
should_return_empty_result
);
}
private void all_results_should_have_value_equal_to_range_payload()
{
_result.All(x => x.Value == _ranges.Last().Payload).ShouldBeTrue();
}
private void first_result_should_have_key_equal_to_range_start()
{
_result.First().Key.ShouldBeEqualTo(_ranges.Last().Start);
}
private void having_end_equal_to_start()
{
var range = _ranges.Last();
range.Start = 23;
range.End = range.Start;
}
private void having_end_equal_to_start_plus_1()
{
var range = _ranges.First();
range.Start = 42;
range.End = range.Start + 1;
}
private void last_result_should_have_key_equal_to_range_end()
{
_result.Last().Key.ShouldBeEqualTo(_ranges.First().End);
}
private void should_return_1_result()
{
_result.Count.ShouldBeEqualTo(1);
}
private void should_return_2_result()
{
_result.Count.ShouldBeEqualTo(2);
}
private void should_return_empty_result()
{
_result.ShouldBeEmpty();
}
private void that_has_one_range()
{
_ranges.Add(new Range<string>
{
Payload = _ranges.Count.ToString()
});
}
private void that_is_empty()
{
_ranges.Clear();
}
private void when_asked_to_flatten()
{
_result = _ranges.FlattenRanges().ToList();
}
private void with_a_list_of_ranges()
{
_ranges = new List<Range<string>>();
}
}
[TestFixture]
public class When_asked_to_group_a_list
{
[Test]
public void Given_items_with_a_header_should_be_grouped__should_group_the_items()
{
var input = new[] { "a", "b", "b", "a", "c", "c", "a" };
var grouped = input.Group((current, previous) => current == previous || current != "a");
var sb = new StringBuilder();
foreach (var group in grouped)
{
sb.Append(string.Join(", ", group));
sb.Append('|');
}
sb.ToString().ShouldBeEqualTo(@"a, b, b|a, c, c|a|");
}
[Test]
public void Given_same_items_together_should_be_grouped__should_group_the_items()
{
var input = new[] { "a", "b", "b", "b", "c", "c", "d" };
var grouped = input.Group((current, previous) => current == previous);
var sb = new StringBuilder();
foreach (var group in grouped)
{
sb.Append(string.Join(", ", group));
sb.Append('|');
}
sb.ToString().ShouldBeEqualTo(@"a|b, b, b|c, c|d|");
}
}
[TestFixture]
public class When_asked_to_join_an_enumerable_list_of_items
{
[Test]
public void Should_return_a_string_containing_the_list_items_separated_by_the_delimiter()
{
const int one = 1;
const int item = 3;
var items = new List<int>
{
one,
item
};
const string delimiter = "','";
var expect = one + delimiter + item;
Assert.AreEqual(expect, items.Join(delimiter));
}
[Test]
public void Should_return_an_empty_string_if_the_list_is_empty()
{
var items = new List<string>();
Assert.IsEmpty(items.Join("x"));
}
[Test]
public void Should_return_an_empty_string_if_the_list_is_null()
{
const List<string> items = null;
Assert.IsEmpty(items.Join("x"));
}
[Test]
public void Should_use_empty_string_if_the_delimiter_is_null()
{
const int one = 1;
const int item = 3;
var items = new List<int>
{
one,
item
};
const string delimiter = null;
var expect = one + "" + item;
Assert.AreEqual(expect, items.Join(delimiter));
}
}
[TestFixture]
public class When_asked_to_memoize_an_IEnumerable
{
[Test]
public void Given_maximum_1_and_1_is_read__should_be_able_to_re_stream_the_entire_enumerable()
{
var count = new[] { 1 };
var memoized = Generate(count).Memoize(1);
var first = memoized.First();
first.ShouldBeEqualTo(1);
var secondSet = memoized.ToList();
secondSet.ShouldContainAllInOrder(Enumerable.Range(1, 10));
}
[Test]
public void Given_maximum_1_and_a_set_of_2_is_read_and_a_set_of_1_is_read__should_return_the_initial_values_from_the_input_each_time()
{
var count = new[] { 1 };
var memoized = Generate(count).Memoize(1);
var firstSet = memoized.Take(2).ToList();
firstSet.ShouldBeEqualTo(Enumerable.Range(1, 2));
var second = memoized.First();
second.ShouldBeEqualTo(1);
}
[Test]
public void Given_maximum_1_and_more_than_1_are_read__should_throw_an_exception_if_another_set_with_more_than_maximum_is_read()
{
var count = new[] { 1 };
var memoized = Generate(count).Memoize(1);
var firstSet = memoized.Take(2).ToList();
firstSet.ShouldBeEqualTo(Enumerable.Range(1, 2));
Assert.Throws<InternalBufferOverflowException>(() => memoized.Take(2).ToList());
}
[Test]
public void Given_no_maximum__should_be_able_to_re_stream_the_entire_enumerable()
{
var count = new[] { 0 };
var memoized = Generate(count).Memoize();
var firstSet = memoized.ToList();
var secondSet = memoized.ToList();
firstSet.ShouldContainAllInOrder(secondSet);
}
private static IEnumerable<int> Generate(IList<int> count)
{
for (var i = 0; i < 10; i++)
{
yield return count[0]++;
}
}
}
[TestFixture]
public class When_asked_to_return_items_in_sets
{
[Test]
public void Should_fill_empty_spots_in_the_last_set_with_the_default_value_if_fill_is_requested()
{
var input = "abcdefghijklm".Select(x => x.ToString()).ToList();
var result = input.InSetsOf(5, true, "x").ToList();
result.Count.ShouldBeEqualTo(3);
result.First().Count.ShouldBeEqualTo(5);
var last = result.Last();
last.Count.ShouldBeEqualTo(5);
last.Join("").ShouldBeEqualTo("klmxx");
}
[Test]
public void Should_not_fill_the_last_set_if_fill_is_not_requested()
{
var input = "abcdefghijkm".Select(x => x.ToString()).ToList();
var result = input.InSetsOf(5, false, "x").ToList();
result.Count.ShouldBeEqualTo(3);
result.First().Count.ShouldBeEqualTo(5);
result.Last().Count.ShouldBeEqualTo(2);
}
[Test]
public void Should_return_the_correct_number_of_sets_if_the_input_contains_a_multiple_of_the_setSize()
{
var input = "abcdefghij".Select(x => x.ToString()).ToList();
var result = input.InSetsOf(5).ToList();
result.Count.ShouldBeEqualTo(2);
result.First().Count.ShouldBeEqualTo(5);
result.Last().Count.ShouldBeEqualTo(5);
}
[Test]
public void Should_separate_the_input_into_sets_of_size_requested()
{
var input = "abcdefghijklm".Select(x => x.ToString()).ToList();
var result = input.InSetsOf(5).ToList();
result.Count.ShouldBeEqualTo(3);
result.First().Count.ShouldBeEqualTo(5);
result.Last().Count.ShouldBeEqualTo(3);
}
}
[TestFixture]
public class When_asked_to_synchronize_2_lists
{
[TestFixture]
public class Given_list_items_are_unordered
{
private List<SyncTestItem> _listA;
private List<SyncTestItem> _listB;
[OneTimeSetUp]
public void BeforeFirstTest()
{
var itemA1 = new SyncTestItem
{
Data = "A1",
KeyId = 1,
ExpectedStatus = SynchronizationStatus.Removed
};
var itemA2 = new SyncTestItem
{
Data = "AB2",
KeyId = 2,
ExpectedStatus = SynchronizationStatus.Unchanged
};
var itemA3 = new SyncTestItem
{
Data = "AB3c",
KeyId = 3,
ExpectedStatus = SynchronizationStatus.Changed
};
var itemB1 = new SyncTestItem
{
Data = "AB3k",
KeyId = 3,
ExpectedStatus = SynchronizationStatus.Changed
};
var itemB2 = new SyncTestItem
{
Data = "B4",
KeyId = 4,
ExpectedStatus = SynchronizationStatus.Added
};
var itemB3 = new SyncTestItem
{
Data = "AB2",
KeyId = 2,
ExpectedStatus = SynchronizationStatus.Unchanged
};
_listA = new List<SyncTestItem>
{
itemA2,
itemA1,
itemA3
};
_listB = new List<SyncTestItem>
{
itemB1,
itemB2,
itemB3
};
}
[Test]
public void Should_mark_items_that_are_in_both_listA_and_listB_and_have_different_contents_as_Changed()
{
var changed = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Changed)
.Select(x => x.OldItem)
.ToList();
changed.Count.ShouldBeEqualTo(1);
AssertCorrectContents(changed, SynchronizationStatus.Changed);
}
[Test]
public void Should_mark_items_that_are_in_both_listA_and_listB_and_have_the_same_contents_as_Unchanged()
{
var unchanged = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Unchanged)
.Select(x => x.OldItem)
.ToList();
unchanged.Count.ShouldBeEqualTo(1);
AssertCorrectContents(unchanged, SynchronizationStatus.Unchanged);
}
[Test]
public void Should_mark_items_that_are_in_listA_that_are_not_in_listB_as_Added()
{
var added = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Added)
.Select(x => x.NewItem)
.ToList();
added.Count.ShouldBeEqualTo(1);
AssertCorrectContents(added, SynchronizationStatus.Added);
}
[Test]
public void Should_mark_items_that_are_in_listB_that_are_not_in_listA_as_Removed()
{
var removed = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Removed)
.Select(x => x.OldItem)
.ToList();
removed.Count.ShouldBeEqualTo(1);
AssertCorrectContents(removed, SynchronizationStatus.Removed);
}
private static void AssertCorrectContents(IEnumerable<SyncTestItem> result, SynchronizationStatus expectedName)
{
var list = result.ToList();
list.ShouldNotBeNull();
list.Any().ShouldBeTrue();
list.All(item => item.ExpectedStatus == expectedName).ShouldBeTrue();
}
}
[TestFixture]
public class Given_previous_list_items_are_ordered_and_new_list_items_are_ordered
{
private IOrderedEnumerable<SyncTestItem> _listA;
private IOrderedEnumerable<SyncTestItem> _listB;
[OneTimeSetUp]
public void BeforeFirstTest()
{
var itemA1 = new SyncTestItem
{
Data = "A1",
KeyId = 1,
ExpectedStatus = SynchronizationStatus.Removed
};
var itemA2 = new SyncTestItem
{
Data = "AB2",
KeyId = 2,
ExpectedStatus = SynchronizationStatus.Unchanged
};
var itemA3 = new SyncTestItem
{
Data = "AB3c",
KeyId = 3,
ExpectedStatus = SynchronizationStatus.Changed
};
var itemB1 = new SyncTestItem
{
Data = "AB3k",
KeyId = 3,
ExpectedStatus = SynchronizationStatus.Changed
};
var itemB2 = new SyncTestItem
{
Data = "B4",
KeyId = 4,
ExpectedStatus = SynchronizationStatus.Added
};
var itemB3 = new SyncTestItem
{
Data = "AB2",
KeyId = 2,
ExpectedStatus = SynchronizationStatus.Unchanged
};
_listA = new List<SyncTestItem>
{
itemA2,
itemA1,
itemA3
}.OrderBy(x => x.KeyId);
_listB = new List<SyncTestItem>
{
itemB1,
itemB2,
itemB3
}.OrderBy(x => x.KeyId);
}
[Test]
public void Should_mark_items_that_are_in_both_listA_and_listB_and_have_different_contents_as_Changed()
{
var changed = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Changed)
.Select(x => x.OldItem)
.ToList();
changed.Count.ShouldBeEqualTo(1);
AssertCorrectContents(changed, SynchronizationStatus.Changed);
}
[Test]
public void Should_mark_items_that_are_in_both_listA_and_listB_and_have_the_same_contents_as_Unchanged()
{
var unchanged = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Unchanged)
.Select(x => x.OldItem)
.ToList();
unchanged.Count.ShouldBeEqualTo(1);
AssertCorrectContents(unchanged, SynchronizationStatus.Unchanged);
}
[Test]
public void Should_mark_items_that_are_in_listA_that_are_not_in_listB_as_Added()
{
var added = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Added)
.Select(x => x.NewItem)
.ToList();
added.Count.ShouldBeEqualTo(1);
AssertCorrectContents(added, SynchronizationStatus.Added);
}
[Test]
public void Should_mark_items_that_are_in_listB_that_are_not_in_listA_as_Removed()
{
var removed = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Removed)
.Select(x => x.OldItem)
.ToList();
removed.Count.ShouldBeEqualTo(1);
AssertCorrectContents(removed, SynchronizationStatus.Removed);
}
private static void AssertCorrectContents(IEnumerable<SyncTestItem> result, SynchronizationStatus expectedName)
{
var list = result.ToList();
list.ShouldNotBeNull();
list.Any().ShouldBeTrue();
list.All(item => item.ExpectedStatus == expectedName).ShouldBeTrue();
}
}
[TestFixture]
public class Given_previous_list_items_are_ordered_but_new_list_items_are_unordered
{
private IOrderedEnumerable<SyncTestItem> _listA;
private List<SyncTestItem> _listB;
[OneTimeSetUp]
public void BeforeFirstTest()
{
var itemA1 = new SyncTestItem
{
Data = "A1",
KeyId = 1,
ExpectedStatus = SynchronizationStatus.Removed
};
var itemA2 = new SyncTestItem
{
Data = "AB2",
KeyId = 2,
ExpectedStatus = SynchronizationStatus.Unchanged
};
var itemA3 = new SyncTestItem
{
Data = "AB3c",
KeyId = 3,
ExpectedStatus = SynchronizationStatus.Changed
};
var itemB1 = new SyncTestItem
{
Data = "AB3k",
KeyId = 3,
ExpectedStatus = SynchronizationStatus.Changed
};
var itemB2 = new SyncTestItem
{
Data = "B4",
KeyId = 4,
ExpectedStatus = SynchronizationStatus.Added
};
var itemB3 = new SyncTestItem
{
Data = "AB2",
KeyId = 2,
ExpectedStatus = SynchronizationStatus.Unchanged
};
_listA = new List<SyncTestItem>
{
itemA2,
itemA1,
itemA3
}.OrderBy(x => x.KeyId);
_listB = new List<SyncTestItem>
{
itemB1,
itemB2,
itemB3
};
}
[Test]
public void Should_mark_items_that_are_in_both_listA_and_listB_and_have_different_contents_as_Changed()
{
var changed = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Changed)
.Select(x => x.OldItem)
.ToList();
changed.Count.ShouldBeEqualTo(1);
AssertCorrectContents(changed, SynchronizationStatus.Changed);
}
[Test]
public void Should_mark_items_that_are_in_both_listA_and_listB_and_have_the_same_contents_as_Unchanged()
{
var unchanged = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Unchanged)
.Select(x => x.OldItem)
.ToList();
unchanged.Count.ShouldBeEqualTo(1);
AssertCorrectContents(unchanged, SynchronizationStatus.Unchanged);
}
[Test]
public void Should_mark_items_that_are_in_listA_that_are_not_in_listB_as_Added()
{
var added = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Added)
.Select(x => x.NewItem)
.ToList();
added.Count.ShouldBeEqualTo(1);
AssertCorrectContents(added, SynchronizationStatus.Added);
}
[Test]
public void Should_mark_items_that_are_in_listB_that_are_not_in_listA_as_Removed()
{
var removed = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Removed)
.Select(x => x.OldItem)
.ToList();
removed.Count.ShouldBeEqualTo(1);
AssertCorrectContents(removed, SynchronizationStatus.Removed);
}
private static void AssertCorrectContents(IEnumerable<SyncTestItem> result, SynchronizationStatus expectedName)
{
var list = result.ToList();
list.ShouldNotBeNull();
list.Any().ShouldBeTrue();
list.All(item => item.ExpectedStatus == expectedName).ShouldBeTrue();
}
}
[TestFixture]
public class Given_previous_list_items_are_unordered_but_new_list_items_are_ordered
{
private List<SyncTestItem> _listA;
private IOrderedEnumerable<SyncTestItem> _listB;
[OneTimeSetUp]
public void BeforeFirstTest()
{
var itemA1 = new SyncTestItem
{
Data = "A1",
KeyId = 1,
ExpectedStatus = SynchronizationStatus.Removed
};
var itemA2 = new SyncTestItem
{
Data = "AB2",
KeyId = 2,
ExpectedStatus = SynchronizationStatus.Unchanged
};
var itemA3 = new SyncTestItem
{
Data = "AB3c",
KeyId = 3,
ExpectedStatus = SynchronizationStatus.Changed
};
var itemB1 = new SyncTestItem
{
Data = "AB3k",
KeyId = 3,
ExpectedStatus = SynchronizationStatus.Changed
};
var itemB2 = new SyncTestItem
{
Data = "B4",
KeyId = 4,
ExpectedStatus = SynchronizationStatus.Added
};
var itemB3 = new SyncTestItem
{
Data = "AB2",
KeyId = 2,
ExpectedStatus = SynchronizationStatus.Unchanged
};
_listA = new List<SyncTestItem>
{
itemA2,
itemA1,
itemA3
};
_listB = new List<SyncTestItem>
{
itemB1,
itemB2,
itemB3
}.OrderBy(x => x.KeyId);
}
[Test]
public void Should_mark_items_that_are_in_both_listA_and_listB_and_have_different_contents_as_Changed()
{
var changed = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Changed)
.Select(x => x.OldItem)
.ToList();
changed.Count.ShouldBeEqualTo(1);
AssertCorrectContents(changed, SynchronizationStatus.Changed);
}
[Test]
public void Should_mark_items_that_are_in_both_listA_and_listB_and_have_the_same_contents_as_Unchanged()
{
var unchanged = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Unchanged)
.Select(x => x.OldItem)
.ToList();
unchanged.Count.ShouldBeEqualTo(1);
AssertCorrectContents(unchanged, SynchronizationStatus.Unchanged);
}
[Test]
public void Should_mark_items_that_are_in_listA_that_are_not_in_listB_as_Added()
{
var added = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Added)
.Select(x => x.NewItem)
.ToList();
added.Count.ShouldBeEqualTo(1);
AssertCorrectContents(added, SynchronizationStatus.Added);
}
[Test]
public void Should_mark_items_that_are_in_listB_that_are_not_in_listA_as_Removed()
{
var removed = _listA.Synchronize(_listB, item => item.KeyId, (item1, item2) => item1.Data == item2.Data)
.Where(x => x.Status == SynchronizationStatus.Removed)
.Select(x => x.OldItem)
.ToList();
removed.Count.ShouldBeEqualTo(1);
AssertCorrectContents(removed, SynchronizationStatus.Removed);
}
private static void AssertCorrectContents(IEnumerable<SyncTestItem> result, SynchronizationStatus expectedName)
{
var list = result.ToList();
list.ShouldNotBeNull();
list.Any().ShouldBeTrue();
list.All(item => item.ExpectedStatus == expectedName).ShouldBeTrue();
}
}
public class SyncTestItem
{
public string Data { get; set; }
public SynchronizationStatus ExpectedStatus { get; set; }
public int KeyId { get; set; }
}
}
public interface ITestItem
{
int KeyId { get; set; }
string Name { get; set; }
}
}
}
| |
/*
* IFrameProcessor.cs
*
* Copyright ?2007 Michael Schwarz (http://www.ajaxpro.info).
* All Rights Reserved.
*
* 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.
*/
/*
* MS 06-04-26 renamed property Method to AjaxMethod to be CLSCompliant
* MS 06-04-28 changed http header names to AjaxPro-Method
* MS 06-04-29 added context item for JSON request
* fixed response (null, exception,...)
* MS 06-05-03 set encoding to UTF-8
* MS 06-05-04 fixed bug on Express Web Developer when method does not have
* any argument
* MS 06-05-09 implemented CanHandleRequest
* fixed return value of AjaxMethod if type equals null
* fixed if there are ambiguous methods
* MS 06-05-15 added script defer="defer"
* MS 06-05-22 using inherited.GetMethodInfo for fixed AjaxNamespace usage for method
* MS 06-05-30 changed method value name to X-AjaxPro-Method
* MS 06-06-06 ContentType moved to inherited class
* MS 06-07-19 fixed if method argument is from type IJavaScriptObject
* MS 06-07-20 removed the fix above and put it to JavaScriptConverter
* MS 06-10-03 fixed bug with CryptProvider
* MS 07-03-24 fixed Ajax token bug
*
*/
using System;
using System.Web;
using System.Reflection;
using System.IO;
namespace AjaxPro
{
internal class IFrameProcessor : IAjaxProcessor
{
private int hashCode;
/// <summary>
/// Initializes a new instance of the <see cref="IFrameProcessor"/> class.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="type">The type.</param>
internal IFrameProcessor(HttpContext context, Type type) : base(context, type)
{
}
#region IAjaxProcessor Members
/// <summary>
/// Retreives the parameters.
/// </summary>
/// <returns></returns>
public override object[] RetreiveParameters()
{
ParameterInfo[] pi = method.GetParameters();
object[] args = new object[pi.Length];
// initialize default values
for(int i=0; i<pi.Length; i++)
args[i] = pi[i].DefaultValue;
string v = context.Request["data"];
// If something went wrong or there are no arguments
// we can return with the empty argument array.
if (v == null || pi.Length == 0 || v == "{}")
return args;
if(context.Request.ContentEncoding != System.Text.Encoding.UTF8)
v = System.Text.Encoding.UTF8.GetString(context.Request.ContentEncoding.GetBytes(v));
hashCode = v.GetHashCode();
// check if we have to decrypt the JSON string.
if(Utility.Settings != null && Utility.Settings.Security != null)
v = Utility.Settings.Security.SecurityProvider.Decrypt(v);
context.Items.Add(Constant.AjaxID + ".JSON", v);
JavaScriptObject jso = (JavaScriptObject)JavaScriptDeserializer.DeserializeFromJson(v, typeof(JavaScriptObject));
for(int i=0; i<pi.Length; i++)
{
//if (pi[i].ParameterType.IsAssignableFrom(jso[pi[i].Name].GetType()))
//{
// args[i] = jso[pi[i].Name];
//}
//else
{
args[i] = JavaScriptDeserializer.Deserialize((IJavaScriptObject)jso[pi[i].Name], pi[i].ParameterType);
}
}
return args;
}
/// <summary>
/// Serializes the object.
/// </summary>
/// <param name="o">The o.</param>
/// <returns></returns>
public override string SerializeObject(object o)
{
// On the client we want to have a real object.
// For more details visit: http://www.crockford.com/JSON/index.html
//
// JSON is built on two structures:
// - A collection of name/value pairs. In various languages,
// this is realized as an object, record, struct, dictionary,
// hash table, keyed list, or associative array.
// - An ordered list of values. In most languages, this is realized
// as an array.
string res;
if (o is Exception)
res = "{\"error\":" + JavaScriptSerializer.Serialize(o) + "}";
else
res = "{\"value\":" + JavaScriptSerializer.Serialize(o) + "}";
// check if we have to encrypt the JSON string.
if (Utility.Settings != null && Utility.Settings.Security != null)
res = Utility.Settings.Security.SecurityProvider.Encrypt(res);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/></head><body>\r\n<script type=\"text/javascript\" defer=\"defer\">\r\ndocument.body.res = \"");
sb.Append(res.Replace("\\", "\\\\").Replace("\"", "\\\""));
sb.Append("\";\r\n</script>\r\n</body></html>");
context.Response.ContentType = this.ContentType;
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.Write(sb.ToString());
return sb.ToString();
}
/// <summary>
/// Gets a value indicating whether this instance can handle request.
/// </summary>
/// <value>
/// <c>true</c> if this instance can handle request; otherwise, <c>false</c>.
/// </value>
internal override bool CanHandleRequest
{
get
{
return context.Request["X-" + Constant.AjaxID + "-Method"] != null;
}
}
/// <summary>
/// Gets the ajax method.
/// </summary>
/// <value>The ajax method.</value>
public override MethodInfo AjaxMethod
{
get
{
string m = context.Request["X-" + Constant.AjaxID + "-Method"];
if (m == null)
return null;
return this.GetMethodInfo(m);
}
}
/// <summary>
/// Gets a value indicating whether this instance is encryption able.
/// </summary>
/// <value>
/// <c>true</c> if this instance is encryption able; otherwise, <c>false</c>.
/// </value>
public override bool IsEncryptionAble
{
get
{
return true;
}
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return hashCode;
}
/// <summary>
/// Gets the type of the content.
/// </summary>
/// <value>The type of the content.</value>
public override string ContentType
{
get
{
return "text/html";
}
}
public override bool IsValidAjaxToken()
{
if (context == null)
return false;
if (Utility.Settings == null || Utility.Settings.Security == null || Utility.Settings.Security.SecurityProvider == null)
return true;
if (Utility.Settings.Security.SecurityProvider.AjaxTokenEnabled == false)
return true;
string token = context.Request["X-" + Constant.AjaxID + "-Token"];
if (token != null)
{
try
{
if (Utility.Settings.Security.SecurityProvider.IsValidAjaxToken(token, Utility.Settings.TokenSitePassword))
return true;
}
catch (Exception)
{
}
}
return false;
}
#endregion
}
}
| |
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
/*
* 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 GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapSearchModule")]
public class MapSearchModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<UUID> m_Clients;
private Scene m_scene = null; // only need one for communication with GridService
private List<Scene> m_scenes = new List<Scene>();
#region ISharedRegionModule Members
public string Name
{
get { return "MapSearchModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
{
m_scene = scene;
}
m_scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
m_Clients = new List<UUID>();
}
public void Close()
{
m_scene = null;
m_scenes.Clear();
}
public void Initialise(IConfigSource source)
{
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
m_scenes.Remove(scene);
if (m_scene == scene && m_scenes.Count > 0)
m_scene = m_scenes[0];
scene.EventManager.OnNewClient -= OnNewClient;
}
#endregion ISharedRegionModule Members
private void AddFinalBlock(List<MapBlockData> blocks)
{
// final block, closing the search result
MapBlockData data = new MapBlockData();
data.Agents = 0;
data.Access = (byte)SimAccess.NonExistent;
data.MapImageId = UUID.Zero;
data.Name = "";
data.RegionFlags = 0;
data.WaterHeight = 0; // not used
data.X = 0;
data.Y = 0;
blocks.Add(data);
}
private void OnMapNameRequest(IClientAPI remoteClient, string mapName, uint flags)
{
List<MapBlockData> blocks = new List<MapBlockData>();
MapBlockData data;
if (mapName.Length < 3 || (mapName.EndsWith("#") && mapName.Length < 4))
{
// final block, closing the search result
AddFinalBlock(blocks);
// flags are agent flags sent from the viewer.
// they have different values depending on different viewers, apparently
remoteClient.SendMapBlock(blocks, flags);
remoteClient.SendAlertMessage("Use a search string with at least 3 characters");
return;
}
//m_log.DebugFormat("MAP NAME=({0})", mapName);
// Hack to get around the fact that ll V3 now drops the port from the
// map name. See https://jira.secondlife.com/browse/VWR-28570
//
// Caller, use this magic form instead:
// secondlife://http|!!mygrid.com|8002|Region+Name/128/128
// or url encode if possible.
// the hacks we do with this viewer...
//
string mapNameOrig = mapName;
if (mapName.Contains("|"))
mapName = mapName.Replace('|', ':');
if (mapName.Contains("+"))
mapName = mapName.Replace('+', ' ');
if (mapName.Contains("!"))
mapName = mapName.Replace('!', '/');
// try to fetch from GridServer
List<GridRegion> regionInfos = m_scene.GridService.GetRegionsByName(m_scene.RegionInfo.ScopeID, mapName, 20);
m_log.DebugFormat("[MAPSEARCHMODULE]: search {0} returned {1} regions. Flags={2}", mapName, regionInfos.Count, flags);
if (regionInfos.Count > 0)
{
foreach (GridRegion info in regionInfos)
{
data = new MapBlockData();
data.Agents = 0;
data.Access = info.Access;
if (flags == 2) // V2 sends this
data.MapImageId = UUID.Zero;
else
data.MapImageId = info.TerrainImage;
// ugh! V2-3 is very sensitive about the result being
// exactly the same as the requested name
if (regionInfos.Count == 1 && mapNameOrig.Contains("|") || mapNameOrig.Contains("+"))
data.Name = mapNameOrig;
else
data.Name = info.RegionName;
data.RegionFlags = 0; // TODO not used?
data.WaterHeight = 0; // not used
data.X = (ushort)Util.WorldToRegionLoc((uint)info.RegionLocX);
data.Y = (ushort)Util.WorldToRegionLoc((uint)info.RegionLocY);
blocks.Add(data);
}
}
// final block, closing the search result
AddFinalBlock(blocks);
// flags are agent flags sent from the viewer.
// they have different values depending on different viewers, apparently
remoteClient.SendMapBlock(blocks, flags);
// send extra user messages for V3
// because the UI is very confusing
// while we don't fix the hard-coded urls
if (flags == 2)
{
if (regionInfos.Count == 0)
remoteClient.SendAlertMessage("No regions found with that name.");
else if (regionInfos.Count == 1)
remoteClient.SendAlertMessage("Region found!");
}
}
private void OnMapNameRequestHandler(IClientAPI remoteClient, string mapName, uint flags)
{
lock (m_Clients)
{
if (m_Clients.Contains(remoteClient.AgentId))
return;
m_Clients.Add(remoteClient.AgentId);
}
try
{
OnMapNameRequest(remoteClient, mapName, flags);
}
finally
{
lock (m_Clients)
m_Clients.Remove(remoteClient.AgentId);
}
}
private void OnNewClient(IClientAPI client)
{
client.OnMapNameRequest += OnMapNameRequestHandler;
}
// private Scene GetClientScene(IClientAPI client)
// {
// foreach (Scene s in m_scenes)
// {
// if (client.Scene.RegionInfo.RegionHandle == s.RegionInfo.RegionHandle)
// return s;
// }
// return m_scene;
// }
}
}
| |
// 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.Numerics;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using System.Runtime.CompilerServices;
internal partial class IntelHardwareIntrinsicTest
{
public static Vector128<T> Vector128Add<T>(Vector128<T> left, Vector128<T> right) where T : struct
{
if (typeof(T) == typeof(byte))
{
return Sse2.Add(left.AsByte(), right.AsByte()).As<byte, T>();
}
else if (typeof(T) == typeof(sbyte))
{
return Sse2.Add(left.AsSByte(), right.AsSByte()).As<sbyte, T>();
}
else if (typeof(T) == typeof(short))
{
return Sse2.Add(left.AsInt16(), right.AsInt16()).As<short, T>();
}
else if (typeof(T) == typeof(ushort))
{
return Sse2.Add(left.AsUInt16(), right.AsUInt16()).As<ushort, T>();
}
else if (typeof(T) == typeof(int))
{
return Sse2.Add(left.AsInt32(), right.AsInt32()).As<int, T>();
}
else if (typeof(T) == typeof(uint))
{
return Sse2.Add(left.AsUInt32(), right.AsUInt32()).As<uint, T>();
}
else if (typeof(T) == typeof(long))
{
return Sse2.Add(left.AsInt64(), right.AsInt64()).As<long, T>();
}
else if (typeof(T) == typeof(ulong))
{
return Sse2.Add(left.AsUInt64(), right.AsUInt64()).As<ulong, T>();
}
else if (typeof(T) == typeof(float))
{
return Sse.Add(left.AsSingle(), right.AsSingle()).As<float, T>();
}
else if (typeof(T) == typeof(double))
{
return Sse2.Add(left.AsDouble(), right.AsDouble()).As<double, T>();
}
else
{
throw new NotSupportedException();
}
}
public static Vector256<T> Vector256Add<T>(Vector256<T> left, Vector256<T> right) where T : struct
{
if (typeof(T) == typeof(byte))
{
return Avx2.Add(left.AsByte(), right.AsByte()).As<byte, T>();
}
else if (typeof(T) == typeof(sbyte))
{
return Avx2.Add(left.AsSByte(), right.AsSByte()).As<sbyte, T>();
}
else if (typeof(T) == typeof(short))
{
return Avx2.Add(left.AsInt16(), right.AsInt16()).As<short, T>();
}
else if (typeof(T) == typeof(ushort))
{
return Avx2.Add(left.AsUInt16(), right.AsUInt16()).As<ushort, T>();
}
else if (typeof(T) == typeof(int))
{
return Avx2.Add(left.AsInt32(), right.AsInt32()).As<int, T>();
}
else if (typeof(T) == typeof(uint))
{
return Avx2.Add(left.AsUInt32(), right.AsUInt32()).As<uint, T>();
}
else if (typeof(T) == typeof(long))
{
return Avx2.Add(left.AsInt64(), right.AsInt64()).As<long, T>();
}
else if (typeof(T) == typeof(ulong))
{
return Avx2.Add(left.AsUInt64(), right.AsUInt64()).As<ulong, T>();
}
else if (typeof(T) == typeof(float))
{
return Avx.Add(left.AsSingle(), right.AsSingle()).As<float, T>();
}
else if (typeof(T) == typeof(double))
{
return Avx.Add(left.AsDouble(), right.AsDouble()).As<double, T>();
}
else
{
throw new NotSupportedException();
}
}
public static Vector128<T> CreateVector128<T>(T value) where T : struct
{
if (typeof(T) == typeof(byte))
{
return Vector128.Create(Convert.ToByte(value)).As<byte, T>();
}
else if (typeof(T) == typeof(sbyte))
{
return Vector128.Create(Convert.ToSByte(value)).As<sbyte, T>();
}
else if (typeof(T) == typeof(short))
{
return Vector128.Create(Convert.ToInt16(value)).As<short, T>();
}
else if (typeof(T) == typeof(ushort))
{
return Vector128.Create(Convert.ToUInt16(value)).As<ushort, T>();
}
else if (typeof(T) == typeof(int))
{
return Vector128.Create(Convert.ToInt32(value)).As<int, T>();
}
else if (typeof(T) == typeof(uint))
{
return Vector128.Create(Convert.ToUInt32(value)).As<uint, T>();
}
else if (typeof(T) == typeof(long))
{
return Vector128.Create(Convert.ToInt64(value)).As<long, T>();
}
else if (typeof(T) == typeof(ulong))
{
return Vector128.Create(Convert.ToUInt64(value)).As<ulong, T>();
}
else if (typeof(T) == typeof(float))
{
return Vector128.Create(Convert.ToSingle(value)).As<float, T>();
}
else if (typeof(T) == typeof(double))
{
return Vector128.Create(Convert.ToDouble(value)).As<double, T>();
}
else
{
throw new NotSupportedException();
}
}
public static Vector256<T> CreateVector256<T>(T value) where T : struct
{
if (typeof(T) == typeof(byte))
{
return Vector256.Create(Convert.ToByte(value)).As<byte, T>();
}
else if (typeof(T) == typeof(sbyte))
{
return Vector256.Create(Convert.ToSByte(value)).As<sbyte, T>();
}
else if (typeof(T) == typeof(short))
{
return Vector256.Create(Convert.ToInt16(value)).As<short, T>();
}
else if (typeof(T) == typeof(ushort))
{
return Vector256.Create(Convert.ToUInt16(value)).As<ushort, T>();
}
else if (typeof(T) == typeof(int))
{
return Vector256.Create(Convert.ToInt32(value)).As<int, T>();
}
else if (typeof(T) == typeof(uint))
{
return Vector256.Create(Convert.ToUInt32(value)).As<uint, T>();
}
else if (typeof(T) == typeof(long))
{
return Vector256.Create(Convert.ToInt64(value)).As<long, T>();
}
else if (typeof(T) == typeof(ulong))
{
return Vector256.Create(Convert.ToUInt64(value)).As<ulong, T>();
}
else if (typeof(T) == typeof(float))
{
return Vector256.Create(Convert.ToSingle(value)).As<float, T>();
}
else if (typeof(T) == typeof(double))
{
return Vector256.Create(Convert.ToDouble(value)).As<double, T>();
}
else
{
throw new NotSupportedException();
}
}
public static bool CheckValue<T>(T value, T expectedValue) where T : struct
{
bool returnVal;
if (typeof(T) == typeof(float))
{
returnVal = Math.Abs(((float)(object)value) - ((float)(object)expectedValue)) <= Single.Epsilon;
}
if (typeof(T) == typeof(double))
{
returnVal = Math.Abs(((double)(object)value) - ((double)(object)expectedValue)) <= Double.Epsilon;
}
else
{
returnVal = value.Equals(expectedValue);
}
if (returnVal == false)
{
if ((typeof(T) == typeof(double)) || (typeof(T) == typeof(float)))
{
Console.WriteLine("CheckValue failed for type " + typeof(T).ToString() + ". Expected: {0} , Got: {1}", expectedValue, value);
}
else
{
Console.WriteLine("CheckValue failed for type " + typeof(T).ToString() + ". Expected: {0} (0x{0:X}), Got: {1} (0x{1:X})", expectedValue, value);
}
}
return returnVal;
}
public static T GetValueFromInt<T>(int value) where T : struct
{
if (typeof(T) == typeof(float))
{
float floatValue = (float)value;
return (T)(object)floatValue;
}
if (typeof(T) == typeof(double))
{
double doubleValue = (double)value;
return (T)(object)doubleValue;
}
if (typeof(T) == typeof(int))
{
return (T)(object)value;
}
if (typeof(T) == typeof(uint))
{
uint uintValue = (uint)value;
return (T)(object)uintValue;
}
if (typeof(T) == typeof(long))
{
long longValue = (long)value;
return (T)(object)longValue;
}
if (typeof(T) == typeof(ulong))
{
ulong longValue = (ulong)value;
return (T)(object)longValue;
}
if (typeof(T) == typeof(ushort))
{
return (T)(object)(ushort)value;
}
if (typeof(T) == typeof(byte))
{
return (T)(object)(byte)value;
}
if (typeof(T) == typeof(short))
{
return (T)(object)(short)value;
}
if (typeof(T) == typeof(sbyte))
{
return (T)(object)(sbyte)value;
}
else
{
throw new ArgumentException();
}
}
}
| |
// 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.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Rules for the Hijri calendar:
// - The Hijri calendar is a strictly Lunar calendar.
// - Days begin at sunset.
// - Islamic Year 1 (Muharram 1, 1 A.H.) is equivalent to absolute date
// 227015 (Friday, July 16, 622 C.E. - Julian).
// - Leap Years occur in the 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, & 29th
// years of a 30-year cycle. Year = leap iff ((11y+14) mod 30 < 11).
// - There are 12 months which contain alternately 30 and 29 days.
// - The 12th month, Dhu al-Hijjah, contains 30 days instead of 29 days
// in a leap year.
// - Common years have 354 days. Leap years have 355 days.
// - There are 10,631 days in a 30-year cycle.
// - The Islamic months are:
// 1. Muharram (30 days) 7. Rajab (30 days)
// 2. Safar (29 days) 8. Sha'ban (29 days)
// 3. Rabi I (30 days) 9. Ramadan (30 days)
// 4. Rabi II (29 days) 10. Shawwal (29 days)
// 5. Jumada I (30 days) 11. Dhu al-Qada (30 days)
// 6. Jumada II (29 days) 12. Dhu al-Hijjah (29 days) {30}
//
// NOTENOTE
// The calculation of the HijriCalendar is based on the absolute date. And the
// absolute date means the number of days from January 1st, 1 A.D.
// Therefore, we do not support the days before the January 1st, 1 A.D.
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0622/07/18 9999/12/31
** Hijri 0001/01/01 9666/04/03
*/
[System.Runtime.InteropServices.ComVisible(true)]
public partial class HijriCalendar : Calendar
{
internal static readonly int HijriEra = 1;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
internal const int MinAdvancedHijri = -2;
internal const int MaxAdvancedHijri = 2;
internal static readonly int[] HijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 };
//internal static Calendar m_defaultInstance;
private int m_HijriAdvance = Int32.MinValue;
// DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3).
internal const int MaxCalendarYear = 9666;
internal const int MaxCalendarMonth = 4;
internal const int MaxCalendarDay = 3;
// Hijri calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 7, day: 18)
// This is the minimal Gregorian date that we support in the HijriCalendar.
internal static readonly DateTime calendarMinValue = new DateTime(622, 7, 18);
internal static readonly DateTime calendarMaxValue = DateTime.MaxValue;
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (calendarMaxValue);
}
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of HijriCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance() {
if (m_defaultInstance == null) {
m_defaultInstance = new HijriCalendar();
}
return (m_defaultInstance);
}
*/
// Construct an instance of Hijri calendar.
public HijriCalendar()
{
}
internal override CalendarId ID
{
get
{
return CalendarId.HIJRI;
}
}
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// the year before the 1st year of the cycle would have been the 30th year
// of the previous cycle which is not a leap year. Common years have 354 days.
return 354;
}
}
/*=================================GetAbsoluteDateHijri==========================
**Action: Gets the Absolute date for the given Hijri date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
long GetAbsoluteDateHijri(int y, int m, int d)
{
return (long)(DaysUpToHijriYear(y) + HijriMonthDays[m - 1] + d - 1 - HijriAdjustment);
}
/*=================================DaysUpToHijriYear==========================
**Action: Gets the total number of days (absolute date) up to the given Hijri Year.
** The absolute date means the number of days from January 1st, 1 A.D.
**Returns: Gets the total number of days (absolute date) up to the given Hijri Year.
**Arguments: HijriYear year value in Hijri calendar.
**Exceptions: None
**Notes:
============================================================================*/
long DaysUpToHijriYear(int HijriYear)
{
long NumDays; // number of absolute days
int NumYear30; // number of years up to current 30 year cycle
int NumYearsLeft; // number of years into 30 year cycle
//
// Compute the number of years up to the current 30 year cycle.
//
NumYear30 = ((HijriYear - 1) / 30) * 30;
//
// Compute the number of years left. This is the number of years
// into the 30 year cycle for the given year.
//
NumYearsLeft = HijriYear - NumYear30 - 1;
//
// Compute the number of absolute days up to the given year.
//
NumDays = ((NumYear30 * 10631L) / 30L) + 227013L;
while (NumYearsLeft > 0)
{
// Common year is 354 days, and leap year is 355 days.
NumDays += 354 + (IsLeapYear(NumYearsLeft, CurrentEra) ? 1 : 0);
NumYearsLeft--;
}
//
// Return the number of absolute days.
//
return (NumDays);
}
public int HijriAdjustment
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_HijriAdvance == Int32.MinValue)
{
// Never been set before. Use the system value from registry.
m_HijriAdvance = GetHijriDateAdjustment();
}
return (m_HijriAdvance);
}
set
{
// NOTE: Check the value of Min/MaxAdavncedHijri with Arabic speakers to see if the assumption is good.
if (value < MinAdvancedHijri || value > MaxAdvancedHijri)
{
throw new ArgumentOutOfRangeException(
"HijriAdjustment",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
MinAdvancedHijri,
MaxAdvancedHijri));
}
Contract.EndContractBlock();
VerifyWritable();
m_HijriAdvance = value;
}
}
static internal void CheckTicksRange(long ticks)
{
if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
String.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
calendarMinValue,
calendarMaxValue));
}
}
static internal void CheckEraRange(int era)
{
if (era != CurrentEra && era != HijriEra)
{
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
}
static internal void CheckYearRange(int year, int era)
{
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
}
static internal void CheckYearMonthRange(int year, int month, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
if (month > MaxCalendarMonth)
{
throw new ArgumentOutOfRangeException(
"month",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarMonth));
}
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
}
/*=================================GetDatePart==========================
**Action: Returns a given date part of this <i>DateTime</i>. This method is used
** to compute the year, day-of-year, month, or day part.
**Returns:
**Arguments:
**Exceptions: ArgumentException if part is incorrect.
**Notes:
** First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks.
** Use the formula (((AbsoluteDate - 227013) * 30) / 10631) + 1, we can a rough value for the Hijri year.
** In order to get the exact Hijri year, we compare the exact absolute date for HijriYear and (HijriYear + 1).
** From here, we can get the correct Hijri year.
============================================================================*/
internal virtual int GetDatePart(long ticks, int part)
{
int HijriYear; // Hijri year
int HijriMonth; // Hijri month
int HijriDay; // Hijri day
long NumDays; // The calculation buffer in number of days.
CheckTicksRange(ticks);
//
// Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
//
NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
//
// See how much we need to backup or advance
//
NumDays += HijriAdjustment;
//
// Calculate the appromixate Hijri Year from this magic formula.
//
HijriYear = (int)(((NumDays - 227013) * 30) / 10631) + 1;
long daysToHijriYear = DaysUpToHijriYear(HijriYear); // The absoulte date for HijriYear
long daysOfHijriYear = GetDaysInYear(HijriYear, CurrentEra); // The number of days for (HijriYear+1) year.
if (NumDays < daysToHijriYear)
{
daysToHijriYear -= daysOfHijriYear;
HijriYear--;
}
else if (NumDays == daysToHijriYear)
{
HijriYear--;
daysToHijriYear -= GetDaysInYear(HijriYear, CurrentEra);
}
else
{
if (NumDays > daysToHijriYear + daysOfHijriYear)
{
daysToHijriYear += daysOfHijriYear;
HijriYear++;
}
}
if (part == DatePartYear)
{
return (HijriYear);
}
//
// Calculate the Hijri Month.
//
HijriMonth = 1;
NumDays -= daysToHijriYear;
if (part == DatePartDayOfYear)
{
return ((int)NumDays);
}
while ((HijriMonth <= 12) && (NumDays > HijriMonthDays[HijriMonth - 1]))
{
HijriMonth++;
}
HijriMonth--;
if (part == DatePartMonth)
{
return (HijriMonth);
}
//
// Calculate the Hijri Day.
//
HijriDay = (int)(NumDays - HijriMonthDays[HijriMonth - 1]);
if (part == DatePartDay)
{
return (HijriDay);
}
// Incorrect part value.
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
// Get the date in Hijri calendar.
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = GetAbsoluteDateHijri(y, m, d) * TicksPerDay + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
[Pure]
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
if (month == 12)
{
// For the 12th month, leap year has 30 days, and common year has 29 days.
return (IsLeapYear(year, CurrentEra) ? 30 : 29);
}
// Other months contain 30 and 29 days alternatively. The 1st month has 30 days.
return (((month % 2) == 1) ? 30 : 29);
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
CheckYearRange(year, era);
// Common years have 354 days. Leap years have 355 days.
return (IsLeapYear(year, CurrentEra) ? 355 : 354);
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
CheckTicksRange(time.Ticks);
return (HijriEra);
}
public override int[] Eras
{
get
{
return (new int[] { HijriEra });
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
CheckYearRange(year, era);
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and MaxCalendarYear.
//
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
return (IsLeapYear(year, era) && month == 12 && day == 30);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearRange(year, era);
return ((((year * 11) + 14) % 30) < 11);
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
// The year/month/era checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
long lDate = GetAbsoluteDateHijri(year, month, day);
if (lDate >= 0)
{
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1451;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"value",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxCalendarYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return (base.ToFourDigitYear(year));
}
if (year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
return (year);
}
}
}
| |
using J2N.Threading.Atomic;
using YAF.Lucene.Net.Index;
using YAF.Lucene.Net.Store;
using YAF.Lucene.Net.Util.Fst;
using System;
using System.Collections.Generic;
namespace YAF.Lucene.Net.Codecs.Lucene42
{
/*
* 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 BinaryDocValues = YAF.Lucene.Net.Index.BinaryDocValues;
using IBits = YAF.Lucene.Net.Util.IBits;
using BlockPackedReader = YAF.Lucene.Net.Util.Packed.BlockPackedReader;
using ByteArrayDataInput = YAF.Lucene.Net.Store.ByteArrayDataInput;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using ChecksumIndexInput = YAF.Lucene.Net.Store.ChecksumIndexInput;
using CorruptIndexException = YAF.Lucene.Net.Index.CorruptIndexException;
using DocsAndPositionsEnum = YAF.Lucene.Net.Index.DocsAndPositionsEnum;
using DocsEnum = YAF.Lucene.Net.Index.DocsEnum;
using DocValues = YAF.Lucene.Net.Index.DocValues;
using DocValuesType = YAF.Lucene.Net.Index.DocValuesType;
using FieldInfo = YAF.Lucene.Net.Index.FieldInfo;
using FieldInfos = YAF.Lucene.Net.Index.FieldInfos;
using IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames;
using IndexInput = YAF.Lucene.Net.Store.IndexInput;
using Int32sRef = YAF.Lucene.Net.Util.Int32sRef;
using IOUtils = YAF.Lucene.Net.Util.IOUtils;
using MonotonicBlockPackedReader = YAF.Lucene.Net.Util.Packed.MonotonicBlockPackedReader;
using NumericDocValues = YAF.Lucene.Net.Index.NumericDocValues;
using PackedInt32s = YAF.Lucene.Net.Util.Packed.PackedInt32s;
using PagedBytes = YAF.Lucene.Net.Util.PagedBytes;
using PositiveInt32Outputs = YAF.Lucene.Net.Util.Fst.PositiveInt32Outputs;
using RamUsageEstimator = YAF.Lucene.Net.Util.RamUsageEstimator;
using SegmentReadState = YAF.Lucene.Net.Index.SegmentReadState;
using SortedDocValues = YAF.Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = YAF.Lucene.Net.Index.SortedSetDocValues;
using TermsEnum = YAF.Lucene.Net.Index.TermsEnum;
using Util = YAF.Lucene.Net.Util.Fst.Util;
/// <summary>
/// Reader for <see cref="Lucene42DocValuesFormat"/>.
/// </summary>
internal class Lucene42DocValuesProducer : DocValuesProducer
{
// metadata maps (just file pointers and minimal stuff)
private readonly IDictionary<int, NumericEntry> numerics;
private readonly IDictionary<int, BinaryEntry> binaries;
private readonly IDictionary<int, FSTEntry> fsts;
private readonly IndexInput data;
private readonly int version;
// ram instances we have already loaded
private readonly IDictionary<int, NumericDocValues> numericInstances = new Dictionary<int, NumericDocValues>();
private readonly IDictionary<int, BinaryDocValues> binaryInstances = new Dictionary<int, BinaryDocValues>();
private readonly IDictionary<int, FST<long?>> fstInstances = new Dictionary<int, FST<long?>>();
private readonly int maxDoc;
private readonly AtomicInt64 ramBytesUsed;
internal const sbyte NUMBER = 0;
internal const sbyte BYTES = 1;
internal const sbyte FST = 2;
internal const int BLOCK_SIZE = 4096;
internal const sbyte DELTA_COMPRESSED = 0;
internal const sbyte TABLE_COMPRESSED = 1;
internal const sbyte UNCOMPRESSED = 2;
internal const sbyte GCD_COMPRESSED = 3;
internal const int VERSION_START = 0;
internal const int VERSION_GCD_COMPRESSION = 1;
internal const int VERSION_CHECKSUM = 2;
internal const int VERSION_CURRENT = VERSION_CHECKSUM;
internal Lucene42DocValuesProducer(SegmentReadState state, string dataCodec, string dataExtension, string metaCodec, string metaExtension)
{
maxDoc = state.SegmentInfo.DocCount;
string metaName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, metaExtension);
// read in the entries from the metadata file.
ChecksumIndexInput @in = state.Directory.OpenChecksumInput(metaName, state.Context);
bool success = false;
ramBytesUsed = new AtomicInt64(RamUsageEstimator.ShallowSizeOfInstance(this.GetType()));
try
{
version = CodecUtil.CheckHeader(@in, metaCodec, VERSION_START, VERSION_CURRENT);
numerics = new Dictionary<int, NumericEntry>();
binaries = new Dictionary<int, BinaryEntry>();
fsts = new Dictionary<int, FSTEntry>();
ReadFields(@in, state.FieldInfos);
if (version >= VERSION_CHECKSUM)
{
CodecUtil.CheckFooter(@in);
}
else
{
#pragma warning disable 612, 618
CodecUtil.CheckEOF(@in);
#pragma warning restore 612, 618
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(@in);
}
else
{
IOUtils.DisposeWhileHandlingException(@in);
}
}
success = false;
try
{
string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, dataExtension);
data = state.Directory.OpenInput(dataName, state.Context);
int version2 = CodecUtil.CheckHeader(data, dataCodec, VERSION_START, VERSION_CURRENT);
if (version != version2)
{
throw new CorruptIndexException("Format versions mismatch");
}
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(this.data);
}
}
}
private void ReadFields(IndexInput meta, FieldInfos infos)
{
int fieldNumber = meta.ReadVInt32();
while (fieldNumber != -1)
{
// check should be: infos.fieldInfo(fieldNumber) != null, which incorporates negative check
// but docvalues updates are currently buggy here (loading extra stuff, etc): LUCENE-5616
if (fieldNumber < 0)
{
// trickier to validate more: because we re-use for norms, because we use multiple entries
// for "composite" types like sortedset, etc.
throw new CorruptIndexException("Invalid field number: " + fieldNumber + ", input=" + meta);
}
int fieldType = meta.ReadByte();
if (fieldType == NUMBER)
{
var entry = new NumericEntry();
entry.Offset = meta.ReadInt64();
entry.Format = (sbyte)meta.ReadByte();
switch (entry.Format)
{
case DELTA_COMPRESSED:
case TABLE_COMPRESSED:
case GCD_COMPRESSED:
case UNCOMPRESSED:
break;
default:
throw new CorruptIndexException("Unknown format: " + entry.Format + ", input=" + meta);
}
if (entry.Format != UNCOMPRESSED)
{
entry.PackedInt32sVersion = meta.ReadVInt32();
}
numerics[fieldNumber] = entry;
}
else if (fieldType == BYTES)
{
BinaryEntry entry = new BinaryEntry();
entry.Offset = meta.ReadInt64();
entry.NumBytes = meta.ReadInt64();
entry.MinLength = meta.ReadVInt32();
entry.MaxLength = meta.ReadVInt32();
if (entry.MinLength != entry.MaxLength)
{
entry.PackedInt32sVersion = meta.ReadVInt32();
entry.BlockSize = meta.ReadVInt32();
}
binaries[fieldNumber] = entry;
}
else if (fieldType == FST)
{
FSTEntry entry = new FSTEntry();
entry.Offset = meta.ReadInt64();
entry.NumOrds = meta.ReadVInt64();
fsts[fieldNumber] = entry;
}
else
{
throw new CorruptIndexException("invalid entry type: " + fieldType + ", input=" + meta);
}
fieldNumber = meta.ReadVInt32();
}
}
public override NumericDocValues GetNumeric(FieldInfo field)
{
lock (this)
{
NumericDocValues instance;
if (!numericInstances.TryGetValue(field.Number, out instance) || instance == null)
{
instance = LoadNumeric(field);
numericInstances[field.Number] = instance;
}
return instance;
}
}
public override long RamBytesUsed() => ramBytesUsed;
public override void CheckIntegrity()
{
if (version >= VERSION_CHECKSUM)
{
CodecUtil.ChecksumEntireFile(data);
}
}
private NumericDocValues LoadNumeric(FieldInfo field)
{
NumericEntry entry = numerics[field.Number];
data.Seek(entry.Offset);
switch (entry.Format)
{
case TABLE_COMPRESSED:
int size = data.ReadVInt32();
if (size > 256)
{
throw new CorruptIndexException("TABLE_COMPRESSED cannot have more than 256 distinct values, input=" + data);
}
var decode = new long[size];
for (int i = 0; i < decode.Length; i++)
{
decode[i] = data.ReadInt64();
}
int formatID = data.ReadVInt32();
int bitsPerValue = data.ReadVInt32();
PackedInt32s.Reader ordsReader = PackedInt32s.GetReaderNoHeader(data, PackedInt32s.Format.ById(formatID), entry.PackedInt32sVersion, maxDoc, bitsPerValue);
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(decode) + ordsReader.RamBytesUsed());
return new NumericDocValuesAnonymousInnerClassHelper(decode, ordsReader);
case DELTA_COMPRESSED:
int blockSize = data.ReadVInt32();
var reader = new BlockPackedReader(data, entry.PackedInt32sVersion, blockSize, maxDoc, false);
ramBytesUsed.AddAndGet(reader.RamBytesUsed());
return reader;
case UNCOMPRESSED:
byte[] bytes = new byte[maxDoc];
data.ReadBytes(bytes, 0, bytes.Length);
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(bytes));
return new NumericDocValuesAnonymousInnerClassHelper2(this, bytes);
case GCD_COMPRESSED:
long min = data.ReadInt64();
long mult = data.ReadInt64();
int quotientBlockSize = data.ReadVInt32();
BlockPackedReader quotientReader = new BlockPackedReader(data, entry.PackedInt32sVersion, quotientBlockSize, maxDoc, false);
ramBytesUsed.AddAndGet(quotientReader.RamBytesUsed());
return new NumericDocValuesAnonymousInnerClassHelper3(min, mult, quotientReader);
default:
throw new InvalidOperationException();
}
}
private class NumericDocValuesAnonymousInnerClassHelper : NumericDocValues
{
private readonly long[] decode;
private readonly PackedInt32s.Reader ordsReader;
public NumericDocValuesAnonymousInnerClassHelper(long[] decode, PackedInt32s.Reader ordsReader)
{
this.decode = decode;
this.ordsReader = ordsReader;
}
public override long Get(int docID)
{
return decode[(int)ordsReader.Get(docID)];
}
}
private class NumericDocValuesAnonymousInnerClassHelper2 : NumericDocValues
{
private readonly byte[] bytes;
public NumericDocValuesAnonymousInnerClassHelper2(Lucene42DocValuesProducer outerInstance, byte[] bytes)
{
this.bytes = bytes;
}
public override long Get(int docID)
{
return (sbyte)bytes[docID];
}
}
private class NumericDocValuesAnonymousInnerClassHelper3 : NumericDocValues
{
private readonly long min;
private readonly long mult;
private readonly BlockPackedReader quotientReader;
public NumericDocValuesAnonymousInnerClassHelper3(long min, long mult, BlockPackedReader quotientReader)
{
this.min = min;
this.mult = mult;
this.quotientReader = quotientReader;
}
public override long Get(int docID)
{
return min + mult * quotientReader.Get(docID);
}
}
public override BinaryDocValues GetBinary(FieldInfo field)
{
lock (this)
{
BinaryDocValues instance;
if (!binaryInstances.TryGetValue(field.Number, out instance) || instance == null)
{
instance = LoadBinary(field);
binaryInstances[field.Number] = instance;
}
return instance;
}
}
private BinaryDocValues LoadBinary(FieldInfo field)
{
BinaryEntry entry = binaries[field.Number];
data.Seek(entry.Offset);
PagedBytes bytes = new PagedBytes(16);
bytes.Copy(data, entry.NumBytes);
PagedBytes.Reader bytesReader = bytes.Freeze(true);
if (entry.MinLength == entry.MaxLength)
{
int fixedLength = entry.MinLength;
ramBytesUsed.AddAndGet(bytes.RamBytesUsed());
return new BinaryDocValuesAnonymousInnerClassHelper(bytesReader, fixedLength);
}
else
{
MonotonicBlockPackedReader addresses = new MonotonicBlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, maxDoc, false);
ramBytesUsed.AddAndGet(bytes.RamBytesUsed() + addresses.RamBytesUsed());
return new BinaryDocValuesAnonymousInnerClassHelper2(bytesReader, addresses);
}
}
private class BinaryDocValuesAnonymousInnerClassHelper : BinaryDocValues
{
private readonly PagedBytes.Reader bytesReader;
private readonly int fixedLength;
public BinaryDocValuesAnonymousInnerClassHelper(PagedBytes.Reader bytesReader, int fixedLength)
{
this.bytesReader = bytesReader;
this.fixedLength = fixedLength;
}
public override void Get(int docID, BytesRef result)
{
bytesReader.FillSlice(result, fixedLength * (long)docID, fixedLength);
}
}
private class BinaryDocValuesAnonymousInnerClassHelper2 : BinaryDocValues
{
private readonly PagedBytes.Reader bytesReader;
private readonly MonotonicBlockPackedReader addresses;
public BinaryDocValuesAnonymousInnerClassHelper2(PagedBytes.Reader bytesReader, MonotonicBlockPackedReader addresses)
{
this.bytesReader = bytesReader;
this.addresses = addresses;
}
public override void Get(int docID, BytesRef result)
{
long startAddress = docID == 0 ? 0 : addresses.Get(docID - 1);
long endAddress = addresses.Get(docID);
bytesReader.FillSlice(result, startAddress, (int)(endAddress - startAddress));
}
}
public override SortedDocValues GetSorted(FieldInfo field)
{
FSTEntry entry = fsts[field.Number];
FST<long?> instance;
lock (this)
{
if (!fstInstances.TryGetValue(field.Number, out instance) || instance == null)
{
data.Seek(entry.Offset);
instance = new FST<long?>(data, PositiveInt32Outputs.Singleton);
ramBytesUsed.AddAndGet(instance.GetSizeInBytes());
fstInstances[field.Number] = instance;
}
}
var docToOrd = GetNumeric(field);
var fst = instance;
// per-thread resources
var @in = fst.GetBytesReader();
var firstArc = new FST.Arc<long?>();
var scratchArc = new FST.Arc<long?>();
var scratchInts = new Int32sRef();
var fstEnum = new BytesRefFSTEnum<long?>(fst);
return new SortedDocValuesAnonymousInnerClassHelper(entry, docToOrd, fst, @in, firstArc, scratchArc, scratchInts, fstEnum);
}
private class SortedDocValuesAnonymousInnerClassHelper : SortedDocValues
{
private readonly FSTEntry entry;
private readonly NumericDocValues docToOrd;
private readonly FST<long?> fst;
private readonly FST.BytesReader @in;
private readonly FST.Arc<long?> firstArc;
private readonly FST.Arc<long?> scratchArc;
private readonly Int32sRef scratchInts;
private readonly BytesRefFSTEnum<long?> fstEnum;
public SortedDocValuesAnonymousInnerClassHelper(FSTEntry entry, NumericDocValues docToOrd, FST<long?> fst, FST.BytesReader @in, FST.Arc<long?> firstArc, FST.Arc<long?> scratchArc, Int32sRef scratchInts, BytesRefFSTEnum<long?> fstEnum)
{
this.entry = entry;
this.docToOrd = docToOrd;
this.fst = fst;
this.@in = @in;
this.firstArc = firstArc;
this.scratchArc = scratchArc;
this.scratchInts = scratchInts;
this.fstEnum = fstEnum;
}
public override int GetOrd(int docID)
{
return (int)docToOrd.Get(docID);
}
public override void LookupOrd(int ord, BytesRef result)
{
try
{
@in.Position = 0;
fst.GetFirstArc(firstArc);
Int32sRef output = YAF.Lucene.Net.Util.Fst.Util.GetByOutput(fst, ord, @in, firstArc, scratchArc, scratchInts);
result.Bytes = new byte[output.Length];
result.Offset = 0;
result.Length = 0;
Util.ToBytesRef(output, result);
}
catch (System.IO.IOException bogus)
{
throw new Exception(bogus.ToString(), bogus);
}
}
public override int LookupTerm(BytesRef key)
{
try
{
BytesRefFSTEnum.InputOutput<long?> o = fstEnum.SeekCeil(key);
if (o == null)
{
return -ValueCount - 1;
}
else if (o.Input.Equals(key))
{
return (int)o.Output.GetValueOrDefault();
}
else
{
return (int)-o.Output.GetValueOrDefault() - 1;
}
}
catch (System.IO.IOException bogus)
{
throw new Exception(bogus.ToString(), bogus);
}
}
public override int ValueCount
{
get
{
return (int)entry.NumOrds;
}
}
public override TermsEnum GetTermsEnum()
{
return new FSTTermsEnum(fst);
}
}
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
FSTEntry entry = fsts[field.Number];
if (entry.NumOrds == 0)
{
return DocValues.EMPTY_SORTED_SET; // empty FST!
}
FST<long?> instance;
lock (this)
{
if (!fstInstances.TryGetValue(field.Number, out instance) || instance == null)
{
data.Seek(entry.Offset);
instance = new FST<long?>(data, PositiveInt32Outputs.Singleton);
ramBytesUsed.AddAndGet(instance.GetSizeInBytes());
fstInstances[field.Number] = instance;
}
}
BinaryDocValues docToOrds = GetBinary(field);
FST<long?> fst = instance;
// per-thread resources
var @in = fst.GetBytesReader();
var firstArc = new FST.Arc<long?>();
var scratchArc = new FST.Arc<long?>();
var scratchInts = new Int32sRef();
var fstEnum = new BytesRefFSTEnum<long?>(fst);
var @ref = new BytesRef();
var input = new ByteArrayDataInput();
return new SortedSetDocValuesAnonymousInnerClassHelper(entry, docToOrds, fst, @in, firstArc, scratchArc, scratchInts, fstEnum, @ref, input);
}
private class SortedSetDocValuesAnonymousInnerClassHelper : SortedSetDocValues
{
private readonly FSTEntry entry;
private readonly BinaryDocValues docToOrds;
private readonly FST<long?> fst;
private readonly FST.BytesReader @in;
private readonly FST.Arc<long?> firstArc;
private readonly FST.Arc<long?> scratchArc;
private readonly Int32sRef scratchInts;
private readonly BytesRefFSTEnum<long?> fstEnum;
private readonly BytesRef @ref;
private readonly ByteArrayDataInput input;
public SortedSetDocValuesAnonymousInnerClassHelper(FSTEntry entry, BinaryDocValues docToOrds, FST<long?> fst, FST.BytesReader @in, FST.Arc<long?> firstArc, FST.Arc<long?> scratchArc, Int32sRef scratchInts, BytesRefFSTEnum<long?> fstEnum, BytesRef @ref, ByteArrayDataInput input)
{
this.entry = entry;
this.docToOrds = docToOrds;
this.fst = fst;
this.@in = @in;
this.firstArc = firstArc;
this.scratchArc = scratchArc;
this.scratchInts = scratchInts;
this.fstEnum = fstEnum;
this.@ref = @ref;
this.input = input;
}
private long currentOrd;
public override long NextOrd()
{
if (input.Eof)
{
return NO_MORE_ORDS;
}
else
{
currentOrd += input.ReadVInt64();
return currentOrd;
}
}
public override void SetDocument(int docID)
{
docToOrds.Get(docID, @ref);
input.Reset(@ref.Bytes, @ref.Offset, @ref.Length);
currentOrd = 0;
}
public override void LookupOrd(long ord, BytesRef result)
{
try
{
@in.Position = 0;
fst.GetFirstArc(firstArc);
Int32sRef output = YAF.Lucene.Net.Util.Fst.Util.GetByOutput(fst, ord, @in, firstArc, scratchArc, scratchInts);
result.Bytes = new byte[output.Length];
result.Offset = 0;
result.Length = 0;
Lucene.Net.Util.Fst.Util.ToBytesRef(output, result);
}
catch (System.IO.IOException bogus)
{
throw new Exception(bogus.ToString(), bogus);
}
}
public override long LookupTerm(BytesRef key)
{
try
{
var o = fstEnum.SeekCeil(key);
if (o == null)
{
return -ValueCount - 1;
}
else if (o.Input.Equals(key))
{
return (int)o.Output.GetValueOrDefault();
}
else
{
return -o.Output.GetValueOrDefault() - 1;
}
}
catch (System.IO.IOException bogus)
{
throw new Exception(bogus.ToString(), bogus);
}
}
public override long ValueCount
{
get
{
return entry.NumOrds;
}
}
public override TermsEnum GetTermsEnum()
{
return new FSTTermsEnum(fst);
}
}
public override IBits GetDocsWithField(FieldInfo field)
{
if (field.DocValuesType == DocValuesType.SORTED_SET)
{
return DocValues.DocsWithValue(GetSortedSet(field), maxDoc);
}
else
{
return new Lucene.Net.Util.Bits.MatchAllBits(maxDoc);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
data.Dispose();
}
}
internal class NumericEntry
{
internal long Offset { get; set; }
internal sbyte Format { get; set; }
/// <summary>
/// NOTE: This was packedIntsVersion (field) in Lucene
/// </summary>
internal int PackedInt32sVersion { get; set; }
}
internal class BinaryEntry
{
internal long Offset { get; set; }
internal long NumBytes { get; set; }
internal int MinLength { get; set; }
internal int MaxLength { get; set; }
/// <summary>
/// NOTE: This was packedIntsVersion (field) in Lucene
/// </summary>
internal int PackedInt32sVersion { get; set; }
internal int BlockSize { get; set; }
}
internal class FSTEntry
{
internal long Offset { get; set; }
internal long NumOrds { get; set; }
}
// exposes FSTEnum directly as a TermsEnum: avoids binary-search next()
internal class FSTTermsEnum : TermsEnum
{
internal readonly BytesRefFSTEnum<long?> @in;
// this is all for the complicated seek(ord)...
// maybe we should add a FSTEnum that supports this operation?
internal readonly FST<long?> fst;
internal readonly FST.BytesReader bytesReader;
internal readonly FST.Arc<long?> firstArc = new FST.Arc<long?>();
internal readonly FST.Arc<long?> scratchArc = new FST.Arc<long?>();
internal readonly Int32sRef scratchInts = new Int32sRef();
internal readonly BytesRef scratchBytes = new BytesRef();
internal FSTTermsEnum(FST<long?> fst)
{
this.fst = fst;
@in = new BytesRefFSTEnum<long?>(fst);
bytesReader = fst.GetBytesReader();
}
public override BytesRef Next()
{
var io = @in.Next();
if (io == null)
{
return null;
}
else
{
return io.Input;
}
}
public override IComparer<BytesRef> Comparer
{
get
{
return BytesRef.UTF8SortedAsUnicodeComparer;
}
}
public override SeekStatus SeekCeil(BytesRef text)
{
if (@in.SeekCeil(text) == null)
{
return SeekStatus.END;
}
else if (Term.Equals(text))
{
// TODO: add SeekStatus to FSTEnum like in https://issues.apache.org/jira/browse/LUCENE-3729
// to remove this comparision?
return SeekStatus.FOUND;
}
else
{
return SeekStatus.NOT_FOUND;
}
}
public override bool SeekExact(BytesRef text)
{
if (@in.SeekExact(text) == null)
{
return false;
}
else
{
return true;
}
}
public override void SeekExact(long ord)
{
// TODO: would be better to make this simpler and faster.
// but we dont want to introduce a bug that corrupts our enum state!
bytesReader.Position = 0;
fst.GetFirstArc(firstArc);
Int32sRef output = YAF.Lucene.Net.Util.Fst.Util.GetByOutput(fst, ord, bytesReader, firstArc, scratchArc, scratchInts);
scratchBytes.Bytes = new byte[output.Length];
scratchBytes.Offset = 0;
scratchBytes.Length = 0;
Lucene.Net.Util.Fst.Util.ToBytesRef(output, scratchBytes);
// TODO: we could do this lazily, better to try to push into FSTEnum though?
@in.SeekExact(scratchBytes);
}
public override BytesRef Term
{
get { return @in.Current.Input; }
}
public override long Ord
{
get { return @in.Current.Output.GetValueOrDefault(); }
}
public override int DocFreq
{
get { throw new System.NotSupportedException(); }
}
public override long TotalTermFreq
{
get { throw new System.NotSupportedException(); }
}
public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
throw new System.NotSupportedException();
}
public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags)
{
throw new System.NotSupportedException();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using Nini.Config;
using OpenMetaverse;
using Aurora.Framework;
using Aurora.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
/*****************************************************
*
* ScriptsHttpRequests
*
* Implements the llHttpRequest and http_response
* callback.
*
* Some stuff was already in LSLLongCmdHandler, and then
* there was this file with a stub class in it. So,
* I am moving some of the objects and functions out of
* LSLLongCmdHandler, such as the HttpRequestClass, the
* start and stop methods, and setting up pending and
* completed queues. These are processed in the
* LSLLongCmdHandler polling loop. Similiar to the
* XMLRPCModule, since that seems to work.
*
* This probably needs some throttling mechanism but
* it's wide open right now. This applies to
* number of requests
*
* Linden puts all kinds of header fields in the requests.
* User-Agent
* X-SecondLife-Shard
* X-SecondLife-Object-Name
* X-SecondLife-Object-Key
* X-SecondLife-Region
* X-SecondLife-Local-Position
* X-SecondLife-Local-Velocity
* X-SecondLife-Local-Rotation
* X-SecondLife-Owner-Name
* X-SecondLife-Owner-Key
*
* HTTPS support
*
* Configurable timeout?
* Configurable max response size?
* Configurable
*
* **************************************************/
namespace Aurora.Modules.Scripting
{
public class HttpRequestModule : INonSharedRegionModule, IHttpRequestModule
{
private readonly object HttpListLock = new object();
private readonly Dictionary<UUID, HTTPMax> m_numberOfPrimHTTPRequests = new Dictionary<UUID, HTTPMax>();
private readonly Dictionary<UUID, UUID> m_reqID2itemID = new Dictionary<UUID, UUID>();
private int DEFAULT_BODY_MAXLENGTH = 2048;
private int MaxNumberOfHTTPRequestsPerSecond = 1;
private int httpTimeout = 30000;
private string m_name = "HttpScriptRequests";
// <itemID, HttpRequestClasss>
private Dictionary<UUID, List<HttpRequestClass>> m_pendingRequests;
private string m_proxyexcepts = "";
private string m_proxyurl = "";
// <reqID, itemID>
private IScene m_scene;
private IScriptModule m_scriptModule;
// private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>();
public HttpRequestModule()
{
ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertificate;
}
public bool IsSharedModule
{
get { return true; }
}
#region IHttpRequestModule Members
public UUID MakeHttpRequest(string url, string parameters, string body)
{
//Make sure that the cmd handler thread is running
m_scriptModule.PokeThreads(UUID.Zero);
return UUID.Zero;
}
public UUID StartHttpRequest(UUID primID, UUID itemID, string url, List<string> parameters,
Dictionary<string, string> headers, string body)
{
UUID reqID = UUID.Random();
HttpRequestClass htc = new HttpRequestClass();
// Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/LlHTTPRequest
//
// Parameters are expected in {key, value, ... , key, value}
int BODY_MAXLENGTH = DEFAULT_BODY_MAXLENGTH;
if (parameters != null)
{
string[] parms = parameters.ToArray();
for (int i = 0; i < parms.Length; i += 2)
{
switch (Int32.Parse(parms[i]))
{
case (int) HttpRequestConstants.HTTP_METHOD:
htc.HttpMethod = parms[i + 1];
break;
case (int) HttpRequestConstants.HTTP_MIMETYPE:
htc.HttpMIMEType = parms[i + 1];
break;
case (int) HttpRequestConstants.HTTP_BODY_MAXLENGTH:
BODY_MAXLENGTH = int.Parse(parms[i + 1]);
break;
case (int) HttpRequestConstants.HTTP_VERIFY_CERT:
htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
break;
}
}
}
bool ShouldProcess = true;
HTTPMax r = null;
if (!m_numberOfPrimHTTPRequests.TryGetValue(primID, out r))
r = new HTTPMax();
if (DateTime.Now.AddSeconds(1).Ticks > r.LastTicks)
r.Number = 0;
if (r.Number++ > MaxNumberOfHTTPRequestsPerSecond)
{
ShouldProcess = false; //Too many for this prim, return status 499
htc.Status = (int) OSHttpStatusCode.ClientErrorJoker;
htc.Finished = true;
}
htc.PrimID = primID;
htc.ItemID = itemID;
htc.Url = url;
htc.MaxLength = BODY_MAXLENGTH;
htc.ReqID = reqID;
htc.HttpTimeout = httpTimeout;
htc.OutboundBody = body;
htc.ResponseHeaders = headers;
htc.proxyurl = m_proxyurl;
htc.proxyexcepts = m_proxyexcepts;
lock (HttpListLock)
{
if (m_pendingRequests.ContainsKey(itemID))
m_pendingRequests[itemID].Add(htc);
else
{
m_reqID2itemID.Add(reqID, itemID);
m_pendingRequests.Add(itemID, new List<HttpRequestClass> {htc});
}
}
if (ShouldProcess)
htc.Process();
//Make sure that the cmd handler thread is running
m_scriptModule.PokeThreads(itemID);
return reqID;
}
public void StopHttpRequest(UUID primID, UUID m_itemID)
{
//Make sure that the cmd handler thread is running
m_scriptModule.PokeThreads(m_itemID);
//Kill all requests and return
if (m_pendingRequests != null)
{
lock (HttpListLock)
{
List<HttpRequestClass> tmpReqs;
if (m_pendingRequests.TryGetValue(m_itemID, out tmpReqs))
{
foreach (HttpRequestClass tmpReq in tmpReqs)
{
tmpReq.Stop();
}
}
m_pendingRequests.Remove(m_itemID);
}
}
}
public int GetRequestCount()
{
return m_pendingRequests.Count;
}
public IServiceRequest GetNextCompletedRequest()
{
if (m_pendingRequests.Count == 0)
return null;
lock (HttpListLock)
{
foreach (HttpRequestClass luid in from luids in m_pendingRequests.Values from luid in luids where luid.Finished select luid)
{
return luid;
}
}
return null;
}
public void RemoveCompletedRequest(IServiceRequest reqid)
{
HttpRequestClass req = (HttpRequestClass) reqid;
lock (HttpListLock)
{
List<HttpRequestClass> tmpReqs;
if (m_pendingRequests.TryGetValue(req.ItemID, out tmpReqs))
{
for (int i = 0; i < tmpReqs.Count; i++)
{
if (tmpReqs[i].ReqID == req.ReqID)
{
tmpReqs[i].Stop();
tmpReqs.RemoveAt(i);
}
}
if (tmpReqs.Count == 1)
m_pendingRequests.Remove(req.ItemID);
else
m_pendingRequests[req.ItemID] = tmpReqs;
}
}
}
#endregion
#region INonSharedRegionModule Members
public void Initialise(IConfigSource config)
{
m_proxyurl = config.Configs["HTTPScriptModule"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["HTTPScriptModule"].GetString("HttpProxyExceptions");
m_pendingRequests = new Dictionary<UUID, List<HttpRequestClass>>();
}
public void AddRegion(IScene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
}
public void RemoveRegion(IScene scene)
{
}
public void RegionLoaded(IScene scene)
{
m_scriptModule = scene.RequestModuleInterface<IScriptModule>();
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
#endregion
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
HttpWebRequest Request = (HttpWebRequest) sender;
if (Request.Headers.Get("NoVerifyCert") != null)
{
return true;
}
if ((((int) sslPolicyErrors) & ~4) != 0)
return false;
#pragma warning disable 618
if (ServicePointManager.CertificatePolicy != null)
{
ServicePoint sp = Request.ServicePoint;
return ServicePointManager.CertificatePolicy.CheckValidationResult(sp, certificate, Request, 0);
}
#pragma warning restore 618
return true;
}
public void PostInitialise()
{
}
#region Nested type: HTTPMax
public class HTTPMax
{
public long LastTicks;
public int Number;
}
#endregion
}
public class HttpRequestClass : IHttpRequestClass
{
// Constants for parameters
// public const int HTTP_BODY_MAXLENGTH = 2;
// public const int HTTP_METHOD = 0;
// public const int HTTP_MIMETYPE = 1;
// public const int HTTP_VERIFY_CERT = 3;
public string HttpMIMEType = "text/plain;charset=utf-8";
public string HttpMethod = "GET";
public int HttpTimeout;
public bool HttpVerifyCert = true;
public int MaxLength;
public object[] _Metadata = new object[0];
public object[] Metadata
{
get { return _Metadata; }
set { _Metadata = value; }
}
public DateTime Next;
public string OutboundBody;
public HttpWebRequest Request;
public string ResponseBody { get; set; }
public Dictionary<string, string> ResponseHeaders;
public List<string> ResponseMetadata;
public int Status { get; set; }
public string Url;
private bool _finished;
private Thread httpThread;
public string proxyexcepts;
public string proxyurl;
#region IServiceRequest Members
public bool Finished
{
get { return _finished; }
set { _finished = value; }
}
public UUID ItemID { get; set; }
public UUID PrimID { get; set; }
public UUID ReqID { get; set; }
public void Process()
{
httpThread = new Thread(SendRequest)
{Name = "HttpRequestThread", Priority = ThreadPriority.Lowest, IsBackground = true};
_finished = false;
httpThread.Start();
}
/*
* TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception
*/
public void SendRequest()
{
Culture.SetCurrentCulture();
HttpWebResponse response = null;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
string tempString = null;
int count = 0;
try
{
Request = (HttpWebRequest) WebRequest.Create(Url);
Request.Method = HttpMethod;
Request.ContentType = HttpMIMEType;
if (!HttpVerifyCert)
{
// Connection Group Name is probably not used so we hijack it to identify
// a desired security exception
// Request.ConnectionGroupName="NoVerify";
Request.Headers.Add("NoVerifyCert", "true");
}
// else
// {
// Request.ConnectionGroupName="Verify";
// }
if (!string.IsNullOrEmpty(proxyurl))
{
if (!string.IsNullOrEmpty(proxyexcepts))
{
string[] elist = proxyexcepts.Split(';');
Request.Proxy = new WebProxy(proxyurl, true, elist);
}
else
{
Request.Proxy = new WebProxy(proxyurl, true);
}
}
foreach (KeyValuePair<string, string> entry in ResponseHeaders)
if (entry.Key.ToLower().Equals("user-agent"))
Request.UserAgent = entry.Value;
else
Request.Headers[entry.Key] = entry.Value;
// Encode outbound data
if (OutboundBody.Length > 0)
{
byte[] data = Util.UTF8.GetBytes(OutboundBody);
Request.ContentLength = data.Length;
Stream bstream = Request.GetRequestStream();
bstream.Write(data, 0, data.Length);
bstream.Close();
}
Request.Timeout = HttpTimeout;
// execute the request
try
{
// execute the request
response = (HttpWebResponse) Request.GetResponse();
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.ProtocolError)
{
throw;
}
response = (HttpWebResponse)e.Response;
}
Status = (int)response.StatusCode;
Stream resStream = response.GetResponseStream();
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Util.UTF8.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
} while (count > 0); // any more data to read?
ResponseBody = sb.ToString();
if (ResponseBody.Length > MaxLength) //Cut it off then
{
ResponseBody = ResponseBody.Remove(MaxLength);
//Add the metaData
Metadata = new object[2] {0, MaxLength};
}
}
catch (Exception e)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = e.Message;
_finished = true;
return;
}
finally
{
if (response != null)
response.Close();
}
Status = (int)HttpStatusCode.OK;
_finished = true;
}
public void Stop()
{
try
{
httpThread.Abort();
}
catch (Exception)
{
}
}
#endregion
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System;
using System.Reflection;
using System.Xml.Serialization;
using System.Security.Cryptography.X509Certificates;
namespace Igor
{
public interface IIgorEditorCore
{
List<string> GetEnabledModuleNames();
IgorHelperDelegateStub GetHelperDelegates();
void RunJobInst();
}
public class IgorHelperDelegateStub
{
public bool bIsValid = false;
public delegate void VoidOneStringParam(string Param1);
// These are duplicated from IgorRuntimeUtils.cs in the Core module. This was necessary to
// keep the updater working, but they are overridden by the RuntimeUtils version once Core is
// installed. If you have any fixes for these two functions, fix them both here and in
// IgorRuntimeUtils.cs.
public static void UpdaterDeleteFile(string TargetFile)
{
if(File.Exists(TargetFile))
{
File.SetAttributes(TargetFile, System.IO.FileAttributes.Normal);
File.Delete(TargetFile);
}
}
// These are duplicated from IgorRuntimeUtils.cs in the Core module. This was necessary to
// keep the updater working, but they are overridden by the RuntimeUtils version once Core is
// installed. If you have any fixes for these two functions, fix them both here and in
// IgorRuntimeUtils.cs.
public static void UpdaterDeleteDirectory(string targetDir)
{
if(!Directory.Exists(targetDir))
{
return;
}
System.IO.File.SetAttributes(targetDir, System.IO.FileAttributes.Normal);
string[] files = System.IO.Directory.GetFiles(targetDir);
string[] dirs = System.IO.Directory.GetDirectories(targetDir);
foreach (string file in files)
{
System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
System.IO.File.Delete(file);
}
foreach (string dir in dirs)
{
UpdaterDeleteDirectory(dir);
}
System.IO.Directory.Delete(targetDir, false);
}
// These are duplicated from IgorRuntimeUtils.cs in the Core module. This was necessary to
// keep the updater working, but they are overridden by the RuntimeUtils version once Core is
// installed. If you have any fixes for these two functions, fix them both here and in
// IgorRuntimeUtils.cs.
public static bool UpdaterCopyFile(string SourceFile, string TargetFile)
{
if(File.Exists(SourceFile))
{
if(File.Exists(TargetFile))
{
UpdaterDeleteFile(TargetFile);
}
try
{
File.Copy(SourceFile, TargetFile);
}
catch(System.IO.IOException IOEx)
{
if(IOEx.GetHashCode() == 112)
{
Debug.LogError("Failed to copy file " + SourceFile + " to " + TargetFile + " because there is not enough free space at the target location.");
}
throw IOEx;
return false;
}
return true;
}
return false;
}
public delegate List<Type> TemplatedTypeListNoParams();
public List<Type> DoNothingTemplatedTypeListNoParams()
{
return new List<Type>();
}
public delegate void VoidOneBoolParam(bool Param1);
public void DoNothingVoidOneBoolParam(bool Param1)
{}
public delegate bool BoolNoParams();
public bool DoNothingBoolNoParams()
{
return false;
}
public delegate bool BoolStringParam(string Param1);
public bool DoNothingBoolStringParam(string Param1)
{
return false;
}
public delegate void VoidStringBoolParams(string Param1, bool Param2);
public void DoNothingVoidStringBoolParams(string Param1, bool Param2)
{}
public delegate bool BoolStringStringParams(string Param1, string Param2);
public bool DoNothingBoolStringStringParams(string Param1, string Param2)
{
return false;
}
public VoidOneStringParam DeleteFile;
public VoidOneStringParam DeleteDirectory;
public BoolStringStringParams CopyFile;
public TemplatedTypeListNoParams GetTypesInheritFromIIgorEditorCore;
public VoidOneBoolParam IgorJobConfig_SetWasMenuTriggered;
public BoolNoParams IgorJobConfig_GetWasMenuTriggered;
public BoolStringParam IgorJobConfig_IsBoolParamSet;
public VoidStringBoolParams IgorJobConfig_SetBoolParam;
public IgorHelperDelegateStub()
{
DeleteFile = UpdaterDeleteFile;
DeleteDirectory = UpdaterDeleteDirectory;
CopyFile = UpdaterCopyFile;
GetTypesInheritFromIIgorEditorCore = DoNothingTemplatedTypeListNoParams;
IgorJobConfig_SetWasMenuTriggered = DoNothingVoidOneBoolParam;
IgorJobConfig_GetWasMenuTriggered = DoNothingBoolNoParams;
IgorJobConfig_IsBoolParamSet = DoNothingBoolStringParam;
IgorJobConfig_SetBoolParam = DoNothingVoidStringBoolParams;
}
}
public partial class IgorUtils
{
public static List<Type> GetTypesWith<TAttribute>(bool bInherit) where TAttribute : Attribute
{
List<Type> AllTypes = new List<Type>();
Assembly[] Assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach(Assembly CurrentAssembly in Assemblies)
{
foreach(Type CurrentType in CurrentAssembly.GetTypes())
{
if(CurrentType.IsDefined(typeof(TAttribute), bInherit))
{
AllTypes.Add(CurrentType);
}
}
}
return AllTypes;
}
public static string GetLocalFileFromModuleFilename(string Filename)
{
string LocalFileName = Filename;
if(LocalFileName.StartsWith("("))
{
LocalFileName = LocalFileName.Substring(LocalFileName.IndexOf(")") + 1);
}
LocalFileName = LocalFileName.Replace("[", "");
LocalFileName = LocalFileName.Replace("]", "");
return LocalFileName;
}
public static string GetRemoteFileFromModuleFilename(string RootPath, string Filename, ref bool bIsRemote)
{
string RemoteFileName = Filename;
bIsRemote = false;
if(RemoteFileName.StartsWith("("))
{
RemoteFileName = RemoteFileName.Replace("(", "");
RemoteFileName = RemoteFileName.Replace(")", "");
bIsRemote = true;
RemoteFileName = RemoteFileName.Replace("../", "");
}
else
{
if(RemoteFileName.StartsWith("."))
{
RemoteFileName = RemoteFileName.Substring(RemoteFileName.LastIndexOf("/") + 1);
}
RemoteFileName = RootPath + RemoteFileName;
}
if(RemoteFileName.Contains("["))
{
int IndexStart = RemoteFileName.IndexOf("[");
int IndexEnd = RemoteFileName.LastIndexOf("]") + 1;
RemoteFileName = RemoteFileName.Replace(RemoteFileName.Substring(IndexStart, IndexEnd - IndexStart), "");
}
return RemoteFileName;
}
public static string DownloadFileForUpdate(string RelativePath, string AbsolutePath = "", bool bIgnoreErrors = false)
{
string DestFilePath = Path.Combine(IgorUpdater.TempLocalDirectory, RelativePath);
try
{
if(File.Exists(DestFilePath))
{
IgorUpdater.HelperDelegates.DeleteFile(DestFilePath);
}
if(!Directory.Exists(Path.GetDirectoryName(DestFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(DestFilePath));
}
if(IgorUpdater.bLocalDownload && AbsolutePath == "")
{
string ParentDirectory = Directory.GetCurrentDirectory();
string NewLocalPrefix = IgorUpdater.LocalPrefix;
while(NewLocalPrefix.StartsWith(".."))
{
ParentDirectory = Directory.GetParent(ParentDirectory).ToString();
NewLocalPrefix = NewLocalPrefix.Substring(3);
}
NewLocalPrefix = Path.Combine(ParentDirectory, NewLocalPrefix);
string LocalFilePath = Path.Combine(NewLocalPrefix, RelativePath);
if(File.Exists(LocalFilePath))
{
IgorUpdater.HelperDelegates.CopyFile(LocalFilePath, DestFilePath);
}
}
else
{
string PathToSource = string.Empty;
if(AbsolutePath == "")
{
PathToSource = IgorUpdater.RemotePrefix + RelativePath;
}
else
{
PathToSource = AbsolutePath;
}
PathToSource = PathToSource.Replace("\\", "/");
WWW www = new WWW(PathToSource);
while(!www.isDone)
{ }
if(www.error != null && www.error != "")
{
if(!bIgnoreErrors)
{
Debug.LogError("Igor Error: Downloading " + PathToSource + " failed. Error is \"" + www.error + "\"");
}
}
else
{
File.WriteAllBytes(DestFilePath, www.bytes);
}
www.Dispose();
}
}
catch(Exception e)
{
Debug.LogError("Igor Error: Failed to download file " + RelativePath + " with error " + e.ToString());
}
return DestFilePath;
}
}
[XmlRoot("IgorModuleList")]
public class IgorModuleList
{
public class ModuleItem
{
[XmlAttribute("ModuleName")]
public string ModuleName;
[XmlAttribute("ModuleDescriptorRelativePath")]
public string ModuleDescriptorRelativePath;
}
[XmlArray("Modules")]
[XmlArrayItem("Module")]
public List<ModuleItem> Modules = new List<ModuleItem>();
public void Save(string path)
{
XmlSerializer serializer = new XmlSerializer(typeof(IgorModuleList));
IgorUpdater.HelperDelegates.DeleteFile(path);
using(FileStream stream = new FileStream(path, FileMode.Create))
{
serializer.Serialize(stream, this);
}
}
public static IgorModuleList Load(string path)
{
XmlSerializer serializer = new XmlSerializer(typeof(IgorModuleList));
if(File.Exists(path))
{
File.SetAttributes(path, System.IO.FileAttributes.Normal);
using(var stream = new FileStream(path, FileMode.Open))
{
return serializer.Deserialize(stream) as IgorModuleList;
}
}
return null;
}
}
[XmlRoot("IgorModuleDescriptor")]
public class IgorModuleDescriptor
{
public string ModuleName;
public int ModuleVersion;
[XmlArray("ModuleFiles")]
[XmlArrayItem("File")]
public List<string> ModuleFiles = new List<string>();
[XmlArray("ModuleDependencies")]
[XmlArrayItem("Module")]
public List<string> ModuleDependencies = new List<string>();
public void Save(string path)
{
XmlSerializer serializer = new XmlSerializer(typeof(IgorModuleDescriptor));
IgorUpdater.HelperDelegates.DeleteFile(path);
using(FileStream stream = new FileStream(path, FileMode.Create))
{
serializer.Serialize(stream, this);
}
}
public static IgorModuleDescriptor Load(string path)
{
XmlSerializer serializer = new XmlSerializer(typeof(IgorModuleDescriptor));
if(File.Exists(path))
{
File.SetAttributes(path, System.IO.FileAttributes.Normal);
}
using(var stream = new FileStream(path, FileMode.Open))
{
return serializer.Deserialize(stream) as IgorModuleDescriptor;
}
}
}
[InitializeOnLoad]
public class IgorUpdater
{
private static IgorHelperDelegateStub _HelperDelegates = null;
public static IgorHelperDelegateStub HelperDelegates {
get {
if(_HelperDelegates == null)
{
Type IgorEditorCoreType = Type.GetType("IgorEditorCore");
if(IgorEditorCoreType != null)
{
IIgorEditorCore EditorCoreInst = (IIgorEditorCore)Activator.CreateInstance(IgorEditorCoreType);
_HelperDelegates = EditorCoreInst.GetHelperDelegates();
}
else
{
_HelperDelegates = new IgorHelperDelegateStub();
}
}
return _HelperDelegates;
}
set {
_HelperDelegates = value;
}
}
static string kPrefix = "Igor_";
[PreferenceItem("Igor")]
static void PreferencesGUI()
{
bDontUpdate = EditorGUILayout.Toggle(new GUIContent("Don't auto-update", "No updating Igor files from local or remote sources"), bDontUpdate);
bAlwaysUpdate = EditorGUILayout.Toggle(new GUIContent("Always update", "Update even if the versions match"), bAlwaysUpdate);
bLocalDownload = EditorGUILayout.Toggle(new GUIContent("Local update", "Update from local directory instead of remotely from GitHub"), bLocalDownload);
bDownloadRemoteWhenLocal = EditorGUILayout.Toggle(new GUIContent("Download remote repos in local", "For modules that have externally hosted content. Enable this if you want Igor to pull the latest version from the remote host even during a local update."), bDownloadRemoteWhenLocal);
LocalPrefix = EditorGUILayout.TextField(new GUIContent("Local Update Directory", "This is the local directory (relative to the project root) to pull from when Local Update is enabled."), LocalPrefix);
}
public static bool bDontUpdate
{
get { return EditorPrefs.GetBool(kPrefix + "bDontUpdate", false); }
set { EditorPrefs.SetBool(kPrefix + "bDontUpdate", value); }
}
public static bool bAlwaysUpdate
{
get { return EditorPrefs.GetBool(kPrefix + "bAlwaysUpdate", false); }
set { EditorPrefs.SetBool(kPrefix + "bAlwaysUpdate", value); }
}
public static bool bLocalDownload
{
get { return EditorPrefs.GetBool(kPrefix + "bLocalDownload", false); }
set { EditorPrefs.SetBool(kPrefix + "bLocalDownload", value); }
}
public static bool bDownloadRemoteWhenLocal
{
get { return EditorPrefs.GetBool(kPrefix + "bDownloadRemoteWhenLocal", false); }
set { EditorPrefs.SetBool(kPrefix + "bDownloadRemoteWhenLocal", value); }
}
public static string LocalPrefix
{
get { return EditorPrefs.GetString(kPrefix + "LocalPrefix", ""); }
set { EditorPrefs.SetString(kPrefix + "LocalPrefix", value); }
}
static IgorUpdater()
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender, X509Certificate certificate,
X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
};
EditorApplication.update += CheckIfResuming;
}
private const int Version = 33;
private const int MajorUpgrade = 2;
private static string OldBaseIgorDirectory = Path.Combine("Assets", Path.Combine("Editor", "Igor"));
public static string BaseIgorDirectory = Path.Combine("Assets", "Igor");
public static string RemotePrefix = "https://raw.githubusercontent.com/mikamikem/Igor/master/";
public static string TempLocalDirectory = "IgorTemp/";
private static string IgorUpdaterBaseFilename = "IgorUpdater.cs";
public static string IgorUpdaterFilename = Path.Combine("Editor", IgorUpdaterBaseFilename);
public static string IgorUpdaterURL = "Editor/" + IgorUpdaterBaseFilename;
public static string IgorModulesListFilename = "IgorModuleList.xml";
public static string InstalledModulesListPath = Path.Combine(BaseIgorDirectory, IgorModulesListFilename);
public static string IgorLocalModulesListFilename = "IgorLocalModulesList.xml";
public static string InstalledLocalModulesListPath = Path.Combine(BaseIgorDirectory, IgorLocalModulesListFilename);
private static IgorModuleList SharedModuleListInst = null;
public static string LocalModuleRoot = Path.Combine(BaseIgorDirectory, "Modules");
public static string RemoteRelativeModuleRoot = "Modules/";
public static string CoreModuleName = "Core.Core";
public static IIgorEditorCore Core = null;
private static List<string> UpdatedContent = new List<string>();
private static List<string> UpdatedModules = new List<string>();
public static bool bTriggerConfigWindowRefresh = false;
[MenuItem("Window/Igor/Check For Updates %i", false, 2)]
public static void MenuCheckForUpdates()
{
IgorUpdater.bTriggerConfigWindowRefresh = true;
IgorUpdater.CheckForUpdates(true, true);
}
// Returns true if files were updated
public static bool CheckForUpdates(bool bForce = false, bool bFromMenu = false, bool bSynchronous = false)
{
HelperDelegates.IgorJobConfig_SetWasMenuTriggered(bFromMenu);
if(CheckForOneTimeForcedUpgrade())
{
MoveConfigsFromOldLocation();
bForce = true;
}
if(!bDontUpdate || bForce)
{
UpdatedContent.Clear();
bool bMajorUpgrade = false;
if(!HelperDelegates.bIsValid)
{
UpdateCore();
bMajorUpgrade = true;
}
bool bNeedsRebuild = bMajorUpgrade || SelfUpdate(out bMajorUpgrade);
bNeedsRebuild = bMajorUpgrade || UpdateCore() || bNeedsRebuild;
bNeedsRebuild = bMajorUpgrade || UpdateModules() || bNeedsRebuild;
if(CheckForOneTimeForcedUpgrade())
{
RemoveOldDirectory();
bNeedsRebuild = true;
}
if(bNeedsRebuild)
{
HelperDelegates.IgorJobConfig_SetBoolParam("restartingfromupdate", true);
string UpdatedContentString = "The following Igor content was ";
if(bAlwaysUpdate)
{
UpdatedContentString += "forcibly ";
}
UpdatedContentString += "updated via ";
if(bLocalDownload)
{
UpdatedContentString += "local copy from " + LocalPrefix;
}
else
{
UpdatedContentString += "remote copy from GitHub";
}
UpdatedContentString += ", refreshing AssetDatabase:\n";
foreach(var content in UpdatedContent)
{
UpdatedContentString += content + "\n";
}
Debug.Log("Igor Log: " + UpdatedContentString);
ImportAssetOptions options = bSynchronous ? ImportAssetOptions.ForceSynchronousImport : ImportAssetOptions.Default;
AssetDatabase.Refresh(options);
}
return bNeedsRebuild;
}
return false;
}
public static void FindCore()
{
if(Core == null)
{
List<Type> ActiveCores = HelperDelegates.GetTypesInheritFromIIgorEditorCore();
if(ActiveCores.Count > 0)
{
Core = (IIgorEditorCore)Activator.CreateInstance(ActiveCores[0]);
}
}
}
public static void CleanupTemp()
{
IgorUpdater.HelperDelegates.DeleteDirectory(TempLocalDirectory);
}
public static int GetCurrentVersion()
{
return Version;
}
public static int GetVersionFromUpdaterFile(string Filename)
{
if(File.Exists(Filename))
{
string FileContents = File.ReadAllText(Filename);
if(!string.IsNullOrEmpty(FileContents))
{
int StartOfVersionNumber = FileContents.IndexOf("private const int Version = ") + "private const int Version = ".Length;
string VersionNumberString = FileContents.Substring(StartOfVersionNumber, FileContents.IndexOf(";", StartOfVersionNumber) - StartOfVersionNumber);
int VersionNumber = -1;
int.TryParse(VersionNumberString, out VersionNumber);
return VersionNumber;
}
}
return -1;
}
public static int GetMajorUpgradeFromUpdaterFile(string Filename)
{
if(File.Exists(Filename))
{
string FileContents = File.ReadAllText(Filename);
if(!string.IsNullOrEmpty(FileContents))
{
int StartOfVersionNumber = FileContents.IndexOf("private const int MajorUpgrade = ") + "private const int MajorUpgrade = ".Length;
string VersionNumberString = FileContents.Substring(StartOfVersionNumber, FileContents.IndexOf(";", StartOfVersionNumber) - StartOfVersionNumber);
int VersionNumber = -1;
int.TryParse(VersionNumberString, out VersionNumber);
return VersionNumber;
}
}
return -1;
}
public static bool SelfUpdate(out bool bMajorUpgrade)
{
bool bThrewException = false;
bMajorUpgrade = false;
string InstalledFilePath = Path.Combine(BaseIgorDirectory, IgorUpdaterFilename);
try
{
string LocalUpdater = IgorUtils.DownloadFileForUpdate(IgorUpdaterURL);
if(File.Exists(LocalUpdater))
{
int NewVersion = GetVersionFromUpdaterFile(LocalUpdater);
int NewMajorUpgrade = GetMajorUpgradeFromUpdaterFile(LocalUpdater);
if(NewMajorUpgrade > MajorUpgrade)
{
bMajorUpgrade = true;
}
if(NewVersion > Version || bAlwaysUpdate)
{
if(File.Exists(InstalledFilePath))
{
IgorUpdater.HelperDelegates.DeleteFile(InstalledFilePath);
}
if(!Directory.Exists(Path.GetDirectoryName(InstalledFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(InstalledFilePath));
}
IgorUpdater.HelperDelegates.CopyFile(LocalUpdater, InstalledFilePath);
return true;
}
}
}
catch(TimeoutException to)
{
if(!File.Exists(InstalledFilePath))
{
Debug.LogError("Igor Error: Caught exception while self-updating. Exception is " + (to == null ? "NULL exception!" : to.ToString()));
bThrewException = true;
CleanupTemp();
}
}
catch(Exception e)
{
Debug.LogError("Igor Error: Caught exception while self-updating. Exception is " + (e == null ? "NULL exception!" : e.ToString()));
bThrewException = true;
CleanupTemp();
}
if(!HelperDelegates.IgorJobConfig_GetWasMenuTriggered())
{
if(bThrewException)
{
Debug.LogError("Igor Error: Exiting EditorApplication because an exception was thrown.");
if(HelperDelegates.bIsValid)
{
EditorApplication.Exit(-1);
}
}
}
return false;
}
public static bool UpdateCore()
{
bool bThrewException = false;
string LocalModulesList = IgorUtils.DownloadFileForUpdate(IgorModulesListFilename);
try
{
if(File.Exists(LocalModulesList))
{
if(File.Exists(InstalledModulesListPath) && HelperDelegates.bIsValid)
{
IgorUpdater.HelperDelegates.DeleteFile(InstalledModulesListPath);
}
IgorUpdater.HelperDelegates.CopyFile(LocalModulesList, InstalledModulesListPath);
}
UpdatedModules.Clear();
if(UpdateModule(CoreModuleName, false))
{
return true;
}
}
catch(TimeoutException to)
{
if(!File.Exists(LocalModulesList))
{
Debug.LogError("Igor Error: Caught exception while self-updating. Exception is " + (to == null ? "NULL exception!" : to.ToString()));
bThrewException = true;
CleanupTemp();
}
}
catch(Exception e)
{
Debug.LogError("Igor Error: Caught exception while updating core. Exception is " + (e == null ? "NULL exception!" : e.ToString()));
bThrewException = true;
CleanupTemp();
}
if(!HelperDelegates.IgorJobConfig_GetWasMenuTriggered())
{
if(bThrewException)
{
Debug.LogError("Igor Error: Exiting EditorApplication because an exception was thrown.");
if(HelperDelegates.bIsValid)
{
EditorApplication.Exit(-1);
}
}
}
return false;
}
public static bool UpdateModule(string ModuleName, bool ForceUpdate)
{
bool bUpdated = false;
if(File.Exists(InstalledModulesListPath))
{
SharedModuleListInst = IgorModuleList.Load(InstalledModulesListPath);
}
if(SharedModuleListInst != null)
{
foreach(IgorModuleList.ModuleItem CurrentModule in SharedModuleListInst.Modules)
{
if(CurrentModule.ModuleName == ModuleName)
{
string ModuleDescriptor = IgorUtils.DownloadFileForUpdate(RemoteRelativeModuleRoot + CurrentModule.ModuleDescriptorRelativePath);
string CurrentModuleDescriptor = Path.Combine(LocalModuleRoot, CurrentModule.ModuleDescriptorRelativePath);
if(File.Exists(ModuleDescriptor))
{
IgorModuleDescriptor CurrentModuleDescriptorInst = null;
IgorModuleDescriptor NewModuleDescriptorInst = IgorModuleDescriptor.Load(ModuleDescriptor);
if(File.Exists(CurrentModuleDescriptor))
{
CurrentModuleDescriptorInst = IgorModuleDescriptor.Load(CurrentModuleDescriptor);
}
if(NewModuleDescriptorInst != null)
{
if(UpdatedModules.Contains(NewModuleDescriptorInst.ModuleName))
{
return false;
}
UpdatedModules.Add(NewModuleDescriptorInst.ModuleName);
if(NewModuleDescriptorInst.ModuleDependencies.Count > 0)
{
foreach(string CurrentDependency in NewModuleDescriptorInst.ModuleDependencies)
{
bUpdated = UpdateModule(CurrentDependency, ForceUpdate) || bUpdated;
}
}
int NewVersion = NewModuleDescriptorInst.ModuleVersion;
if(CurrentModuleDescriptorInst == null || NewVersion > CurrentModuleDescriptorInst.ModuleVersion || bAlwaysUpdate || ForceUpdate)
{
bUpdated = true;
UpdatedContent.Add(ModuleName);
List<string> FilesToDelete = new List<string>();
if(CurrentModuleDescriptorInst != null)
{
IgorUpdater.HelperDelegates.DeleteFile(CurrentModuleDescriptor);
FilesToDelete.AddRange(CurrentModuleDescriptorInst.ModuleFiles);
}
if(!Directory.Exists(Path.GetDirectoryName(CurrentModuleDescriptor)))
{
Directory.CreateDirectory(Path.GetDirectoryName(CurrentModuleDescriptor));
}
IgorUpdater.HelperDelegates.CopyFile(ModuleDescriptor, CurrentModuleDescriptor);
foreach(string ModuleFile in NewModuleDescriptorInst.ModuleFiles)
{
FilesToDelete.Remove(ModuleFile);
bool bIsExternal = false;
string LocalFile = IgorUtils.GetLocalFileFromModuleFilename(ModuleFile);
string FullLocalPath = Path.Combine(LocalModuleRoot, Path.Combine(Path.GetDirectoryName(CurrentModule.ModuleDescriptorRelativePath), LocalFile));
string RemotePath = IgorUtils.GetRemoteFileFromModuleFilename(RemoteRelativeModuleRoot + Path.GetDirectoryName(CurrentModule.ModuleDescriptorRelativePath) + "/", ModuleFile, ref bIsExternal);
if(LocalFile.StartsWith("."))
{
string Base = Path.Combine(LocalModuleRoot.Replace('/', Path.DirectorySeparatorChar), Path.GetDirectoryName(CurrentModule.ModuleDescriptorRelativePath.Replace('/', Path.DirectorySeparatorChar)));
string NewLocalFile = LocalFile.Replace('/', Path.DirectorySeparatorChar);
int FirstIndex = NewLocalFile.IndexOf(".." + Path.DirectorySeparatorChar);
while(FirstIndex != -1)
{
int LastIndex = Base.LastIndexOf(Path.DirectorySeparatorChar);
if(LastIndex != -1)
{
Base = Base.Substring(0, LastIndex);
}
NewLocalFile = NewLocalFile.Substring(3);
FirstIndex = NewLocalFile.IndexOf(".." + Path.DirectorySeparatorChar);
}
FullLocalPath = Path.Combine(Base, NewLocalFile);
RemotePath = IgorUtils.GetRemoteFileFromModuleFilename(RemoteRelativeModuleRoot + Path.GetDirectoryName(CurrentModule.ModuleDescriptorRelativePath) + "/", ModuleFile, ref bIsExternal);
}
string TempDownloadPath = "";
if(bIsExternal)
{
if(!bLocalDownload || bDownloadRemoteWhenLocal || !File.Exists(FullLocalPath))
{
if(LocalFile.Contains("../"))
{
TempDownloadPath = IgorUtils.DownloadFileForUpdate(FullLocalPath, RemotePath);
}
else
{
TempDownloadPath = IgorUtils.DownloadFileForUpdate(Path.Combine(Path.GetDirectoryName(CurrentModule.ModuleDescriptorRelativePath), LocalFile), RemotePath);
}
}
}
else
{
TempDownloadPath = IgorUtils.DownloadFileForUpdate(RemotePath);
}
if(TempDownloadPath != "")
{
if(File.Exists(FullLocalPath))
{
IgorUpdater.HelperDelegates.DeleteFile(FullLocalPath);
}
if(!Directory.Exists(Path.GetDirectoryName(FullLocalPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(FullLocalPath));
}
if(File.Exists(TempDownloadPath))
{
IgorUpdater.HelperDelegates.CopyFile(TempDownloadPath, FullLocalPath);
}
}
}
foreach(string FilenameToDelete in FilesToDelete)
{
string LocalFile = IgorUtils.GetLocalFileFromModuleFilename(FilenameToDelete);
string FullLocalPath = Path.Combine(LocalModuleRoot, Path.Combine(Path.GetDirectoryName(CurrentModule.ModuleDescriptorRelativePath), LocalFile));
if(File.Exists(FullLocalPath))
{
IgorUpdater.HelperDelegates.DeleteFile(FullLocalPath);
}
}
}
}
}
return bUpdated;
}
}
}
return false;
}
public static bool UpdateModules()
{
bool bThrewException = false;
try
{
FindCore();
if(Core != null)
{
bool bUpdated = false;
UpdatedModules.Clear();
foreach(string CurrentModule in Core.GetEnabledModuleNames())
{
bUpdated = UpdateModule(CurrentModule, false) || bUpdated;
}
if(bUpdated)
{
return true;
}
}
}
catch(TimeoutException)
{
// We should eventually handle this case by triggering a re-attempt
}
catch(Exception e)
{
Debug.LogError("Igor Error: Caught exception while updating modules. Exception is " + (e == null ? "NULL exception!" : e.ToString()));
bThrewException = true;
CleanupTemp();
}
if(!HelperDelegates.IgorJobConfig_GetWasMenuTriggered())
{
if(bThrewException)
{
Debug.LogError("Igor Error: Exiting EditorApplication because an exception was thrown.");
if(HelperDelegates.bIsValid)
{
EditorApplication.Exit(-1);
}
}
}
return false;
}
public static void CheckIfResuming()
{
if(!EditorApplication.isCompiling)
{
bool bThrewException = false;
EditorApplication.update -= CheckIfResuming;
try
{
FindCore();
if(HelperDelegates.IgorJobConfig_IsBoolParamSet("restartingfromupdate") || HelperDelegates.IgorJobConfig_IsBoolParamSet("updatebeforebuild") || Core == null)
{
HelperDelegates.IgorJobConfig_SetBoolParam("restartingfromupdate", false);
if(!CheckForUpdates())
{
if(HelperDelegates.IgorJobConfig_IsBoolParamSet("updatebeforebuild"))
{
HelperDelegates.IgorJobConfig_SetBoolParam("updatebeforebuild", false);
if(Core != null)
{
Core.RunJobInst();
}
else
{
Debug.LogError("Igor Error: Something went really wrong. We don't have Igor's core, but we've already finished updating everything. Report this with your logs please!");
}
}
}
}
}
catch(Exception e)
{
Debug.LogError("Igor Error: Caught exception while resuming from updates. Exception is " + (e == null ? "NULL exception!" : e.ToString()));
bThrewException = true;
}
if(!HelperDelegates.IgorJobConfig_GetWasMenuTriggered())
{
if(bThrewException)
{
Debug.LogError("Igor Error: Exiting EditorApplication because an exception was thrown.");
if(HelperDelegates.bIsValid)
{
EditorApplication.Exit(-1);
}
}
}
}
}
public static void GenerateModuleList()
{
IgorModuleList NewInst = new IgorModuleList();
IgorModuleList.ModuleItem NewItem = new IgorModuleList.ModuleItem();
NewItem.ModuleName = "Core.Core";
NewItem.ModuleDescriptorRelativePath = "Core/Core/Core.mod";
NewInst.Modules.Add(NewItem);
NewInst.Save(IgorModulesListFilename);
}
public static bool CheckForOneTimeForcedUpgrade()
{
if(File.Exists(Path.Combine(OldBaseIgorDirectory, IgorUpdaterBaseFilename)))
{
return true;
}
return false;
}
public static void MoveConfigsFromOldLocation()
{
string OriginalConfigFile = Path.Combine(OldBaseIgorDirectory, "IgorConfig.xml");
if(File.Exists(OriginalConfigFile))
{
string DestinationConfigFile = Path.Combine(BaseIgorDirectory, "IgorConfig.xml");
if(!Directory.Exists(Path.GetDirectoryName(DestinationConfigFile)))
{
Directory.CreateDirectory(Path.GetDirectoryName(DestinationConfigFile));
}
IgorUpdater.HelperDelegates.CopyFile(OriginalConfigFile, DestinationConfigFile);
}
}
public static void RemoveOldDirectory()
{
IgorUpdater.HelperDelegates.DeleteDirectory(OldBaseIgorDirectory);
IgorUpdater.HelperDelegates.DeleteFile(OldBaseIgorDirectory + ".meta");
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Derivatives.Algo
File: BasketBlackScholes.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Derivatives
{
using System;
using System.Linq;
using Ecng.Collections;
using StockSharp.Algo.Positions;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Localization;
/// <summary>
/// Portfolio model for calculating the values of Greeks by the Black-Scholes formula.
/// </summary>
public class BasketBlackScholes : BlackScholes
{
/// <summary>
/// The model for calculating Greeks values by the Black-Scholes formula based on the position.
/// </summary>
public class InnerModel
{
/// <summary>
/// Initializes a new instance of the <see cref="InnerModel"/>.
/// </summary>
/// <param name="model">The model for calculating Greeks values by the Black-Scholes formula.</param>
/// <param name="positionManager">The position manager.</param>
public InnerModel(BlackScholes model, IPositionManager positionManager)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
if (positionManager == null)
throw new ArgumentNullException(nameof(positionManager));
Model = model;
PositionManager = positionManager;
}
/// <summary>
/// The model for calculating Greeks values by the Black-Scholes formula.
/// </summary>
public BlackScholes Model { get; }
/// <summary>
/// The position manager.
/// </summary>
public IPositionManager PositionManager { get; }
}
/// <summary>
/// The interface describing the internal models collection <see cref="InnerModels"/>.
/// </summary>
public interface IInnerModelList : ISynchronizedCollection<InnerModel>
{
/// <summary>
/// To get the model for calculating Greeks values by the Black-Scholes formula for a particular option.
/// </summary>
/// <param name="option">Options contract.</param>
/// <returns>The model. If the option is not registered, then <see langword="null" /> will be returned.</returns>
InnerModel this[Security option] { get; }
}
private sealed class InnerModelList : CachedSynchronizedList<InnerModel>, IInnerModelList
{
private readonly BasketBlackScholes _parent;
public InnerModelList(BasketBlackScholes parent)
{
if (parent == null)
throw new ArgumentNullException(nameof(parent));
_parent = parent;
}
InnerModel IInnerModelList.this[Security option]
{
get
{
if (option == null)
throw new ArgumentNullException(nameof(option));
return this.SyncGet(c => c.FirstOrDefault(i => i.Model.Option == option));
}
}
protected override bool OnAdding(InnerModel item)
{
item.Model.RoundDecimals = _parent.RoundDecimals;
return base.OnAdding(item);
}
protected override bool OnInserting(int index, InnerModel item)
{
item.Model.RoundDecimals = _parent.RoundDecimals;
return base.OnInserting(index, item);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="BasketBlackScholes"/>.
/// </summary>
/// <param name="securityProvider">The provider of information about instruments.</param>
/// <param name="dataProvider">The market data provider.</param>
public BasketBlackScholes(ISecurityProvider securityProvider, IMarketDataProvider dataProvider)
: base(securityProvider, dataProvider)
{
_innerModels = new InnerModelList(this);
}
/// <summary>
/// Initializes a new instance of the <see cref="BasketBlackScholes"/>.
/// </summary>
/// <param name="underlyingAsset">Underlying asset.</param>
/// <param name="dataProvider">The market data provider.</param>
public BasketBlackScholes(Security underlyingAsset, IMarketDataProvider dataProvider)
: base(underlyingAsset, dataProvider)
{
_innerModels = new InnerModelList(this);
_underlyingAsset = underlyingAsset;
}
private readonly InnerModelList _innerModels;
/// <summary>
/// Information about options.
/// </summary>
public IInnerModelList InnerModels => _innerModels;
/// <summary>
/// The position by the underlying asset.
/// </summary>
public IPositionManager UnderlyingAssetPosition { get; set; }
/// <summary>
/// Options contract.
/// </summary>
public override Security Option
{
get { throw new NotSupportedException(); }
}
private Security _underlyingAsset;
/// <summary>
/// Underlying asset.
/// </summary>
public override Security UnderlyingAsset
{
get
{
if (_underlyingAsset == null)
{
var info = _innerModels.SyncGet(c => c.FirstOrDefault());
if (info == null)
throw new InvalidOperationException(LocalizedStrings.Str700);
_underlyingAsset = info.Model.Option.GetAsset(SecurityProvider);
}
return _underlyingAsset;
}
}
/// <summary>
/// The number of decimal places at calculated values. The default is -1, which means no values rounding.
/// </summary>
public override int RoundDecimals
{
set
{
base.RoundDecimals = value;
lock (_innerModels.SyncRoot)
{
_innerModels.ForEach(m => m.Model.RoundDecimals = value);
}
}
}
private decimal GetAssetPosition()
{
return UnderlyingAssetPosition?.Position ?? 0;
}
/// <summary>
/// To calculate the option delta.
/// </summary>
/// <param name="currentTime">The current time.</param>
/// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param>
/// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param>
/// <returns>The option delta. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns>
public override decimal? Delta(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null)
{
return ProcessOptions(bs => bs.Delta(currentTime, deviation, assetPrice)) + GetAssetPosition();
}
/// <summary>
/// To calculate the option gamma.
/// </summary>
/// <param name="currentTime">The current time.</param>
/// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param>
/// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param>
/// <returns>The option gamma. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns>
public override decimal? Gamma(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null)
{
return ProcessOptions(bs => bs.Gamma(currentTime, deviation, assetPrice));
}
/// <summary>
/// To calculate the option vega.
/// </summary>
/// <param name="currentTime">The current time.</param>
/// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param>
/// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param>
/// <returns>The option vega. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns>
public override decimal? Vega(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null)
{
return ProcessOptions(bs => bs.Vega(currentTime, deviation, assetPrice));
}
/// <summary>
/// To calculate the option theta.
/// </summary>
/// <param name="currentTime">The current time.</param>
/// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param>
/// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param>
/// <returns>The option theta. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns>
public override decimal? Theta(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null)
{
return ProcessOptions(bs => bs.Theta(currentTime, deviation, assetPrice));
}
/// <summary>
/// To calculate the option rho.
/// </summary>
/// <param name="currentTime">The current time.</param>
/// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param>
/// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param>
/// <returns>The option rho. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns>
public override decimal? Rho(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null)
{
return ProcessOptions(bs => bs.Rho(currentTime, deviation, assetPrice));
}
/// <summary>
/// To calculate the option premium.
/// </summary>
/// <param name="currentTime">The current time.</param>
/// <param name="deviation">The standard deviation. If it is not specified, then <see cref="BlackScholes.DefaultDeviation"/> is used.</param>
/// <param name="assetPrice">The price of the underlying asset. If the price is not specified, then the last trade price getting from <see cref="BlackScholes.UnderlyingAsset"/>.</param>
/// <returns>The option premium. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns>
public override decimal? Premium(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null)
{
return ProcessOptions(bs => bs.Premium(currentTime, deviation, assetPrice));
}
/// <summary>
/// To calculate the implied volatility.
/// </summary>
/// <param name="currentTime">The current time.</param>
/// <param name="premium">The option premium.</param>
/// <returns>The implied volatility. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns>
public override decimal? ImpliedVolatility(DateTimeOffset currentTime, decimal premium)
{
return ProcessOptions(bs => bs.ImpliedVolatility(currentTime, premium), false);
}
/// <summary>
/// To create the order book of volatility.
/// </summary>
/// <param name="currentTime">The current time.</param>
/// <returns>The order book volatility.</returns>
public override MarketDepth ImpliedVolatility(DateTimeOffset currentTime)
{
throw new NotSupportedException();
//return UnderlyingAsset.GetMarketDepth().ImpliedVolatility(this);
}
private decimal? ProcessOptions(Func<BlackScholes, decimal?> func, bool usePos = true)
{
return _innerModels.Cache.Sum(m =>
{
var iv = (decimal?)DataProvider.GetSecurityValue(m.Model.Option, Level1Fields.ImpliedVolatility);
return iv == null ? null : func(m.Model) * (usePos ? m.PositionManager.Position : 1);
});
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type GroupEventsCollectionRequest.
/// </summary>
public partial class GroupEventsCollectionRequest : BaseRequest, IGroupEventsCollectionRequest
{
/// <summary>
/// Constructs a new GroupEventsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public GroupEventsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Event to the collection via POST.
/// </summary>
/// <param name="eventsEvent">The Event to add.</param>
/// <returns>The created Event.</returns>
public System.Threading.Tasks.Task<Event> AddAsync(Event eventsEvent)
{
return this.AddAsync(eventsEvent, CancellationToken.None);
}
/// <summary>
/// Adds the specified Event to the collection via POST.
/// </summary>
/// <param name="eventsEvent">The Event to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Event.</returns>
public System.Threading.Tasks.Task<Event> AddAsync(Event eventsEvent, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<Event>(eventsEvent, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IGroupEventsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IGroupEventsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<GroupEventsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IGroupEventsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IGroupEventsCollectionRequest Expand(Expression<Func<Event, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IGroupEventsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IGroupEventsCollectionRequest Select(Expression<Func<Event, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IGroupEventsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IGroupEventsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IGroupEventsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IGroupEventsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System;
using System.Drawing;
using FastQuant;
using FastQuant.Indicators;
using System.Linq;
namespace Samples.SlowTurtleTrendFollowing
{
public class Turtles : InstrumentStrategy
{
private int positionInBlock;
private bool buyOnNewBlock;
private bool sellOnNewBlock;
private SMA fastSMA;
private SMA slowSMA;
private Group barsGroup;
private Group fillGroup;
private Group equityGroup;
private Group fastSmaGroup;
private Group slowSmaGroup;
[Parameter]
public double AllocationPerInstrument = 100000;
[Parameter]
double Qty = 100;
[Parameter]
int BarBlockSize = 6;
[Parameter]
int FastSMALength = 22;
[Parameter]
int SlowSMALength = 55;
public Turtles(Framework framework, string name)
: base(framework, name)
{
}
protected override void OnStrategyStart()
{
Portfolio.Account.Deposit(AllocationPerInstrument, CurrencyId.USD, "Initial allocation");
// Set up indicators.
fastSMA = new SMA(Bars, FastSMALength);
slowSMA = new SMA(Bars, SlowSMALength);
AddGroups();
}
protected override void OnBarOpen(Instrument instrument, Bar bar)
{
double orderQty = Qty;
// Set order qty if position already exist.
if (HasPosition(Instrument))
orderQty = Math.Abs(Position.Amount) + Qty;
// Send trading orders if needed.
if (positionInBlock == 0)
{
if (buyOnNewBlock)
{
Order order = BuyOrder(Instrument, orderQty, "Reverse to Long");
Send(order);
buyOnNewBlock = false;
}
if (sellOnNewBlock)
{
Order order = SellOrder(Instrument, orderQty, "Reverse to Short");
Send(order);
sellOnNewBlock = false;
}
}
}
protected override void OnBar(Instrument instrument, Bar bar)
{
// Add bar to bar series.
Bars.Add(bar);
Log(bar, barsGroup);
if (fastSMA.Count > 0)
Log(fastSMA.Last, fastSmaGroup);
if (slowSMA.Count > 0)
Log(slowSMA.Last, slowSmaGroup);
// Calculate performance.
Portfolio.Performance.Update();
Log(Portfolio.Value, equityGroup);
// Check strategy logic.
if (fastSMA.Count > 0 && slowSMA.Count > 0)
{
Cross cross = fastSMA.Crosses(slowSMA, bar.DateTime);
if (cross == Cross.Above)
buyOnNewBlock = true;
if (cross == Cross.Below)
sellOnNewBlock = true;
}
positionInBlock = (positionInBlock++) % BarBlockSize;
}
protected override void OnFill(Fill fill)
{
Log(fill, fillGroup);
}
private void AddGroups()
{
// Create bars group.
barsGroup = new Group("Bars");
barsGroup.Add("Pad", DataObjectType.String, 0);
barsGroup.Add("SelectorKey", Instrument.Symbol);
// Create fills group.
fillGroup = new Group("Fills");
fillGroup.Add("Pad", 0);
fillGroup.Add("SelectorKey", Instrument.Symbol);
// Create equity group.
equityGroup = new Group("Equity");
equityGroup.Add("Pad", 1);
equityGroup.Add("SelectorKey", Instrument.Symbol);
// Create fast sma values group.
fastSmaGroup = new Group("FastSMA");
fastSmaGroup.Add("Pad", 0);
fastSmaGroup.Add("SelectorKey", Instrument.Symbol);
fastSmaGroup.Add("Color", Color.Green);
// Create slow sma values group.
slowSmaGroup = new Group("SlowSMA");
slowSmaGroup.Add("Pad", 0);
slowSmaGroup.Add("SelectorKey", Instrument.Symbol);
slowSmaGroup.Add("Color", Color.Red);
// Add groups to manager.
GroupManager.Add(barsGroup);
GroupManager.Add(fillGroup);
GroupManager.Add(equityGroup);
GroupManager.Add(fastSmaGroup);
GroupManager.Add(slowSmaGroup);
}
}
public class Backtest : Scenario
{
private long barSize = 300;
public Backtest(Framework framework)
: base(framework)
{
}
public override void Run()
{
Instrument instrument1 = InstrumentManager.Instruments["AAPL"];
Instrument instrument2 = InstrumentManager.Instruments["MSFT"];
strategy = new Turtles(framework, "Turtles");
strategy.AddInstrument(instrument1);
strategy.AddInstrument(instrument2);
DataSimulator.DateTime1 = new DateTime(2013, 01, 01);
DataSimulator.DateTime2 = new DateTime(2013, 12, 31);
BarFactory.Add(instrument1, BarType.Time, barSize);
BarFactory.Add(instrument2, BarType.Time, barSize);
StartStrategy();
}
}
public class Realtime : Scenario
{
private long barSize = 300;
public Realtime(Framework framework)
: base(framework)
{
}
public override void Run()
{
Instrument instrument1 = InstrumentManager.Instruments["AAPL"];
Instrument instrument2 = InstrumentManager.Instruments["MSFT"];
strategy = new Turtles(framework, "Turtles");
strategy.AddInstrument(instrument1);
strategy.AddInstrument(instrument2);
strategy.DataProvider = ProviderManager.GetDataProvider("QuantRouter");
strategy.ExecutionProvider = ProviderManager.GetExecutionProvider("QuantRouter");
DataSimulator.DateTime1 = new DateTime(2013, 01, 01);
DataSimulator.DateTime2 = new DateTime(2013, 12, 31);
BarFactory.Add(instrument1, BarType.Time, barSize);
BarFactory.Add(instrument2, BarType.Time, barSize);
StartStrategy();
}
}
class Program
{
static void Main(string[] args)
{
var scenario = args.Contains("--realtime") ? (Scenario)new Realtime(Framework.Current) : (Scenario)new Backtest(Framework.Current);
scenario.Run();
}
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Semmle.Extraction.CSharp.Populators;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
namespace Semmle.Extraction.CSharp.Entities
{
internal abstract class Method : CachedSymbol<IMethodSymbol>, IExpressionParentEntity, IStatementParentEntity
{
protected Method(Context cx, IMethodSymbol init)
: base(cx, init) { }
protected void PopulateParameters()
{
var originalMethod = OriginalDefinition;
IEnumerable<IParameterSymbol> parameters = Symbol.Parameters;
IEnumerable<IParameterSymbol> originalParameters = originalMethod.Symbol.Parameters;
foreach (var p in parameters.Zip(originalParameters, (paramSymbol, originalParam) => new { paramSymbol, originalParam }))
{
var original = SymbolEqualityComparer.Default.Equals(p.paramSymbol, p.originalParam)
? null
: Parameter.Create(Context, p.originalParam, originalMethod);
Parameter.Create(Context, p.paramSymbol, this, original);
}
if (Symbol.IsVararg)
{
// Mono decided that "__arglist" should be an explicit parameter,
// so now we need to populate it.
VarargsParam.Create(Context, this);
}
}
/// <summary>
/// Extracts constructor initializers.
/// </summary>
protected virtual void ExtractInitializers(TextWriter trapFile)
{
// Normal methods don't have initializers,
// so there's nothing to extract.
}
private void PopulateMethodBody(TextWriter trapFile)
{
if (!IsSourceDeclaration)
return;
var block = Block;
var expr = ExpressionBody;
if (block is not null || expr is not null)
{
Context.PopulateLater(
() =>
{
ExtractInitializers(trapFile);
if (block is not null)
Statements.Block.Create(Context, block, this, 0);
else
Expression.Create(Context, expr!, this, 0);
NumberOfLines(trapFile, BodyDeclaringSymbol, this);
});
}
}
public static void NumberOfLines(TextWriter trapFile, ISymbol symbol, IEntity callable)
{
foreach (var decl in symbol.DeclaringSyntaxReferences)
{
var node = (CSharpSyntaxNode)decl.GetSyntax();
var lineCounts = node.Accept(new AstLineCounter());
if (lineCounts is not null)
{
trapFile.numlines(callable, lineCounts);
}
}
}
public void Overrides(TextWriter trapFile)
{
foreach (var explicitInterface in Symbol.ExplicitInterfaceImplementations
.Where(sym => sym.MethodKind == MethodKind.Ordinary)
.Select(impl => Type.Create(Context, impl.ContainingType)))
{
trapFile.explicitly_implements(this, explicitInterface.TypeRef);
if (IsSourceDeclaration)
{
foreach (var syntax in Symbol.DeclaringSyntaxReferences.Select(d => d.GetSyntax()).OfType<MethodDeclarationSyntax>())
TypeMention.Create(Context, syntax.ExplicitInterfaceSpecifier!.Name, this, explicitInterface);
}
}
if (Symbol.OverriddenMethod is not null)
{
trapFile.overrides(this, Method.Create(Context, Symbol.OverriddenMethod));
}
}
/// <summary>
/// Factored out to share logic between `Method` and `UserOperator`.
/// </summary>
private static void BuildMethodId(Method m, EscapingTextWriter trapFile)
{
if (!SymbolEqualityComparer.Default.Equals(m.Symbol, m.Symbol.OriginalDefinition))
{
if (!SymbolEqualityComparer.Default.Equals(m.Symbol, m.ConstructedFromSymbol))
{
trapFile.WriteSubId(Create(m.Context, m.ConstructedFromSymbol));
trapFile.Write('<');
// Encode the nullability of the type arguments in the label.
// Type arguments with different nullability can result in
// a constructed method with different nullability of its parameters and return type,
// so we need to create a distinct database entity for it.
trapFile.BuildList(",", m.Symbol.GetAnnotatedTypeArguments(), ta => { ta.Symbol.BuildOrWriteId(m.Context, trapFile, m.Symbol); trapFile.Write((int)ta.Nullability); });
trapFile.Write('>');
}
else
{
trapFile.WriteSubId(m.ContainingType!);
trapFile.Write(".");
trapFile.WriteSubId(m.OriginalDefinition);
}
WritePostfix(m, trapFile);
return;
}
m.Symbol.ReturnType.BuildOrWriteId(m.Context, trapFile, m.Symbol);
trapFile.Write(" ");
trapFile.WriteSubId(m.ContainingType!);
AddExplicitInterfaceQualifierToId(m.Context, trapFile, m.Symbol.ExplicitInterfaceImplementations);
trapFile.Write(".");
trapFile.Write(m.Symbol.Name);
if (m.Symbol.IsGenericMethod)
{
trapFile.Write('`');
trapFile.Write(m.Symbol.TypeParameters.Length);
}
AddParametersToId(m.Context, trapFile, m.Symbol);
WritePostfix(m, trapFile);
}
private static void WritePostfix(Method m, EscapingTextWriter trapFile)
{
switch (m.Symbol.MethodKind)
{
case MethodKind.PropertyGet:
trapFile.Write(";getter");
break;
case MethodKind.PropertySet:
trapFile.Write(";setter");
break;
case MethodKind.EventAdd:
trapFile.Write(";adder");
break;
case MethodKind.EventRaise:
trapFile.Write(";raiser");
break;
case MethodKind.EventRemove:
trapFile.Write(";remover");
break;
default:
trapFile.Write(";method");
break;
}
}
public override void WriteId(EscapingTextWriter trapFile)
{
BuildMethodId(this, trapFile);
}
protected static void AddParametersToId(Context cx, EscapingTextWriter trapFile, IMethodSymbol method)
{
trapFile.Write('(');
var index = 0;
var @params = method.Parameters;
foreach (var param in @params)
{
trapFile.WriteSeparator(",", ref index);
param.Type.BuildOrWriteId(cx, trapFile, method);
trapFile.Write(" ");
trapFile.Write(param.Name);
switch (param.RefKind)
{
case RefKind.Out:
trapFile.Write(" out");
break;
case RefKind.Ref:
trapFile.Write(" ref");
break;
}
}
if (method.IsVararg)
{
trapFile.WriteSeparator(",", ref index);
trapFile.Write("__arglist");
}
trapFile.Write(')');
}
public static void AddExplicitInterfaceQualifierToId(Context cx, EscapingTextWriter trapFile, IEnumerable<ISymbol> explicitInterfaceImplementations)
{
if (explicitInterfaceImplementations.Any())
trapFile.AppendList(",", explicitInterfaceImplementations.Select(impl => cx.CreateEntity(impl.ContainingType)));
}
public virtual string Name => Symbol.Name;
/// <summary>
/// Creates a method of the appropriate subtype.
/// </summary>
/// <param name="cx"></param>
/// <param name="methodDecl"></param>
/// <returns></returns>
[return: NotNullIfNotNull("methodDecl")]
public static Method? Create(Context cx, IMethodSymbol? methodDecl)
{
if (methodDecl is null)
return null;
var methodKind = methodDecl.MethodKind;
if (methodKind == MethodKind.ExplicitInterfaceImplementation)
{
// Retrieve the original method kind
methodKind = methodDecl.ExplicitInterfaceImplementations.Select(m => m.MethodKind).FirstOrDefault();
}
switch (methodKind)
{
case MethodKind.StaticConstructor:
case MethodKind.Constructor:
return Constructor.Create(cx, methodDecl);
case MethodKind.ReducedExtension:
if (SymbolEqualityComparer.Default.Equals(methodDecl, methodDecl.ConstructedFrom))
{
return OrdinaryMethod.Create(cx, methodDecl.ReducedFrom!);
}
return OrdinaryMethod.Create(cx, methodDecl.ReducedFrom!.Construct(methodDecl.TypeArguments, methodDecl.TypeArgumentNullableAnnotations));
case MethodKind.Ordinary:
case MethodKind.DelegateInvoke:
return OrdinaryMethod.Create(cx, methodDecl);
case MethodKind.Destructor:
return Destructor.Create(cx, methodDecl);
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
return Accessor.GetPropertySymbol(methodDecl) is IPropertySymbol prop ? Accessor.Create(cx, methodDecl, prop) : OrdinaryMethod.Create(cx, methodDecl);
case MethodKind.EventAdd:
case MethodKind.EventRemove:
return EventAccessor.GetEventSymbol(methodDecl) is IEventSymbol @event ? EventAccessor.Create(cx, methodDecl, @event) : OrdinaryMethod.Create(cx, methodDecl);
case MethodKind.UserDefinedOperator:
case MethodKind.BuiltinOperator:
return UserOperator.Create(cx, methodDecl);
case MethodKind.Conversion:
return Conversion.Create(cx, methodDecl);
case MethodKind.AnonymousFunction:
throw new InternalError(methodDecl, "Attempt to create a lambda");
case MethodKind.LocalFunction:
return LocalFunction.Create(cx, methodDecl);
default:
throw new InternalError(methodDecl, $"Unhandled method '{methodDecl}' of kind '{methodDecl.MethodKind}'");
}
}
public Method OriginalDefinition => Create(Context, Symbol.OriginalDefinition);
public override Location? FullLocation => ReportingLocation;
public override bool IsSourceDeclaration => Symbol.IsSourceDeclaration();
/// <summary>
/// Whether this method has type parameters.
/// </summary>
public bool IsGeneric => Symbol.IsGenericMethod;
/// <summary>
/// Whether this method has unbound type parameters.
/// </summary>
public bool IsUnboundGeneric => IsGeneric && SymbolEqualityComparer.Default.Equals(Symbol.ConstructedFrom, Symbol);
public bool IsBoundGeneric => IsGeneric && !IsUnboundGeneric;
protected IMethodSymbol ConstructedFromSymbol => Symbol.ConstructedFrom;
bool IExpressionParentEntity.IsTopLevelParent => true;
bool IStatementParentEntity.IsTopLevelParent => true;
protected void PopulateGenerics(TextWriter trapFile)
{
var isFullyConstructed = IsBoundGeneric;
if (IsGeneric)
{
var child = 0;
if (isFullyConstructed)
{
trapFile.constructed_generic(this, Method.Create(Context, ConstructedFromSymbol));
foreach (var tp in Symbol.GetAnnotatedTypeArguments())
{
trapFile.type_arguments(Type.Create(Context, tp.Symbol), child, this);
child++;
}
var nullability = new Nullability(Symbol);
if (!nullability.IsOblivious)
trapFile.type_nullability(this, NullabilityEntity.Create(Context, nullability));
}
else
{
foreach (var typeParam in Symbol.TypeParameters.Select(tp => TypeParameter.Create(Context, tp)))
{
trapFile.type_parameters(typeParam, child, this);
child++;
}
}
}
}
public static void ExtractRefReturn(TextWriter trapFile, IMethodSymbol method, IEntity element)
{
if (method.ReturnsByRef)
trapFile.type_annotation(element, Kinds.TypeAnnotation.Ref);
if (method.ReturnsByRefReadonly)
trapFile.type_annotation(element, Kinds.TypeAnnotation.ReadonlyRef);
}
protected void PopulateMethod(TextWriter trapFile)
{
// Common population code for all callables
BindComments();
PopulateAttributes();
PopulateParameters();
PopulateMethodBody(trapFile);
PopulateGenerics(trapFile);
PopulateMetadataHandle(trapFile);
PopulateNullability(trapFile, Symbol.GetAnnotatedReturnType());
}
public override TrapStackBehaviour TrapStackBehaviour => TrapStackBehaviour.PushesLabel;
}
}
| |
/*
* 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.Data;
using System.Reflection;
using log4net;
using Mono.Data.SqliteClient;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// An Inventory Interface to the SQLite database
/// </summary>
public class SQLiteInventoryStore : SQLiteUtil, IInventoryDataPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const string invItemsSelect = "select * from inventoryitems";
private const string invFoldersSelect = "select * from inventoryfolders";
private SqliteConnection conn;
private DataSet ds;
private SqliteDataAdapter invItemsDa;
private SqliteDataAdapter invFoldersDa;
public void Initialise()
{
m_log.Info("[SQLiteInventoryData]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// <list type="bullet">
/// <item>Initialises Inventory interface</item>
/// <item>Loads and initialises a new SQLite connection and maintains it.</item>
/// <item>use default URI if connect string string is empty.</item>
/// </list>
/// </summary>
/// <param name="dbconnect">connect string</param>
public void Initialise(string dbconnect)
{
if (dbconnect == string.Empty)
{
dbconnect = "URI=file:inventoryStore.db,version=3";
}
m_log.Info("[INVENTORY DB]: Sqlite - connecting: " + dbconnect);
conn = new SqliteConnection(dbconnect);
conn.Open();
Assembly assem = GetType().Assembly;
Migration m = new Migration(conn, assem, "InventoryStore");
m.Update();
SqliteCommand itemsSelectCmd = new SqliteCommand(invItemsSelect, conn);
invItemsDa = new SqliteDataAdapter(itemsSelectCmd);
// SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa);
SqliteCommand foldersSelectCmd = new SqliteCommand(invFoldersSelect, conn);
invFoldersDa = new SqliteDataAdapter(foldersSelectCmd);
ds = new DataSet();
ds.Tables.Add(createInventoryFoldersTable());
invFoldersDa.Fill(ds.Tables["inventoryfolders"]);
setupFoldersCommands(invFoldersDa, conn);
m_log.Info("[INVENTORY DB]: Populated Inventory Folders Definitions");
ds.Tables.Add(createInventoryItemsTable());
invItemsDa.Fill(ds.Tables["inventoryitems"]);
setupItemsCommands(invItemsDa, conn);
m_log.Info("[INVENTORY DB]: Populated Inventory Items Definitions");
ds.AcceptChanges();
}
/// <summary>
/// Closes the inventory interface
/// </summary>
public void Dispose()
{
if (conn != null)
{
conn.Close();
conn = null;
}
if (invItemsDa != null)
{
invItemsDa.Dispose();
invItemsDa = null;
}
if (invFoldersDa != null)
{
invFoldersDa.Dispose();
invFoldersDa = null;
}
if (ds != null)
{
ds.Dispose();
ds = null;
}
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public InventoryItemBase buildItem(DataRow row)
{
InventoryItemBase item = new InventoryItemBase();
item.ID = new UUID((string) row["UUID"]);
item.AssetID = new UUID((string) row["assetID"]);
item.AssetType = Convert.ToInt32(row["assetType"]);
item.InvType = Convert.ToInt32(row["invType"]);
item.Folder = new UUID((string) row["parentFolderID"]);
item.Owner = new UUID((string) row["avatarID"]);
item.CreatorId = (string)row["creatorsID"];
item.Name = (string) row["inventoryName"];
item.Description = (string) row["inventoryDescription"];
item.NextPermissions = Convert.ToUInt32(row["inventoryNextPermissions"]);
item.CurrentPermissions = Convert.ToUInt32(row["inventoryCurrentPermissions"]);
item.BasePermissions = Convert.ToUInt32(row["inventoryBasePermissions"]);
item.EveryOnePermissions = Convert.ToUInt32(row["inventoryEveryOnePermissions"]);
item.GroupPermissions = Convert.ToUInt32(row["inventoryGroupPermissions"]);
// new fields
if (!Convert.IsDBNull(row["salePrice"]))
item.SalePrice = Convert.ToInt32(row["salePrice"]);
if (!Convert.IsDBNull(row["saleType"]))
item.SaleType = Convert.ToByte(row["saleType"]);
if (!Convert.IsDBNull(row["creationDate"]))
item.CreationDate = Convert.ToInt32(row["creationDate"]);
if (!Convert.IsDBNull(row["groupID"]))
item.GroupID = new UUID((string)row["groupID"]);
if (!Convert.IsDBNull(row["groupOwned"]))
item.GroupOwned = Convert.ToBoolean(row["groupOwned"]);
if (!Convert.IsDBNull(row["Flags"]))
item.Flags = Convert.ToUInt32(row["Flags"]);
return item;
}
/// <summary>
/// Fill a database row with item data
/// </summary>
/// <param name="row"></param>
/// <param name="item"></param>
private static void fillItemRow(DataRow row, InventoryItemBase item)
{
row["UUID"] = item.ID.ToString();
row["assetID"] = item.AssetID.ToString();
row["assetType"] = item.AssetType;
row["invType"] = item.InvType;
row["parentFolderID"] = item.Folder.ToString();
row["avatarID"] = item.Owner.ToString();
row["creatorsID"] = item.CreatorId.ToString();
row["inventoryName"] = item.Name;
row["inventoryDescription"] = item.Description;
row["inventoryNextPermissions"] = item.NextPermissions;
row["inventoryCurrentPermissions"] = item.CurrentPermissions;
row["inventoryBasePermissions"] = item.BasePermissions;
row["inventoryEveryOnePermissions"] = item.EveryOnePermissions;
row["inventoryGroupPermissions"] = item.GroupPermissions;
// new fields
row["salePrice"] = item.SalePrice;
row["saleType"] = item.SaleType;
row["creationDate"] = item.CreationDate;
row["groupID"] = item.GroupID.ToString();
row["groupOwned"] = item.GroupOwned;
row["flags"] = item.Flags;
}
/// <summary>
/// Add inventory folder
/// </summary>
/// <param name="folder">Folder base</param>
/// <param name="add">true=create folder. false=update existing folder</param>
/// <remarks>nasty</remarks>
private void addFolder(InventoryFolderBase folder, bool add)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString());
if (inventoryRow == null)
{
if (! add)
m_log.ErrorFormat("Interface Misuse: Attempting to Update non-existant inventory folder: {0}", folder.ID);
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
if (add)
m_log.ErrorFormat("Interface Misuse: Attempting to Add inventory folder that already exists: {0}", folder.ID);
fillFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// Move an inventory folder
/// </summary>
/// <param name="folder">folder base</param>
private void moveFolder(InventoryFolderBase folder)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString());
if (inventoryRow == null)
{
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
moveFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// add an item in inventory
/// </summary>
/// <param name="item">the item</param>
/// <param name="add">true=add item ; false=update existing item</param>
private void addItem(InventoryItemBase item, bool add)
{
lock (ds)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
DataRow inventoryRow = inventoryItemTable.Rows.Find(item.ID.ToString());
if (inventoryRow == null)
{
if (!add)
m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Update non-existant inventory item: {0}", item.ID);
inventoryRow = inventoryItemTable.NewRow();
fillItemRow(inventoryRow, item);
inventoryItemTable.Rows.Add(inventoryRow);
}
else
{
if (add)
m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Add inventory item that already exists: {0}", item.ID);
fillItemRow(inventoryRow, item);
}
invItemsDa.Update(ds, "inventoryitems");
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
inventoryRow = inventoryFolderTable.Rows.Find(item.Folder.ToString());
if (inventoryRow != null) //MySQL doesn't throw an exception here, so sqlite shouldn't either.
inventoryRow["version"] = (int)inventoryRow["version"] + 1;
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// TODO : DataSet commit
/// </summary>
public void Shutdown()
{
// TODO: DataSet commit
}
/// <summary>
/// The name of this DB provider
/// </summary>
/// <returns>Name of DB provider</returns>
public string Name
{
get { return "SQLite Inventory Data Interface"; }
}
/// <summary>
/// Returns the version of this DB provider
/// </summary>
/// <returns>A string containing the DB provider version</returns>
public string Version
{
get
{
Module module = GetType().Module;
// string dllName = module.Assembly.ManifestModule.Name;
Version dllVersion = module.Assembly.GetName().Version;
return
string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
dllVersion.Revision);
}
}
/// <summary>
/// Returns a list of inventory items contained within the specified folder
/// </summary>
/// <param name="folderID">The UUID of the target folder</param>
/// <returns>A List of InventoryItemBase items</returns>
public List<InventoryItemBase> getInventoryInFolder(UUID folderID)
{
lock (ds)
{
List<InventoryItemBase> retval = new List<InventoryItemBase>();
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
string selectExp = "parentFolderID = '" + folderID + "'";
DataRow[] rows = inventoryItemTable.Select(selectExp);
foreach (DataRow row in rows)
{
retval.Add(buildItem(row));
}
return retval;
}
}
/// <summary>
/// Returns a list of the root folders within a users inventory
/// </summary>
/// <param name="user">The user whos inventory is to be searched</param>
/// <returns>A list of folder objects</returns>
public List<InventoryFolderBase> getUserRootFolders(UUID user)
{
return new List<InventoryFolderBase>();
}
// see InventoryItemBase.getUserRootFolder
public InventoryFolderBase getUserRootFolder(UUID user)
{
lock (ds)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "agentID = '" + user + "' AND parentID = '" + UUID.Zero + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{
folders.Add(buildFolder(row));
}
// There should only ever be one root folder for a user. However, if there's more
// than one we'll simply use the first one rather than failing. It would be even
// nicer to print some message to this effect, but this feels like it's too low a
// to put such a message out, and it's too minor right now to spare the time to
// suitably refactor.
if (folders.Count > 0)
{
return folders[0];
}
return null;
}
}
/// <summary>
/// Append a list of all the child folders of a parent folder
/// </summary>
/// <param name="folders">list where folders will be appended</param>
/// <param name="parentID">ID of parent</param>
protected void getInventoryFolders(ref List<InventoryFolderBase> folders, UUID parentID)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "parentID = '" + parentID + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{
folders.Add(buildFolder(row));
}
}
}
/// <summary>
/// Returns a list of inventory folders contained in the folder 'parentID'
/// </summary>
/// <param name="parentID">The folder to get subfolders for</param>
/// <returns>A list of inventory folders</returns>
public List<InventoryFolderBase> getInventoryFolders(UUID parentID)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
getInventoryFolders(ref folders, parentID);
return folders;
}
/// <summary>
/// See IInventoryDataPlugin
/// </summary>
/// <param name="parentID"></param>
/// <returns></returns>
public List<InventoryFolderBase> getFolderHierarchy(UUID parentID)
{
/* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one
* - We will only need to hit the database twice instead of n times.
* - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned
* by the same person, each user only has 1 inventory heirarchy
* - The returned list is not ordered, instead of breadth-first ordered
There are basically 2 usage cases for getFolderHeirarchy:
1) Getting the user's entire inventory heirarchy when they log in
2) Finding a subfolder heirarchy to delete when emptying the trash.
This implementation will pull all inventory folders from the database, and then prune away any folder that
is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the
database than to make n requests. This pays off only if requested heirarchy is large.
By making this choice, we are making the worst case better at the cost of making the best case worse
- Francis
*/
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
DataRow[] folderRows = null, parentRow;
InventoryFolderBase parentFolder = null;
lock (ds)
{
/* Fetch the parent folder from the database to determine the agent ID.
* Then fetch all inventory folders for that agent from the agent ID.
*/
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "UUID = '" + parentID + "'";
parentRow = inventoryFolderTable.Select(selectExp); // Assume at most 1 result
if (parentRow.GetLength(0) >= 1) // No result means parent folder does not exist
{
parentFolder = buildFolder(parentRow[0]);
UUID agentID = parentFolder.Owner;
selectExp = "agentID = '" + agentID + "'";
folderRows = inventoryFolderTable.Select(selectExp);
}
if (folderRows != null && folderRows.GetLength(0) >= 1) // No result means parent folder does not exist
{ // or has no children
/* if we're querying the root folder, just return an unordered list of all folders in the user's
* inventory
*/
if (parentFolder.ParentID == UUID.Zero)
{
foreach (DataRow row in folderRows)
{
InventoryFolderBase curFolder = buildFolder(row);
if (curFolder.ID != parentID) // Return all folders except the parent folder of heirarchy
folders.Add(buildFolder(row));
}
} // If requesting root folder
/* else we are querying a non-root folder. We currently have a list of all of the user's folders,
* we must construct a list of all folders in the heirarchy below parentID.
* Our first step will be to construct a hash table of all folders, indexed by parent ID.
* Once we have constructed the hash table, we will do a breadth-first traversal on the tree using the
* hash table to find child folders.
*/
else
{ // Querying a non-root folder
// Build a hash table of all user's inventory folders, indexed by each folder's parent ID
Dictionary<UUID, List<InventoryFolderBase>> hashtable =
new Dictionary<UUID, List<InventoryFolderBase>>(folderRows.GetLength(0));
foreach (DataRow row in folderRows)
{
InventoryFolderBase curFolder = buildFolder(row);
if (curFolder.ParentID != UUID.Zero) // Discard root of tree - not needed
{
if (hashtable.ContainsKey(curFolder.ParentID))
{
// Current folder already has a sibling - append to sibling list
hashtable[curFolder.ParentID].Add(curFolder);
}
else
{
List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>();
siblingList.Add(curFolder);
// Current folder has no known (yet) siblings
hashtable.Add(curFolder.ParentID, siblingList);
}
}
} // For all inventory folders
// Note: Could release the ds lock here - we don't access folderRows or the database anymore.
// This is somewhat of a moot point as the callers of this function usually lock db anyways.
if (hashtable.ContainsKey(parentID)) // if requested folder does have children
folders.AddRange(hashtable[parentID]);
// BreadthFirstSearch build inventory tree **Note: folders.Count is *not* static
for (int i = 0; i < folders.Count; i++)
if (hashtable.ContainsKey(folders[i].ID))
folders.AddRange(hashtable[folders[i].ID]);
} // if requesting a subfolder heirarchy
} // if folder parentID exists and has children
} // lock ds
return folders;
}
/// <summary>
/// Returns an inventory item by its UUID
/// </summary>
/// <param name="item">The UUID of the item to be returned</param>
/// <returns>A class containing item information</returns>
public InventoryItemBase getInventoryItem(UUID item)
{
lock (ds)
{
DataRow row = ds.Tables["inventoryitems"].Rows.Find(item.ToString());
if (row != null)
{
return buildItem(row);
}
else
{
return null;
}
}
}
/// <summary>
/// Returns a specified inventory folder by its UUID
/// </summary>
/// <param name="folder">The UUID of the folder to be returned</param>
/// <returns>A class containing folder information</returns>
public InventoryFolderBase getInventoryFolder(UUID folder)
{
// TODO: Deep voodoo here. If you enable this code then
// multi region breaks. No idea why, but I figured it was
// better to leave multi region at this point. It does mean
// that you don't get to see system textures why creating
// clothes and the like. :(
lock (ds)
{
DataRow row = ds.Tables["inventoryfolders"].Rows.Find(folder.ToString());
if (row != null)
{
return buildFolder(row);
}
else
{
return null;
}
}
}
/// <summary>
/// Creates a new inventory item based on item
/// </summary>
/// <param name="item">The item to be created</param>
public void addInventoryItem(InventoryItemBase item)
{
addItem(item, true);
}
/// <summary>
/// Updates an inventory item with item (updates based on ID)
/// </summary>
/// <param name="item">The updated item</param>
public void updateInventoryItem(InventoryItemBase item)
{
addItem(item, false);
}
/// <summary>
/// Delete an inventory item
/// </summary>
/// <param name="item">The item UUID</param>
public void deleteInventoryItem(UUID itemID)
{
lock (ds)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
DataRow inventoryRow = inventoryItemTable.Rows.Find(itemID.ToString());
if (inventoryRow != null)
{
inventoryRow.Delete();
}
invItemsDa.Update(ds, "inventoryitems");
}
}
public InventoryItemBase queryInventoryItem(UUID itemID)
{
return getInventoryItem(itemID);
}
public InventoryFolderBase queryInventoryFolder(UUID folderID)
{
return getInventoryFolder(folderID);
}
/// <summary>
/// Delete all items in the specified folder
/// </summary>
/// <param name="folderId">id of the folder, whose item content should be deleted</param>
/// <todo>this is horribly inefficient, but I don't want to ruin the overall structure of this implementation</todo>
private void deleteItemsInFolder(UUID folderId)
{
List<InventoryItemBase> items = getInventoryInFolder(folderId);
foreach (InventoryItemBase i in items)
deleteInventoryItem(i.ID);
}
/// <summary>
/// Adds a new folder specified by folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void addInventoryFolder(InventoryFolderBase folder)
{
addFolder(folder, true);
}
/// <summary>
/// Updates a folder based on its ID with folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void updateInventoryFolder(InventoryFolderBase folder)
{
addFolder(folder, false);
}
/// <summary>
/// Moves a folder based on its ID with folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void moveInventoryFolder(InventoryFolderBase folder)
{
moveFolder(folder);
}
/// <summary>
/// Delete a folder
/// </summary>
/// <remarks>
/// This will clean-up any child folders and child items as well
/// </remarks>
/// <param name="folderID">the folder UUID</param>
public void deleteInventoryFolder(UUID folderID)
{
lock (ds)
{
List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID);
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow;
//Delete all sub-folders
foreach (InventoryFolderBase f in subFolders)
{
inventoryRow = inventoryFolderTable.Rows.Find(f.ID.ToString());
if (inventoryRow != null)
{
deleteItemsInFolder(f.ID);
inventoryRow.Delete();
}
}
//Delete the actual row
inventoryRow = inventoryFolderTable.Rows.Find(folderID.ToString());
if (inventoryRow != null)
{
deleteItemsInFolder(folderID);
inventoryRow.Delete();
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/***********************************************************************
*
* Data Table definitions
*
**********************************************************************/
/// <summary>
/// Create the "inventoryitems" table
/// </summary>
private static DataTable createInventoryItemsTable()
{
DataTable inv = new DataTable("inventoryitems");
createCol(inv, "UUID", typeof (String)); //inventoryID
createCol(inv, "assetID", typeof (String));
createCol(inv, "assetType", typeof (Int32));
createCol(inv, "invType", typeof (Int32));
createCol(inv, "parentFolderID", typeof (String));
createCol(inv, "avatarID", typeof (String));
createCol(inv, "creatorsID", typeof (String));
createCol(inv, "inventoryName", typeof (String));
createCol(inv, "inventoryDescription", typeof (String));
// permissions
createCol(inv, "inventoryNextPermissions", typeof (Int32));
createCol(inv, "inventoryCurrentPermissions", typeof (Int32));
createCol(inv, "inventoryBasePermissions", typeof (Int32));
createCol(inv, "inventoryEveryOnePermissions", typeof (Int32));
createCol(inv, "inventoryGroupPermissions", typeof (Int32));
// sale info
createCol(inv, "salePrice", typeof(Int32));
createCol(inv, "saleType", typeof(Byte));
// creation date
createCol(inv, "creationDate", typeof(Int32));
// group info
createCol(inv, "groupID", typeof(String));
createCol(inv, "groupOwned", typeof(Boolean));
// Flags
createCol(inv, "flags", typeof(UInt32));
inv.PrimaryKey = new DataColumn[] { inv.Columns["UUID"] };
return inv;
}
/// <summary>
/// Creates the "inventoryfolders" table
/// </summary>
/// <returns></returns>
private static DataTable createInventoryFoldersTable()
{
DataTable fol = new DataTable("inventoryfolders");
createCol(fol, "UUID", typeof (String)); //folderID
createCol(fol, "name", typeof (String));
createCol(fol, "agentID", typeof (String));
createCol(fol, "parentID", typeof (String));
createCol(fol, "type", typeof (Int32));
createCol(fol, "version", typeof (Int32));
fol.PrimaryKey = new DataColumn[] {fol.Columns["UUID"]};
return fol;
}
/// <summary>
///
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn)
{
lock (ds)
{
da.InsertCommand = createInsertCommand("inventoryitems", ds.Tables["inventoryitems"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("inventoryitems", "UUID=:UUID", ds.Tables["inventoryitems"]);
da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from inventoryitems where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
}
/// <summary>
///
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupFoldersCommands(SqliteDataAdapter da, SqliteConnection conn)
{
lock (ds)
{
da.InsertCommand = createInsertCommand("inventoryfolders", ds.Tables["inventoryfolders"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("inventoryfolders", "UUID=:UUID", ds.Tables["inventoryfolders"]);
da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from inventoryfolders where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
private static InventoryFolderBase buildFolder(DataRow row)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = new UUID((string) row["UUID"]);
folder.Name = (string) row["name"];
folder.Owner = new UUID((string) row["agentID"]);
folder.ParentID = new UUID((string) row["parentID"]);
folder.Type = Convert.ToInt16(row["type"]);
folder.Version = Convert.ToUInt16(row["version"]);
return folder;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <param name="folder"></param>
private static void fillFolderRow(DataRow row, InventoryFolderBase folder)
{
row["UUID"] = folder.ID.ToString();
row["name"] = folder.Name;
row["agentID"] = folder.Owner.ToString();
row["parentID"] = folder.ParentID.ToString();
row["type"] = folder.Type;
row["version"] = folder.Version;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <param name="folder"></param>
private static void moveFolderRow(DataRow row, InventoryFolderBase folder)
{
row["UUID"] = folder.ID.ToString();
row["parentID"] = folder.ParentID.ToString();
}
public List<InventoryItemBase> fetchActiveGestures (UUID avatarID)
{
lock (ds)
{
List<InventoryItemBase> items = new List<InventoryItemBase>();
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
string selectExp
= "avatarID = '" + avatarID + "' AND assetType = " + (int)AssetType.Gesture + " AND flags = 1";
//m_log.DebugFormat("[SQL]: sql = " + selectExp);
DataRow[] rows = inventoryItemTable.Select(selectExp);
foreach (DataRow row in rows)
{
items.Add(buildItem(row));
}
return items;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Notifications;
using QuantConnect.Packets;
namespace QuantConnect.Messaging
{
/// <summary>
/// Desktop implementation of messaging system for Lean Engine
/// </summary>
public class EventMessagingHandler : IMessagingHandler
{
private AlgorithmNodePacket _job;
private volatile bool _loaded;
private Queue<Packet> _queue;
/// <summary>
/// Gets or sets whether this messaging handler has any current subscribers.
/// When set to false, messages won't be sent.
/// </summary>
public bool HasSubscribers
{
get;
set;
}
/// <summary>
/// Initialize the Messaging System Plugin.
/// </summary>
public void Initialize()
{
_queue = new Queue<Packet>();
ConsumerReadyEvent += () => { _loaded = true; };
}
/// <summary>
/// Set Loaded to true
/// </summary>
public void LoadingComplete()
{
_loaded = true;
}
/// <summary>
/// Set the user communication channel
/// </summary>
/// <param name="job"></param>
public void SetAuthentication(AlgorithmNodePacket job)
{
_job = job;
}
#pragma warning disable 1591
public delegate void DebugEventRaised(DebugPacket packet);
public event DebugEventRaised DebugEvent;
public delegate void SystemDebugEventRaised(SystemDebugPacket packet);
#pragma warning disable 0067 // SystemDebugEvent is not used currently; ignore the warning
public event SystemDebugEventRaised SystemDebugEvent;
#pragma warning restore 0067
public delegate void LogEventRaised(LogPacket packet);
public event LogEventRaised LogEvent;
public delegate void RuntimeErrorEventRaised(RuntimeErrorPacket packet);
public event RuntimeErrorEventRaised RuntimeErrorEvent;
public delegate void HandledErrorEventRaised(HandledErrorPacket packet);
public event HandledErrorEventRaised HandledErrorEvent;
public delegate void BacktestResultEventRaised(BacktestResultPacket packet);
public event BacktestResultEventRaised BacktestResultEvent;
public delegate void ConsumerReadyEventRaised();
public event ConsumerReadyEventRaised ConsumerReadyEvent;
#pragma warning restore 1591
/// <summary>
/// Send any message with a base type of Packet.
/// </summary>
public void Send(Packet packet)
{
//Until we're loaded queue it up
if (!_loaded)
{
_queue.Enqueue(packet);
return;
}
//Catch up if this is the first time
while (_queue.Count > 0)
{
ProcessPacket(_queue.Dequeue());
}
//Finally process this new packet
ProcessPacket(packet);
}
/// <summary>
/// Send any notification with a base type of Notification.
/// </summary>
/// <param name="notification">The notification to be sent.</param>
public void SendNotification(Notification notification)
{
var type = notification.GetType();
if (type == typeof (NotificationEmail) || type == typeof (NotificationWeb) || type == typeof (NotificationSms) || type == typeof (NotificationTelegram))
{
Log.Error("Messaging.SendNotification(): Send not implemented for notification of type: " + type.Name);
return;
}
notification.Send();
}
/// <summary>
/// Send any message with a base type of Packet that has been enqueued.
/// </summary>
public void SendEnqueuedPackets()
{
while (_queue.Count > 0 && _loaded)
{
ProcessPacket(_queue.Dequeue());
}
}
/// <summary>
/// Packet processing implementation
/// </summary>
private void ProcessPacket(Packet packet)
{
//Packets we handled in the UX.
switch (packet.Type)
{
case PacketType.Debug:
var debug = (DebugPacket)packet;
OnDebugEvent(debug);
break;
case PacketType.SystemDebug:
var systemDebug = (SystemDebugPacket)packet;
OnSystemDebugEvent(systemDebug);
break;
case PacketType.Log:
var log = (LogPacket)packet;
OnLogEvent(log);
break;
case PacketType.RuntimeError:
var runtime = (RuntimeErrorPacket)packet;
OnRuntimeErrorEvent(runtime);
break;
case PacketType.HandledError:
var handled = (HandledErrorPacket)packet;
OnHandledErrorEvent(handled);
break;
case PacketType.BacktestResult:
var result = (BacktestResultPacket)packet;
OnBacktestResultEvent(result);
break;
}
}
/// <summary>
/// Raise a debug event safely
/// </summary>
protected virtual void OnDebugEvent(DebugPacket packet)
{
var handler = DebugEvent;
if (handler != null)
{
handler(packet);
}
}
/// <summary>
/// Raise a system debug event safely
/// </summary>
protected virtual void OnSystemDebugEvent(SystemDebugPacket packet)
{
var handler = DebugEvent;
if (handler != null)
{
handler(packet);
}
}
/// <summary>
/// Handler for consumer ready code.
/// </summary>
public virtual void OnConsumerReadyEvent()
{
var handler = ConsumerReadyEvent;
if (handler != null)
{
handler();
}
}
/// <summary>
/// Raise a log event safely
/// </summary>
protected virtual void OnLogEvent(LogPacket packet)
{
var handler = LogEvent;
if (handler != null)
{
handler(packet);
}
}
/// <summary>
/// Raise a handled error event safely
/// </summary>
protected virtual void OnHandledErrorEvent(HandledErrorPacket packet)
{
var handler = HandledErrorEvent;
if (handler != null)
{
handler(packet);
}
}
/// <summary>
/// Raise runtime error safely
/// </summary>
protected virtual void OnRuntimeErrorEvent(RuntimeErrorPacket packet)
{
var handler = RuntimeErrorEvent;
if (handler != null)
{
handler(packet);
}
}
/// <summary>
/// Raise a backtest result event safely.
/// </summary>
protected virtual void OnBacktestResultEvent(BacktestResultPacket packet)
{
var handler = BacktestResultEvent;
if (handler != null)
{
handler(packet);
}
}
/// <summary>
/// Dispose of any resources
/// </summary>
public virtual void Dispose()
{
}
}
}
| |
namespace Faithlife.Utility
{
/// <summary>
/// Provides methods for manipulating integers.
/// </summary>
public static class HashCodeUtility
{
/// <summary>
/// Gets a hash code for the specified <see cref="int"/>; this hash code is guaranteed not to change in future.
/// </summary>
/// <param name="value">The <see cref="int"/> to hash.</param>
/// <returns>A hash code for the specified <see cref="int"/>.</returns>
/// <remarks>Based on "Robert Jenkins' 32 bit integer hash function" at http://www.concentric.net/~Ttwang/tech/inthash.htm</remarks>
public static int GetPersistentHashCode(int value)
{
unchecked
{
var n = (uint) value;
n = (n + 0x7ed55d16) + (n << 12);
n = (n ^ 0xc761c23c) ^ (n >> 19);
n = (n + 0x165667b1) + (n << 5);
n = (n + 0xd3a2646c) ^ (n << 9);
n = (n + 0xfd7046c5) + (n << 3);
n = (n ^ 0xb55a4f09) ^ (n >> 16);
return (int) n;
}
}
/// <summary>
/// Gets a hash code for the specified <see cref="long"/>; this hash code is guaranteed not to change in future.
/// </summary>
/// <param name="value">The <see cref="long"/> to hash.</param>
/// <returns>A hash code for the specified <see cref="long"/>.</returns>
/// <remarks>Based on "64 bit to 32 bit Hash Functions" at http://www.concentric.net/~Ttwang/tech/inthash.htm</remarks>
public static int GetPersistentHashCode(long value)
{
unchecked
{
var n = (ulong) value;
n = (~n) + (n << 18);
n = n ^ (n >> 31);
n = n * 21;
n = n ^ (n >> 11);
n = n + (n << 6);
n = n ^ (n >> 22);
return (int) n;
}
}
/// <summary>
/// Gets a hash code for the specified <see cref="bool"/>; this hash code is guaranteed not to change in future.
/// </summary>
/// <param name="value">The <see cref="bool"/> to hash.</param>
/// <returns>A hash code for the specified <see cref="bool"/>.</returns>
public static int GetPersistentHashCode(bool value)
{
// these values are the persistent hash codes for 0 and 1
return value ? -1266253386 : 1800329511;
}
/// <summary>
/// Combines the specified hash codes.
/// </summary>
/// <param name="hashCode1">The first hash code.</param>
/// <returns>The combined hash code.</returns>
/// <remarks>This is a specialization of <see cref="CombineHashCodes(int[])"/> for efficiency.</remarks>
public static int CombineHashCodes(int hashCode1)
{
unchecked
{
var a = 0xdeadbeef + 4;
var b = a;
var c = a;
a += (uint) hashCode1;
FinalizeHash(ref a, ref b, ref c);
return (int) c;
}
}
/// <summary>
/// Combines the specified hash codes.
/// </summary>
/// <param name="hashCode1">The first hash code.</param>
/// <param name="hashCode2">The second hash code.</param>
/// <returns>The combined hash code.</returns>
/// <remarks>This is a specialization of <see cref="CombineHashCodes(int[])"/> for efficiency.</remarks>
public static int CombineHashCodes(int hashCode1, int hashCode2)
{
unchecked
{
var a = 0xdeadbeef + 8;
var b = a;
var c = a;
a += (uint) hashCode1;
b += (uint) hashCode2;
FinalizeHash(ref a, ref b, ref c);
return (int) c;
}
}
/// <summary>
/// Combines the specified hash codes.
/// </summary>
/// <param name="hashCode1">The first hash code.</param>
/// <param name="hashCode2">The second hash code.</param>
/// <param name="hashCode3">The third hash code.</param>
/// <returns>The combined hash code.</returns>
/// <remarks>This is a specialization of <see cref="CombineHashCodes(int[])"/> for efficiency.</remarks>
public static int CombineHashCodes(int hashCode1, int hashCode2, int hashCode3)
{
unchecked
{
var a = 0xdeadbeef + 12;
var b = a;
var c = a;
a += (uint) hashCode1;
b += (uint) hashCode2;
c += (uint) hashCode3;
FinalizeHash(ref a, ref b, ref c);
return (int) c;
}
}
/// <summary>
/// Combines the specified hash codes.
/// </summary>
/// <param name="hashCode1">The first hash code.</param>
/// <param name="hashCode2">The second hash code.</param>
/// <param name="hashCode3">The third hash code.</param>
/// <param name="hashCode4">The fourth hash code.</param>
/// <returns>The combined hash code.</returns>
/// <remarks>This is a specialization of <see cref="CombineHashCodes(int[])"/> for efficiency.</remarks>
public static int CombineHashCodes(int hashCode1, int hashCode2, int hashCode3, int hashCode4)
{
unchecked
{
var a = 0xdeadbeef + 16;
var b = a;
var c = a;
a += (uint) hashCode1;
b += (uint) hashCode2;
c += (uint) hashCode3;
MixHash(ref a, ref b, ref c);
a += (uint) hashCode4;
FinalizeHash(ref a, ref b, ref c);
return (int) c;
}
}
/// <summary>
/// Combines the specified hash codes.
/// </summary>
/// <param name="hashCodes">An array of hash codes.</param>
/// <returns>The combined hash code.</returns>
/// <remarks>This method is based on the "hashword" function at http://burtleburtle.net/bob/c/lookup3.c. It attempts to thoroughly
/// mix all the bits in the input hash codes.</remarks>
public static int CombineHashCodes(params int[]? hashCodes)
{
unchecked
{
// check for null
if (hashCodes is null)
return 0x0d608219;
var nLength = hashCodes.Length;
var a = 0xdeadbeef + (((uint) nLength) << 2);
var b = a;
var c = a;
var nIndex = 0;
while (nLength - nIndex > 3)
{
a += (uint) hashCodes[nIndex];
b += (uint) hashCodes[nIndex + 1];
c += (uint) hashCodes[nIndex + 2];
MixHash(ref a, ref b, ref c);
nIndex += 3;
}
if (nLength - nIndex > 2)
c += (uint) hashCodes[nIndex + 2];
if (nLength - nIndex > 1)
b += (uint) hashCodes[nIndex + 1];
if (nLength - nIndex > 0)
{
a += (uint) hashCodes[nIndex];
FinalizeHash(ref a, ref b, ref c);
}
return (int) c;
}
}
// The "rot()" macro from http://burtleburtle.net/bob/c/lookup3.c
private static uint Rotate(uint x, int k)
{
return (x << k) | (x >> (32 - k));
}
// The "mix()" macro from http://burtleburtle.net/bob/c/lookup3.c
private static void MixHash(ref uint a, ref uint b, ref uint c)
{
unchecked
{
a -= c;
a ^= Rotate(c, 4);
c += b;
b -= a;
b ^= Rotate(a, 6);
a += c;
c -= b;
c ^= Rotate(b, 8);
b += a;
a -= c;
a ^= Rotate(c, 16);
c += b;
b -= a;
b ^= Rotate(a, 19);
a += c;
c -= b;
c ^= Rotate(b, 4);
b += a;
}
}
// The "final()" macro from http://burtleburtle.net/bob/c/lookup3.c
private static void FinalizeHash(ref uint a, ref uint b, ref uint c)
{
unchecked
{
c ^= b;
c -= Rotate(b, 14);
a ^= c;
a -= Rotate(c, 11);
b ^= a;
b -= Rotate(a, 25);
c ^= b;
c -= Rotate(b, 16);
a ^= c;
a -= Rotate(c, 4);
b ^= a;
b -= Rotate(a, 14);
c ^= b;
c -= Rotate(b, 24);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ComponentDispatcher.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Security.Permissions;
using MS.Internal;
using MS.Win32;
using MS.Internal.WindowsBase;
namespace System.Windows.Interop
{
/// <summary>
/// This is the delegate used for registering with the
/// ThreadFilterMessage and ThreadPreprocessMessage Events.
///</summary>
[SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
public delegate void ThreadMessageEventHandler(ref MSG msg, ref bool handled);
/// <summary>
/// This is a static class used to share control of the message pump.
/// Whomever is pumping (i.e. calling GetMessage()) will also send
/// the messages to RaiseThreadKeyMessage() which will dispatch them to
/// the ThreadFilterMessage and then (if not handled) to the ThreadPreprocessMessage
/// delegates. That way everyone can be included in the message loop.
/// Currently only Keyboard messages are supported.
/// There are also Events for Idle and facilities for Thread-Modal operation.
///</summary>
public static class ComponentDispatcher
{
static ComponentDispatcher()
{
_threadSlot = Thread.AllocateDataSlot();
}
private static ComponentDispatcherThread CurrentThreadData
{
get
{
ComponentDispatcherThread data;
object obj = Thread.GetData(_threadSlot);
if(null == obj)
{
data = new ComponentDispatcherThread();
Thread.SetData(_threadSlot, data);
}
else
{
data = (ComponentDispatcherThread) obj;
}
return data;
}
}
// Properties
/// <summary>
/// Returns true if one or more components has gone modal.
/// Although once one component is modal a 2nd shouldn't.
///</summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// PublicOk: There is a demand here
/// </SecurityNote>
public static bool IsThreadModal
{
[SecurityCritical]
get
{
SecurityHelper.DemandUnrestrictedUIPermission();
ComponentDispatcherThread data = ComponentDispatcher.CurrentThreadData;
return data.IsThreadModal;
}
}
/// <summary>
/// Returns "current" message. More exactly the last MSG Raised.
///</summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// PublicOk: There is a demand here
/// </SecurityNote>
public static MSG CurrentKeyboardMessage
{
[SecurityCritical]
get
{
SecurityHelper.DemandUnrestrictedUIPermission();
return ComponentDispatcher.CurrentThreadData.CurrentKeyboardMessage;
}
}
/// <summary>
/// Returns "current" message. More exactly the last MSG Raised.
///</summary>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// </SecurityNote>
internal static MSG UnsecureCurrentKeyboardMessage
{
[FriendAccessAllowed] // Built into Base, used by Core or Framework.
[SecurityCritical]
get
{
return ComponentDispatcher.CurrentThreadData.CurrentKeyboardMessage;
}
[FriendAccessAllowed] // Built into Base, used by Core or Framework.
[SecurityCritical]
set
{
ComponentDispatcher.CurrentThreadData.CurrentKeyboardMessage = value;
}
}
// Methods
/// <summary>
/// A component calls this to go modal. Current thread wide only.
///</summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// PublicOk: There is a demand here
/// </SecurityNote>
[SecurityCritical]
public static void PushModal()
{
SecurityHelper.DemandUnrestrictedUIPermission();
CriticalPushModal();
}
/// <summary>
/// A component calls this to go modal. Current thread wide only.
///</summary>
/// <SecurityNote>
/// Critical: This bypasses the demand for unrestricted UIPermission.
/// </SecurityNote>
[SecurityCritical]
internal static void CriticalPushModal()
{
ComponentDispatcherThread data = ComponentDispatcher.CurrentThreadData;
data.PushModal();
}
/// <summary>
/// A component calls this to end being modal.
///</summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// PublicOk: There is a demand here
/// </SecurityNote>
[SecurityCritical]
public static void PopModal()
{
SecurityHelper.DemandUnrestrictedUIPermission();
CriticalPopModal();
}
/// <summary>
/// A component calls this to end being modal.
///</summary>
/// <SecurityNote>
/// Critical: This bypasses the demand for unrestricted UIPermission.
/// </SecurityNote>
[SecurityCritical]
internal static void CriticalPopModal()
{
ComponentDispatcherThread data = ComponentDispatcher.CurrentThreadData;
data.PopModal();
}
/// <summary>
/// The message loop pumper calls this when it is time to do idle processing.
///</summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// PublicOk: There is a demand here
/// </SecurityNote>
[SecurityCritical]
[UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
public static void RaiseIdle()
{
ComponentDispatcherThread data = ComponentDispatcher.CurrentThreadData;
data.RaiseIdle();
}
/// <summary>
/// The message loop pumper calls this for every keyboard message.
/// </summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// PublicOk: There is a demand here
/// </SecurityNote>
[SecurityCritical]
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
[SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
[UIPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
public static bool RaiseThreadMessage(ref MSG msg)
{
ComponentDispatcherThread data = ComponentDispatcher.CurrentThreadData;
return data.RaiseThreadMessage(ref msg);
}
// Events
/// <summary>
/// Components register delegates with this event to handle
/// thread idle processing.
///</summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// PublicOk: There is a demand here
/// </SecurityNote>
public static event EventHandler ThreadIdle
{
[SecurityCritical]
add {
SecurityHelper.DemandUnrestrictedUIPermission();
ComponentDispatcher.CurrentThreadData.ThreadIdle += value;
}
[SecurityCritical]
remove {
SecurityHelper.DemandUnrestrictedUIPermission();
ComponentDispatcher.CurrentThreadData.ThreadIdle -= value;
}
}
/// <summary>
/// Components register delegates with this event to handle
/// Keyboard Messages (first chance processing).
///</summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// PublicOk: There is a demand here
/// </SecurityNote>
[SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
public static event ThreadMessageEventHandler ThreadFilterMessage
{
[SecurityCritical]
add {
SecurityHelper.DemandUnrestrictedUIPermission();
ComponentDispatcher.CurrentThreadData.ThreadFilterMessage += value;
}
[SecurityCritical]
remove {
SecurityHelper.DemandUnrestrictedUIPermission();
ComponentDispatcher.CurrentThreadData.ThreadFilterMessage -= value;
}
}
/// <summary>
/// Components register delegates with this event to handle
/// Keyboard Messages (second chance processing).
///</summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: Exposing the raw input enables tampering. (The MSG structure is passed by-ref.)
/// PublicOk: There is a demand here
/// </SecurityNote>
[SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")]
public static event ThreadMessageEventHandler ThreadPreprocessMessage
{
[UIPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
[SecurityCritical]
add
{
ComponentDispatcher.CurrentThreadData.ThreadPreprocessMessage += value;
}
[UIPermissionAttribute(SecurityAction.LinkDemand, Unrestricted=true)]
[SecurityCritical]
remove {
ComponentDispatcher.CurrentThreadData.ThreadPreprocessMessage -= value;
}
}
/// <summary>
/// Adds the specified handler to the front of the invocation list
/// of the PreprocessMessage event.
/// <summary>
/// <SecurityNote>
/// Critical: Not to expose raw input, which may be destined for a
/// window in another security context. Also, MSG contains a window
/// handle, which we don't want to expose.
/// </SecurityNote>
[SecurityCritical]
internal static void CriticalAddThreadPreprocessMessageHandlerFirst(ThreadMessageEventHandler handler)
{
ComponentDispatcher.CurrentThreadData.AddThreadPreprocessMessageHandlerFirst(handler);
}
/// <summary>
/// Removes the first occurance of the specified handler from the
/// invocation list of the PreprocessMessage event.
/// <summary>
/// <SecurityNote>
/// Critical: Not to expose raw input, which may be destined for a
/// window in another security context. Also, MSG contains a window
/// handle, which we don't want to expose.
/// </SecurityNote>
[SecurityCritical]
internal static void CriticalRemoveThreadPreprocessMessageHandlerFirst(ThreadMessageEventHandler handler)
{
ComponentDispatcher.CurrentThreadData.RemoveThreadPreprocessMessageHandlerFirst(handler);
}
/// <summary>
/// Components register delegates with this event to handle
/// a component on this thread has "gone modal", when previously none were.
///</summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// PublicOk: There is a demand here
/// </SecurityNote>
public static event EventHandler EnterThreadModal
{
[SecurityCritical]
add {
SecurityHelper.DemandUnrestrictedUIPermission();
ComponentDispatcher.CurrentThreadData.EnterThreadModal += value;
}
[SecurityCritical]
remove {
SecurityHelper.DemandUnrestrictedUIPermission();
ComponentDispatcher.CurrentThreadData.EnterThreadModal -= value;
}
}
/// <summary>
/// Components register delegates with this event to handle
/// all components on this thread are done being modal.
///</summary>
/// <remarks>
/// Callers must have UIPermission(PermissionState.Unrestricted) to call this API.
/// </remarks>
/// <SecurityNote>
/// Critical: This is blocked off as defense in depth
/// PublicOk: There is a demand here
/// </SecurityNote>
public static event EventHandler LeaveThreadModal
{
[SecurityCritical]
add
{
SecurityHelper.DemandUnrestrictedUIPermission();
ComponentDispatcher.CurrentThreadData.LeaveThreadModal += value;
}
[SecurityCritical]
remove {
SecurityHelper.DemandUnrestrictedUIPermission();
ComponentDispatcher.CurrentThreadData.LeaveThreadModal -= value;
}
}
// member data
private static System.LocalDataStoreSlot _threadSlot;
}
};
| |
/*
* 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.Data;
using System.Reflection;
using log4net;
using MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.MySQL
{
public class MySQLGenericTableHandler<T> : MySqlFramework where T: class, new()
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public MySQLGenericTableHandler(string connectionString,
string realm, string storeName) : base(connectionString)
{
m_Realm = realm;
m_connectionString = connectionString;
if (storeName != String.Empty)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, storeName);
m.Update();
}
}
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (fields.Length == 0)
return;
foreach (FieldInfo f in fields)
{
if (f.Name != "Data")
m_Fields[f.Name] = f;
else
m_DataField = f;
}
}
private void CheckColumnNames(IDataReader reader)
{
if (m_ColumnNames != null)
return;
List<string> columnNames = new List<string>();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null &&
(!m_Fields.ContainsKey(row["ColumnName"].ToString())))
columnNames.Add(row["ColumnName"].ToString());
}
m_ColumnNames = columnNames;
}
public virtual T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public virtual T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
using (MySqlCommand cmd = new MySqlCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
terms.Add("`" + fields[i] + "` = ?" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
}
protected T[] DoQuery(MySqlCommand cmd)
{
List<T> result = new List<T>();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
cmd.Connection = dbcon;
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader == null)
return new T[0];
CheckColumnNames(reader);
while (reader.Read())
{
T row = new T();
foreach (string name in m_Fields.Keys)
{
if (reader[name] is DBNull)
{
continue;
}
if (m_Fields[name].FieldType == typeof(bool))
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0 ? true : false);
}
else if (m_Fields[name].FieldType == typeof(UUID))
{
m_Fields[name].SetValue(row, DBGuid.FromDB(reader[name]));
}
else if (m_Fields[name].FieldType == typeof(int))
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else if (m_Fields[name].FieldType == typeof(uint))
{
uint v = Convert.ToUInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else
{
m_Fields[name].SetValue(row, reader[name]);
}
}
if (m_DataField != null)
{
Dictionary<string, string> data =
new Dictionary<string, string>();
foreach (string col in m_ColumnNames)
{
data[col] = reader[col].ToString();
if (data[col] == null)
data[col] = String.Empty;
}
m_DataField.SetValue(row, data);
}
result.Add(row);
}
}
}
return result.ToArray();
}
public virtual T[] Get(string where)
{
using (MySqlCommand cmd = new MySqlCommand())
{
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
}
public virtual bool Store(T row)
{
// m_log.DebugFormat("[MYSQL GENERIC TABLE HANDLER]: Store(T row) invoked");
using (MySqlCommand cmd = new MySqlCommand())
{
string query = "";
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add("?" + fi.Name);
// Temporarily return more information about what field is unexpectedly null for
// http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
// InventoryTransferModule or we may be required to substitute a DBNull here.
if (fi.GetValue(row) == null)
throw new NullReferenceException(
string.Format(
"[MYSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
fi.Name, row));
cmd.Parameters.AddWithValue(fi.Name, fi.GetValue(row).ToString());
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
names.Add(kvp.Key);
values.Add("?" + kvp.Key);
cmd.Parameters.AddWithValue("?" + kvp.Key, kvp.Value);
}
}
query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
cmd.CommandText = query;
if (ExecuteNonQuery(cmd) > 0)
return true;
return false;
}
}
public virtual bool Delete(string field, string key)
{
return Delete(new string[] { field }, new string[] { key });
}
public virtual bool Delete(string[] fields, string[] keys)
{
// m_log.DebugFormat(
// "[MYSQL GENERIC TABLE HANDLER]: Delete(string[] fields, string[] keys) invoked with {0}:{1}",
// string.Join(",", fields), string.Join(",", keys));
if (fields.Length != keys.Length)
return false;
List<string> terms = new List<string>();
using (MySqlCommand cmd = new MySqlCommand())
{
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
terms.Add("`" + fields[i] + "` = ?" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("delete from {0} where {1}", m_Realm, where);
cmd.CommandText = query;
return ExecuteNonQuery(cmd) > 0;
}
}
public long GetCount(string field, string key)
{
return GetCount(new string[] { field }, new string[] { key });
}
public long GetCount(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return 0;
List<string> terms = new List<string>();
using (MySqlCommand cmd = new MySqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
terms.Add("`" + fields[i] + "` = ?" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
Object result = DoQueryScalar(cmd);
return Convert.ToInt64(result);
}
}
public long GetCount(string where)
{
using (MySqlCommand cmd = new MySqlCommand())
{
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
object result = DoQueryScalar(cmd);
return Convert.ToInt64(result);
}
}
public object DoQueryScalar(MySqlCommand cmd)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
cmd.Connection = dbcon;
return cmd.ExecuteScalar();
}
}
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Text;
using System.Windows.Forms;
using SwarmCoordinatorInterface;
namespace SwarmCoordinator
{
public partial class SwarmCoordinator : Form
{
public bool Ticking = false;
public bool RestartRequested = false;
private TcpServerChannel ServerChannel = null;
public SwarmCoordinator()
{
InitializeComponent();
}
private void Log( string Message )
{
Debug.WriteLine( DateTime.Now.ToLongTimeString() + ": " + Message );
}
private void AppExceptionHandler( object sender, UnhandledExceptionEventArgs args )
{
Exception E = ( Exception )args.ExceptionObject;
Log( "Application exception: " + E.ToString() );
}
public void Init()
{
// Register application exception handler
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( AppExceptionHandler );
// Register in interface implementation
RemotingConfiguration.RegisterWellKnownServiceType( typeof( SwarmCoordinatorImplementation ), "SwarmCoordinator", WellKnownObjectMode.Singleton );
// Start up network services, by opening a network communication channel
ServerChannel = new TcpServerChannel( "CoordinatorServer", Properties.Settings.Default.CoordinatorRemotingPort );
ChannelServices.RegisterChannel( ServerChannel, false );
// Initialise the interface
Coordinator.Init();
// Set the title bar to include the name of the machine
TopLevelControl.Text = "Swarm Coordinator running on " + Environment.MachineName;
// Display the window
Show();
Ticking = true;
}
public bool Restarting()
{
return RestartRequested;
}
public void Destroy()
{
// Clean up the coordinator
Coordinator.Destroy();
// Free up the remoting channel
if( ServerChannel != null )
{
ChannelServices.UnregisterChannel( ServerChannel );
ServerChannel = null;
}
}
public void Run()
{
// Update the agent state based on the ping time
Coordinator.MaintainAgents();
// Update the grid view to represent to current state of the agents
UpdateGridRows();
}
private void UpdateGridRows()
{
if( Coordinator.AgentsDirty )
{
// Clear out any existing rows
AgentGridView.Rows.Clear();
// Get a list of agents
Dictionary<string, AgentInfo> Agents = Coordinator.GetAgents();
List<string> AgentNames = new List<string>( Agents.Keys );
AgentNames.Sort();
// Create a row for each agent
foreach( string AgentName in AgentNames )
{
AgentInfo NextAgent = Agents[AgentName];
DataGridViewRow Row = new DataGridViewRow();
DataGridViewTextBoxCell NextCell = null;
NextCell = new DataGridViewTextBoxCell();
NextCell.Value = NextAgent.Name;
if( NextAgent.Configuration.ContainsKey( "UserName" ) )
{
NextCell.Value += " (" + NextAgent.Configuration["UserName"] + ")";
}
else
{
NextCell.Value += " (UnknownUser)";
}
Row.Cells.Add( NextCell );
NextCell = new DataGridViewTextBoxCell();
if( NextAgent.Configuration.ContainsKey( "GroupName" ) )
{
NextCell.Value = NextAgent.Configuration["GroupName"];
}
else
{
NextCell.Value = "Undefined";
}
Row.Cells.Add( NextCell );
NextCell = new DataGridViewTextBoxCell();
NextCell.Value = NextAgent.Version;
Row.Cells.Add( NextCell );
NextCell = new DataGridViewTextBoxCell();
string NextCellStateValue;
if( NextAgent.State == AgentState.Working )
{
if( ( NextAgent.Configuration.ContainsKey( "WorkingFor" ) ) &&
( ( NextAgent.Configuration["WorkingFor"] as string ) != "" ) )
{
NextCellStateValue = "Working for " + NextAgent.Configuration["WorkingFor"];
}
else
{
NextCellStateValue = "Working for an unknown Agent";
}
}
else
{
NextCellStateValue = NextAgent.State.ToString();
}
if( ( NextAgent.Configuration.ContainsKey( "AssignedTo" ) ) &&
( ( NextAgent.Configuration["AssignedTo"] as string ) != "" ) )
{
NextCellStateValue += ", Assigned to " + NextAgent.Configuration["AssignedTo"];
}
else
{
NextCellStateValue += ", Unassigned";
}
NextCell.Value = NextCellStateValue;
Row.Cells.Add( NextCell );
NextCell = new DataGridViewTextBoxCell();
if( NextAgent.Configuration.ContainsKey( "IPAddress" ) )
{
NextCell.Value = NextAgent.Configuration["IPAddress"];
}
else
{
NextCell.Value = "Undefined";
}
Row.Cells.Add( NextCell );
NextCell = new DataGridViewTextBoxCell();
if( NextAgent.Configuration.ContainsKey( "LastPingTime" ) )
{
NextCell.Value = NextAgent.Configuration["LastPingTime"];
}
else
{
NextCell.Value = "Undefined";
}
Row.Cells.Add( NextCell );
NextCell = new DataGridViewTextBoxCell();
if( NextAgent.Configuration.ContainsKey( "LocalAvailableCores" ) )
{
NextCell.Value = NextAgent.Configuration["LocalAvailableCores"];
}
else
{
NextCell.Value = "Undefined";
}
Row.Cells.Add( NextCell );
NextCell = new DataGridViewTextBoxCell();
if( NextAgent.Configuration.ContainsKey( "RemoteAvailableCores" ) )
{
NextCell.Value = NextAgent.Configuration["RemoteAvailableCores"];
}
else
{
NextCell.Value = "Undefined";
}
Row.Cells.Add( NextCell );
AgentGridView.Rows.Add( Row );
}
Coordinator.AgentsDirty = false;
}
}
private void SwarmCoordinator_Closing( object sender, FormClosingEventArgs e )
{
Ticking = false;
}
private void RestartCoordinatorButton_Click( object sender, EventArgs e )
{
RestartRequested = true;
Ticking = false;
}
private void RestartQAAgentsButton_Click( object sender, EventArgs e )
{
Coordinator.RestartAgentGroup( "QATestGroup" );
}
private void RestartAllAgentsButton_Click( object sender, EventArgs e )
{
Coordinator.RestartAllAgents();
}
}
public class SwarmCoordinatorImplementation : MarshalByRefObject, ISwarmCoordinator
{
public PingResponse Ping( AgentInfo Agent )
{
return ( Coordinator.Ping( Agent ) );
}
public Int32 GetUniqueHandle()
{
return ( Coordinator.GetUniqueHandle() );
}
public List<AgentInfo> GetAvailableAgents( Hashtable RequestedConfiguration )
{
return ( Coordinator.GetAvailableAgents( RequestedConfiguration ) );
}
public Int32 RestartAgentGroup( string GroupNameToRestart )
{
return ( Coordinator.RestartAgentGroup( GroupNameToRestart ) );
}
public Int32 Method( Hashtable InParameters, ref Hashtable OutParameters )
{
return ( Coordinator.Method( InParameters, ref OutParameters ) );
}
}
}
| |
/*
* Copyright (c) 2012 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
using Com.Viperstudio.Utils;
namespace Com.Viperstudio.Utils
{
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (float) dict["float"]);
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to floats.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a float, an integer,a string, null, true, or false</returns>
public static object Deserialize (TextReader json) {
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WHITE_SPACE = " \t\n\r";
const string WORD_BREAK = " \t\n\r{}[],:\"";
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
TextReader json;
Parser(TextReader reader) {
json = reader;
}
public static object Parse (TextReader reader) {
using (var instance = new Parser(reader)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new StringBuilder();
for (int i=0; i< 4; i++) {
hex.Append(NextChar);
}
s.Append((char) Convert.ToInt32(hex.ToString(), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
float parsedFloat;
float.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out parsedFloat);
return parsedFloat;
}
void EatWhitespace() {
while (WHITE_SPACE.IndexOf(PeekChar) != -1) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (WORD_BREAK.IndexOf(PeekChar) == -1) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
char c = PeekChar;
switch (c) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
string word = NextWord;
switch (word) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
}
else if ((asStr = value as string) != null) {
SerializeString(asStr);
}
else if (value is bool) {
builder.Append(value.ToString().ToLower());
}
else if ((asList = value as IList) != null) {
SerializeArray(asList);
}
else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
}
else if (value is char) {
SerializeString(value.ToString());
}
else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
}
else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
if (value is float
|| value is int
|| value is uint
|| value is long
|| value is float
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong
|| value is decimal) {
builder.Append(value.ToString());
}
else {
SerializeString(value.ToString());
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using BTDB.Collections;
using BTDB.Encrypted;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.ODBLayer;
using BTDB.StreamLayer;
namespace BTDB.EventStoreLayer
{
class TypeSerializersMapping : ITypeSerializersMapping, ITypeSerializersLightMapping, ITypeSerializersId2LoaderMapping
{
const int ReservedBuiltInTypes = 50;
StructList<InfoForType?> _id2DescriptorMap;
readonly Dictionary<object, InfoForType> _typeOrDescriptor2Info = new Dictionary<object, InfoForType>(ReferenceEqualityComparer<object>.Instance);
readonly TypeSerializers _typeSerializers;
readonly ISymmetricCipher _symmetricCipher;
public TypeSerializersMapping(TypeSerializers typeSerializers)
{
_typeSerializers = typeSerializers;
_symmetricCipher = _typeSerializers.GetSymmetricCipher();
AddBuildInTypes();
}
public void Reset()
{
_id2DescriptorMap.Clear();
_typeOrDescriptor2Info.Clear();
AddBuildInTypes();
}
void AddBuildInTypes()
{
_id2DescriptorMap.Add(null); // 0 = null
_id2DescriptorMap.Add(null); // 1 = back reference
foreach (var predefinedType in BasicSerializersFactory.TypeDescriptors)
{
var infoForType = new InfoForType { Id = (int)_id2DescriptorMap.Count, Descriptor = predefinedType };
_typeOrDescriptor2Info[predefinedType] = infoForType;
_id2DescriptorMap.Add(infoForType);
}
while (_id2DescriptorMap.Count < ReservedBuiltInTypes) _id2DescriptorMap.Add(null);
}
public void LoadTypeDescriptors(AbstractBufferedReader reader)
{
var typeId = reader.ReadVUInt32();
var firstTypeId = typeId;
while (typeId != 0)
{
if (typeId < firstTypeId) firstTypeId = typeId;
var typeCategory = (TypeCategory)reader.ReadUInt8();
ITypeDescriptor descriptor;
switch (typeCategory)
{
case TypeCategory.BuildIn:
throw new ArgumentOutOfRangeException();
case TypeCategory.Class:
descriptor = new ObjectTypeDescriptor(_typeSerializers, reader, NestedDescriptorReader);
break;
case TypeCategory.List:
descriptor = new ListTypeDescriptor(_typeSerializers, reader, NestedDescriptorReader);
break;
case TypeCategory.Dictionary:
descriptor = new DictionaryTypeDescriptor(_typeSerializers, reader, NestedDescriptorReader);
break;
case TypeCategory.Enum:
descriptor = new EnumTypeDescriptor(_typeSerializers, reader);
break;
case TypeCategory.Nullable:
descriptor = new NullableTypeDescriptor(_typeSerializers, reader, NestedDescriptorReader);
break;
default:
throw new ArgumentOutOfRangeException();
}
while (typeId >= _id2DescriptorMap.Count)
_id2DescriptorMap.Add(null);
_id2DescriptorMap[(int) typeId] ??= new InfoForType {Id = (int) typeId, Descriptor = descriptor};
typeId = reader.ReadVUInt32();
}
for (var i = firstTypeId; i < _id2DescriptorMap.Count; i++)
{
_id2DescriptorMap[i]!.Descriptor.MapNestedTypes(d => d is PlaceHolderDescriptor placeHolderDescriptor ? _id2DescriptorMap[(int)placeHolderDescriptor.TypeId]!.Descriptor : d);
}
// This additional cycle is needed to fill names of recursive structures
for (var i = firstTypeId; i < _id2DescriptorMap.Count; i++)
{
_id2DescriptorMap[i]!.Descriptor.MapNestedTypes(d => d);
}
for (var i = firstTypeId; i < _id2DescriptorMap.Count; i++)
{
var infoForType = _id2DescriptorMap[(int)i];
var descriptor = _typeSerializers.MergeDescriptor(infoForType!.Descriptor);
infoForType.Descriptor = descriptor;
_typeOrDescriptor2Info[descriptor] = infoForType;
}
}
ITypeDescriptor NestedDescriptorReader(AbstractBufferedReader reader)
{
var typeId = reader.ReadVUInt32();
if (typeId < _id2DescriptorMap.Count)
{
var infoForType = _id2DescriptorMap[(int)typeId];
if (infoForType != null)
return infoForType.Descriptor;
}
return new PlaceHolderDescriptor(typeId);
}
class PlaceHolderDescriptor : ITypeDescriptor
{
internal uint TypeId { get; }
public PlaceHolderDescriptor(uint typeId)
{
TypeId = typeId;
}
bool IEquatable<ITypeDescriptor>.Equals(ITypeDescriptor other)
{
throw new InvalidOperationException();
}
string ITypeDescriptor.Name => "";
bool ITypeDescriptor.FinishBuildFromType(ITypeDescriptorFactory factory)
{
throw new InvalidOperationException();
}
void ITypeDescriptor.BuildHumanReadableFullName(StringBuilder text, HashSet<ITypeDescriptor> stack, uint indent)
{
throw new InvalidOperationException();
}
bool ITypeDescriptor.Equals(ITypeDescriptor other, HashSet<ITypeDescriptor> stack)
{
throw new InvalidOperationException();
}
Type? ITypeDescriptor.GetPreferredType()
{
return null;
}
public Type? GetPreferredType(Type targetType)
{
return null;
}
public bool AnyOpNeedsCtx()
{
throw new InvalidOperationException();
}
public void GenerateLoad(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx, Action<IILGen> pushDescriptor, Type targetType)
{
throw new InvalidOperationException();
}
public void GenerateSkip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx)
{
throw new InvalidOperationException();
}
public void GenerateSave(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx, Action<IILGen> pushValue, Type valueType)
{
throw new InvalidOperationException();
}
ITypeNewDescriptorGenerator ITypeDescriptor.BuildNewDescriptorGenerator()
{
throw new InvalidOperationException();
}
public ITypeDescriptor NestedType(int index)
{
throw new InvalidOperationException();
}
void ITypeDescriptor.MapNestedTypes(Func<ITypeDescriptor, ITypeDescriptor> map)
{
throw new InvalidOperationException();
}
bool ITypeDescriptor.Sealed => false;
bool ITypeDescriptor.StoredInline => false;
public bool LoadNeedsHelpWithConversion => false;
void ITypeDescriptor.ClearMappingToType()
{
throw new InvalidOperationException();
}
public bool ContainsField(string name)
{
throw new InvalidOperationException();
}
public ITypeDescriptor CloneAndMapNestedTypes(ITypeDescriptorCallbacks typeSerializers, Func<ITypeDescriptor, ITypeDescriptor> map)
{
throw new InvalidOperationException();
}
}
public object? LoadObject(AbstractBufferedReader reader)
{
var typeId = reader.ReadVUInt32();
if (typeId == 0)
{
return null;
}
if (typeId == 1)
{
throw new InvalidDataException("Backreference cannot be first object");
}
return Load(typeId, reader, null);
}
public object Load(uint typeId, AbstractBufferedReader reader, ITypeBinaryDeserializerContext? context)
{
var infoForType = _id2DescriptorMap[typeId];
if (infoForType!.Loader == null)
{
infoForType.Loader = _typeSerializers.GetLoader(infoForType.Descriptor);
}
return infoForType.Loader(reader, context, this, infoForType.Descriptor);
}
public ISymmetricCipher GetSymmetricCipher() => _symmetricCipher;
public bool SomeTypeStored => false;
public IDescriptorSerializerContext StoreNewDescriptors(AbstractBufferedWriter writer, object? obj)
{
if (obj == null) return this;
InfoForType infoForType;
var objType = obj.GetType();
if (obj is IKnowDescriptor iKnowDescriptor)
{
var descriptor = iKnowDescriptor.GetDescriptor();
if (!_typeOrDescriptor2Info.TryGetValue(descriptor, out infoForType))
{
infoForType = new InfoForType { Id = 0, Descriptor = descriptor };
}
}
else
{
if (!_typeOrDescriptor2Info.TryGetValue(objType, out infoForType))
{
var descriptor = _typeSerializers.DescriptorOf(objType);
if (!_typeOrDescriptor2Info.TryGetValue(descriptor!, out infoForType))
{
infoForType = new InfoForType { Id = 0, Descriptor = descriptor };
}
else
{
_typeOrDescriptor2Info[objType] = infoForType;
}
}
}
DescriptorSerializerContext ctx = null;
if (infoForType.Id == 0)
{
ctx = new DescriptorSerializerContext(this, writer);
ctx.AddDescriptor(infoForType);
}
ref var actions = ref infoForType.Type2Actions.GetOrAddValueRef(objType);
if (!actions.KnownNewTypeDiscoverer)
{
actions.NewTypeDiscoverer = _typeSerializers.GetNewDescriptorSaver(infoForType.Descriptor, objType);
actions.KnownNewTypeDiscoverer = true;
}
var action = actions.NewTypeDiscoverer;
if (action != null)
{
ctx ??= new DescriptorSerializerContext(this, writer);
action(obj, ctx);
}
if (ctx != null && ctx.SomeTypeStored)
{
return ctx;
}
return this;
}
public void CommitNewDescriptors()
{
}
class DescriptorSerializerContext : IDescriptorSerializerContext, IDescriptorSerializerLiteContext, ITypeSerializersLightMapping
{
readonly TypeSerializersMapping _typeSerializersMapping;
readonly AbstractBufferedWriter _writer;
readonly TypeSerializers _typeSerializers;
StructList<InfoForType> _id2InfoMap;
readonly Dictionary<object, InfoForType> _typeOrDescriptor2InfoMap = new Dictionary<object, InfoForType>(ReferenceEqualityComparer<object>.Instance);
public DescriptorSerializerContext(TypeSerializersMapping typeSerializersMapping, AbstractBufferedWriter writer)
{
_typeSerializersMapping = typeSerializersMapping;
_writer = writer;
_typeSerializers = _typeSerializersMapping._typeSerializers;
}
public void AddDescriptor(InfoForType infoForType)
{
infoForType.Id = (int)(_typeSerializersMapping._id2DescriptorMap.Count + _id2InfoMap.Count);
_typeOrDescriptor2InfoMap.Add(infoForType.Descriptor, infoForType);
_id2InfoMap.Add(infoForType);
var idx = 0;
ITypeDescriptor nestedDescriptor;
while ((nestedDescriptor = infoForType.Descriptor.NestedType(idx)) != null)
{
if (!TryDescriptor2Id(nestedDescriptor, out _))
AddDescriptor(new InfoForType { Descriptor = nestedDescriptor });
idx++;
}
}
uint Descriptor2Id(ITypeDescriptor? descriptor)
{
if (descriptor == null) return 0;
if (_typeOrDescriptor2InfoMap.TryGetValue(descriptor, out var infoForType))
return (uint)infoForType.Id;
if (_typeSerializersMapping._typeOrDescriptor2Info.TryGetValue(descriptor, out infoForType))
return (uint)infoForType.Id;
throw new InvalidOperationException();
}
bool TryDescriptor2Id(ITypeDescriptor descriptor, out int typeId)
{
if (_typeOrDescriptor2InfoMap.TryGetValue(descriptor, out var infoForType) ||
_typeSerializersMapping._typeOrDescriptor2Info.TryGetValue(descriptor, out infoForType))
{
typeId = infoForType.Id;
return true;
}
typeId = 0;
return false;
}
public bool SomeTypeStored => _id2InfoMap.Count != 0;
public IDescriptorSerializerContext StoreNewDescriptors(AbstractBufferedWriter writer, object? obj)
{
if (obj == null) return this;
InfoForType infoForType;
var objType = obj.GetType();
if (obj is IKnowDescriptor iKnowDescriptor)
{
var descriptor = iKnowDescriptor.GetDescriptor();
if (!_typeOrDescriptor2InfoMap.TryGetValue(descriptor, out infoForType) &&
!_typeSerializersMapping._typeOrDescriptor2Info.TryGetValue(descriptor, out infoForType))
{
infoForType = new InfoForType { Id = 0, Descriptor = descriptor };
}
}
else
{
if (!_typeOrDescriptor2InfoMap.TryGetValue(objType, out infoForType) &&
!_typeSerializersMapping._typeOrDescriptor2Info.TryGetValue(objType, out infoForType))
{
var descriptor = _typeSerializers.DescriptorOf(objType);
if (_typeOrDescriptor2InfoMap.TryGetValue(descriptor!, out infoForType))
{
_typeOrDescriptor2InfoMap[objType] = infoForType;
}
else if (_typeSerializersMapping._typeOrDescriptor2Info.TryGetValue(descriptor, out infoForType))
{
_typeSerializersMapping._typeOrDescriptor2Info[objType] = infoForType;
}
else
{
infoForType = new InfoForType { Id = 0, Descriptor = descriptor };
}
}
}
if (infoForType.Id == 0)
{
AddDescriptor(infoForType);
}
ref var actions = ref infoForType.Type2Actions.GetOrAddValueRef(objType);
if (!actions.KnownNewTypeDiscoverer)
{
actions.NewTypeDiscoverer = _typeSerializers.GetNewDescriptorSaver(infoForType.Descriptor, objType);
actions.KnownNewTypeDiscoverer = true;
}
var action = actions.NewTypeDiscoverer;
action?.Invoke(obj, this);
return this;
}
public void CommitNewDescriptors()
{
_typeSerializersMapping._id2DescriptorMap.AddRange(_id2InfoMap);
var ownerTypeOrDescriptor2Info = _typeSerializersMapping._typeOrDescriptor2Info;
foreach (var d2IPair in _typeOrDescriptor2InfoMap)
{
ownerTypeOrDescriptor2Info[d2IPair.Key] = d2IPair.Value;
}
}
public void StoreObject(AbstractBufferedWriter writer, object? obj)
{
if (obj == null)
{
writer.WriteUInt8(0);
return;
}
var infoForType = GetInfoFromObject(obj, out _);
StoreObjectCore(_typeSerializers, writer, obj, infoForType, this);
}
public void FinishNewDescriptors(AbstractBufferedWriter writer)
{
if (SomeTypeStored)
{
for (var i = (int)_id2InfoMap.Count - 1; i >= 0; i--)
{
writer.WriteVUInt32((uint)(i + _typeSerializersMapping._id2DescriptorMap.Count));
_typeSerializers.StoreDescriptor(_id2InfoMap[i].Descriptor, writer, Descriptor2Id);
}
writer.WriteUInt8(0);
}
}
public void StoreNewDescriptors(object obj)
{
StoreNewDescriptors(_writer, obj);
}
public InfoForType GetInfoFromObject(object obj, out TypeSerializers typeSerializers)
{
InfoForType infoForType;
if (obj is IKnowDescriptor iKnowDescriptor)
{
var descriptor = iKnowDescriptor.GetDescriptor();
if (!_typeOrDescriptor2InfoMap.TryGetValue(descriptor, out infoForType))
_typeSerializersMapping._typeOrDescriptor2Info.TryGetValue(descriptor, out infoForType);
}
else
{
var objType = obj.GetType();
if (!_typeOrDescriptor2InfoMap.TryGetValue(objType, out infoForType) && !_typeSerializersMapping._typeOrDescriptor2Info.TryGetValue(objType, out infoForType))
{
var descriptor = _typeSerializers.DescriptorOf(objType);
if (_typeOrDescriptor2InfoMap.TryGetValue(descriptor!, out infoForType))
{
_typeOrDescriptor2InfoMap[objType] = infoForType;
}
else if (_typeSerializersMapping._typeOrDescriptor2Info.TryGetValue(descriptor, out infoForType))
{
_typeSerializersMapping._typeOrDescriptor2Info[objType] = infoForType;
}
}
}
if (infoForType == null)
{
throw new InvalidOperationException(
$"Type {obj.GetType().FullName} was not registered using StoreNewDescriptors");
}
typeSerializers = _typeSerializers;
return infoForType;
}
public ISymmetricCipher GetSymmetricCipher() => _typeSerializers.GetSymmetricCipher();
}
public void StoreObject(AbstractBufferedWriter writer, object? obj)
{
if (obj == null)
{
writer.WriteUInt8(0);
return;
}
var infoForType = GetInfoFromObject(obj, out var typeSerializers);
StoreObjectCore(typeSerializers, writer, obj, infoForType, this);
}
static void StoreObjectCore(TypeSerializers typeSerializers, AbstractBufferedWriter writer, object obj, InfoForType infoForType, ITypeSerializersLightMapping mapping)
{
writer.WriteVUInt32((uint)infoForType.Id);
var objType = obj.GetType();
ref var actions = ref infoForType.Type2Actions.GetOrAddValueRef(objType);
if (!actions.KnownSimpleSaver)
{
actions.SimpleSaver = typeSerializers.GetSimpleSaver(infoForType.Descriptor, objType);
actions.KnownSimpleSaver = true;
}
var simpleSaver = actions.SimpleSaver;
if (simpleSaver != null)
{
simpleSaver(writer, obj);
return;
}
if (!actions.KnownComplexSaver)
{
actions.ComplexSaver = typeSerializers.GetComplexSaver(infoForType.Descriptor, objType);
actions.KnownComplexSaver = true;
}
var complexSaver = actions.ComplexSaver;
var ctx = new TypeBinarySerializerContext(mapping, writer, obj);
complexSaver(writer, ctx, obj);
}
class TypeBinarySerializerContext : ITypeBinarySerializerContext
{
readonly ITypeSerializersLightMapping _mapping;
readonly AbstractBufferedWriter _writer;
readonly Dictionary<object, uint> _backRefs = new Dictionary<object, uint>(ReferenceEqualityComparer<object>.Instance);
public TypeBinarySerializerContext(ITypeSerializersLightMapping mapping, AbstractBufferedWriter writer, object obj)
{
_mapping = mapping;
_writer = writer;
_backRefs.Add(obj, 0);
}
public void StoreObject(object? obj)
{
if (obj == null)
{
_writer.WriteUInt8(0);
return;
}
if (_backRefs.TryGetValue(obj, out var backRefId))
{
_writer.WriteUInt8(1);
_writer.WriteVUInt32(backRefId);
return;
}
_backRefs.Add(obj, (uint)_backRefs.Count);
var infoForType = _mapping.GetInfoFromObject(obj, out var typeSerializers);
_writer.WriteVUInt32((uint)infoForType.Id);
var objType = obj.GetType();
ref var actions = ref infoForType.Type2Actions.GetOrAddValueRef(objType);
if (!actions.KnownSimpleSaver)
{
actions.SimpleSaver = typeSerializers.GetSimpleSaver(infoForType.Descriptor, objType);
actions.KnownSimpleSaver = true;
}
var simpleSaver = actions.SimpleSaver;
if (simpleSaver != null)
{
simpleSaver(_writer, obj);
return;
}
if (!actions.KnownComplexSaver)
{
actions.ComplexSaver = typeSerializers.GetComplexSaver(infoForType.Descriptor, objType);
actions.KnownComplexSaver = true;
}
var complexSaver = actions.ComplexSaver;
complexSaver(_writer, this, obj);
}
public void StoreEncryptedString(EncryptedString value)
{
var writer = new ByteBufferWriter();
writer.WriteString(value);
var cipher = _mapping.GetSymmetricCipher();
var plain = writer.Data.AsSyncReadOnlySpan();
var encSize = cipher.CalcEncryptedSizeFor(plain);
var enc = new byte[encSize];
cipher.Encrypt(plain, enc);
_writer.WriteByteArray(enc);
}
}
public void FinishNewDescriptors(AbstractBufferedWriter writer)
{
}
public InfoForType GetInfoFromObject(object obj, out TypeSerializers typeSerializers)
{
InfoForType infoForType;
if (obj is IKnowDescriptor iKnowDescriptor)
{
var descriptor = iKnowDescriptor.GetDescriptor();
_typeOrDescriptor2Info.TryGetValue(descriptor, out infoForType);
}
else
{
var objType = obj.GetType();
if (!_typeOrDescriptor2Info.TryGetValue(objType, out infoForType))
{
var descriptor = _typeSerializers.DescriptorOf(objType);
if (_typeOrDescriptor2Info.TryGetValue(descriptor!, out infoForType))
{
_typeOrDescriptor2Info[objType] = infoForType;
}
}
}
typeSerializers = _typeSerializers;
if (infoForType == null)
{
throw new InvalidOperationException(
$"Type {obj.GetType().FullName} was not registered using StoreNewDescriptors");
}
return infoForType;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
[AddComponentMenu("NGUI/NData/ItemsSource Binding")]
public class NguiItemsSourceBinding : NguiBinding
{
private NguiListItemTemplate _itemTemplate;
protected EZData.Collection _collection;
protected bool _isCollectionSelecting = false;
private UITable _uiTable = null;
private UIGrid _uiGrid = null;
public override void Awake()
{
base.Awake();
_uiTable = GetComponent<UITable>();
_uiGrid = GetComponent<UIGrid>();
_itemTemplate = gameObject.GetComponent<NguiListItemTemplate>();
}
protected override void Unbind()
{
base.Unbind();
if (_collection != null)
{
_collection.OnItemInsert -= OnItemInsert;
_collection.OnItemRemove -= OnItemRemove;
_collection.OnItemsClear -= OnItemsClear;
_collection.OnSelectionChange -= OnCollectionSelectionChange;
_collection = null;
OnItemsClear();
}
}
protected override void Bind()
{
base.Bind();
var context = GetContext(Path);
if (context == null)
return;
_collection = context.FindCollection(Path, this);
if (_collection == null)
return;
_collection.OnItemInsert += OnItemInsert;
_collection.OnItemRemove += OnItemRemove;
_collection.OnItemsClear += OnItemsClear;
_collection.OnSelectionChange += OnCollectionSelectionChange;
for (var i = 0; i < _collection.ItemsCount; ++i)
{
OnItemInsert(i, _collection.GetBaseItem(i));
}
OnCollectionSelectionChange();
}
protected virtual void OnItemInsert(int position, EZData.Context item)
{
GameObject itemObject = null;
if (_itemTemplate != null)
{
itemObject = _itemTemplate.Instantiate(item, position);
itemObject.name = string.Format("{0}", position);
for (var i = 0; i < transform.childCount; ++i)
{
var child = transform.GetChild(i).gameObject;
int childNumber;
if (int.TryParse(child.name, out childNumber) && childNumber >= position)
{
child.name = string.Format("{0}", childNumber + 1);
}
}
itemObject.transform.parent = gameObject.transform;
itemObject.transform.localScale = Vector3.one;
itemObject.transform.localPosition = Vector3.back;
}
else
{
if (position < transform.childCount)
{
itemObject = transform.GetChild(position).gameObject;
var itemData = itemObject.GetComponent<NguiItemDataContext>();
if (itemData != null)
{
itemData.SetContext(item);
itemData.SetIndex(position);
}
}
}
if (itemObject != null)
{
foreach(var dragObject in itemObject.GetComponentsInChildren<UIDragObject>())
{
if (dragObject.target == null)
dragObject.target = gameObject.transform;
}
foreach(var dragObject in itemObject.GetComponents<UIDragObject>())
{
if (dragObject.target == null)
dragObject.target = gameObject.transform;
}
var parentVisibility = NguiUtils.GetComponentInParentsAs<IVisibilityBinding>(gameObject);
foreach(var visibility in NguiUtils.GetComponentsInChildrenAs<IVisibilityBinding>(itemObject))
{
visibility.InvalidateParent();
}
var visible = parentVisibility == null ? true : parentVisibility.Visible;
NguiUtils.SetVisible(itemObject, visible);
RepositionContent();
}
}
protected virtual void OnItemRemove(int position)
{
if (_itemTemplate == null)
return;
for (var i = 0; i < transform.childCount; ++i)
{
var child = transform.GetChild(i).gameObject;
int childNumber;
if (int.TryParse(child.name, out childNumber))
{
if (childNumber == position)
{
GameObject.DestroyImmediate(child);
break;
}
}
}
for (var i = 0; i < transform.childCount; ++i)
{
var child = transform.GetChild(i).gameObject;
int childNumber;
if (int.TryParse(child.name, out childNumber))
{
if (childNumber > position)
{
child.name = string.Format("{0}", childNumber - 1);
}
}
}
RepositionContent();
}
private void RepositionContent()
{
if (_uiTable != null)
{
var parentLookup = NguiUtils.GetComponentInParentsExcluding<UITable>(
gameObject);
if (parentLookup == null)
_uiTable.repositionNow = true;
else
_uiTable.Reposition();
}
if (_uiGrid != null)
{
var parentLookup = NguiUtils.GetComponentInParentsExcluding<UITable>(
gameObject);
if (parentLookup == null)
_uiGrid.repositionNow = true;
else
_uiGrid.Reposition();
}
var parent = NguiUtils.GetComponentInParentsExcluding<UITable>(gameObject);
while (parent != null)
{
var parentLookup = NguiUtils.GetComponentInParentsExcluding<UITable>(
parent.gameObject);
if (parentLookup == null)
parent.repositionNow = true;
else
parent.Reposition();
parent = parentLookup;
}
}
protected virtual void OnItemsClear()
{
if (_itemTemplate == null)
return;
while(transform.childCount > 0)
{
GameObject.DestroyImmediate(transform.GetChild(0).gameObject);
}
RepositionContent();
}
public void OnSelectionChange(GameObject selectedObject)
{
if (_collection != null && !_isCollectionSelecting)
{
_isCollectionSelecting = true;
for (var i = 0; i < transform.childCount; ++i)
{
var child = transform.GetChild(i).gameObject;
if (selectedObject != child)
continue;
int childNumber;
if (int.TryParse(child.name, out childNumber))
{
_collection.SelectItem(childNumber);
break;
}
}
_isCollectionSelecting = false;
}
}
protected virtual void OnCollectionSelectionChange()
{
for (var i = 0; i < transform.childCount; ++i)
{
var child = transform.GetChild(i).gameObject;
int childNumber;
if (int.TryParse(child.name, out childNumber))
{
var itemData = child.GetComponent<NguiItemDataContext>();
if (itemData != null)
itemData.SetSelected(childNumber == _collection.SelectedIndex);
}
}
}
}
| |
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Abp.AspNetCore.App.Controllers;
using Abp.AspNetCore.App.Models;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Events.Bus;
using Abp.Events.Bus.Exceptions;
using Abp.Localization;
using Abp.UI;
using Abp.Web.Models;
using Microsoft.AspNetCore.Localization;
using NSubstitute;
using Shouldly;
using Xunit;
namespace Abp.AspNetCore.Tests
{
public class SimpleTestControllerTests : AppTestBase
{
[Fact]
public void Should_Resolve_Controller()
{
ServiceProvider.GetService<SimpleTestController>().ShouldNotBeNull();
}
[Fact]
public async Task Should_Return_Content()
{
// Act
var response = await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.SimpleContent)
)
);
// Assert
response.ShouldBe("Hello world...");
}
[Fact]
public async Task Should_Wrap_Json_By_Default()
{
// Act
var response = await GetResponseAsObjectAsync<AjaxResponse<SimpleViewModel>>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.SimpleJson)
)
);
//Assert
response.Result.StrValue.ShouldBe("Forty Two");
response.Result.IntValue.ShouldBe(42);
}
[Theory]
[InlineData(true, "This is a user friendly exception message")]
[InlineData(false, "This is an exception message")]
public async Task Should_Wrap_Json_Exception_By_Default(bool userFriendly, string message)
{
//Arrange
var exceptionEventRaised = false;
Resolve<IEventBus>().Register<AbpHandledExceptionData>(data =>
{
exceptionEventRaised = true;
data.Exception.ShouldNotBeNull();
data.Exception.Message.ShouldBe(message);
});
// Act
var response = await GetResponseAsObjectAsync<AjaxResponse<SimpleViewModel>>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.SimpleJsonException),
new
{
message,
userFriendly
}),
HttpStatusCode.InternalServerError
);
//Assert
response.Error.ShouldNotBeNull();
if (userFriendly)
{
response.Error.Message.ShouldBe(message);
}
else
{
response.Error.Message.ShouldNotBe(message);
}
exceptionEventRaised.ShouldBeTrue();
}
[Fact]
public async Task Should_Not_Wrap_Json_Exception_If_Requested()
{
//Act & Assert
await Assert.ThrowsAsync<UserFriendlyException>(async () =>
{
await GetResponseAsObjectAsync<AjaxResponse<SimpleViewModel>>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.SimpleJsonExceptionDownWrap)
));
});
}
[Fact]
public async Task Should_Not_Wrap_Json_If_DontWrap_Declared()
{
// Act
var response = await GetResponseAsObjectAsync<SimpleViewModel>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.SimpleJsonDontWrap)
));
//Assert
response.StrValue.ShouldBe("Forty Two");
response.IntValue.ShouldBe(42);
}
[Fact]
public async Task Should_Wrap_Void_Methods()
{
// Act
var response = await GetResponseAsObjectAsync<AjaxResponse>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetVoidTest)
));
response.Success.ShouldBeTrue();
response.Result.ShouldBeNull();
}
[Fact]
public async Task Should_Not_Wrap_Void_Methods_If_Requested()
{
// Act
var response = await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetVoidTestDontWrap)
));
response.ShouldBeNullOrEmpty();
}
[Fact]
public async Task Should_Not_Wrap_ActionResult()
{
// Act
var response = await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetActionResultTest)
));
//Assert
response.ShouldBe("GetActionResultTest-Result");
}
[Fact]
public async Task Should_Not_Wrap_Async_ActionResult()
{
// Act
var response = await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetActionResultTestAsync)
));
//Assert
response.ShouldBe("GetActionResultTestAsync-Result");
}
[Fact]
public async Task Should_Wrap_Async_Void_On_Exception()
{
// Act
var response = await GetResponseAsObjectAsync<AjaxResponse>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetVoidExceptionTestAsync)
), HttpStatusCode.InternalServerError);
response.Error.ShouldNotBeNull();
response.Error.Message.ShouldBe("GetVoidExceptionTestAsync-Exception");
response.Result.ShouldBeNull();
}
[Fact]
public async Task Should_Not_Wrap_Async_ActionResult_On_Exception()
{
// Act
(await Assert.ThrowsAsync<UserFriendlyException>(async () =>
{
await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetActionResultExceptionTestAsync)
), HttpStatusCode.InternalServerError);
})).Message.ShouldBe("GetActionResultExceptionTestAsync-Exception");
}
[Fact]
public async Task AbpLocalizationHeaderRequestCultureProvider_Test()
{
//Arrange
Client.DefaultRequestHeaders.Add(CookieRequestCultureProvider.DefaultCookieName, "c=it|uic=it");
var culture = await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetCurrentCultureNameTest)
));
culture.ShouldBe("it");
}
}
}
| |
//===--- PerformanceTests.cs ---------------------------------------------------------===//
//
// Copyright (c) 2015 Joe Duffy. All rights reserved.
//
// This file is distributed under the MIT License. See LICENSE.md for details.
//
//===----------------------------------------------------------------------===//
using System;
using System.Collections.Generic;
using System.Linq;
class PerformanceTests
{
private const int ElementsCount = 10000;
/// <summary>
/// the JIT compiler eliminates bounds check for some standard loops i.e. (int j = 0; j < array.Length; j++) { sum += array[j] }
/// the purpose of this test is to show how big the difference is because of that
/// and hopefully in the future prove that we gained similar performance
/// </summary>
public bool TestPerfOfStandardBoundariesForLoop(Tester tester)
{
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount),
array => {
int sum = 0;
for (int j = 0; j < array.Length; j++) {
sum += array[j];
}
return sum;
});
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount).Slice(),
slice => {
int sum = 0;
for (int j = 0; j < slice.Length; j++) {
sum += slice[j];
}
return sum;
});
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount).ToList(),
list => {
int sum = 0;
for (int j = 0; j < list.Count; j++) {
sum += list[j];
}
return sum;
});
return true;
}
/// <summary>
/// the JIT compiler does not eliminate bounds check for nonstandard loops
/// i.e. (int j = 0; j < array.Length / 2; j++) { sum += array[j + 1] }
/// the purpose of this test is to show how fast Slice is when compared
/// to array and list that do not get any extra support from CLR
/// </summary>
public bool TestPerfOfNonStandardBoundariesForLoop(Tester tester)
{
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount),
array => {
int sum = 0;
for (int j = 0; j < array.Length / 2; j++) {
sum += array[j * 2];
}
return sum;
});
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount).Slice(),
slice => {
int sum = 0;
for (int j = 0; j < slice.Length / 2; j++) {
sum += slice[j * 2];
}
return sum;
});
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount).ToList(),
list => {
int sum = 0;
for (int j = 0; j < list.Count / 2; j++) {
sum += list[j * 2];
}
return sum;
});
return true;
}
/// <summary>
/// the compiler optimizes foreach loops for:
/// 1) built in collections like arrays
/// 2) these collections that do have public method "GetEnumerator that takes no parameters and returns a type that has two members:
/// a) a method MoveNext that takes no parameters and return a Boolean, and
/// b) a property Current with a getter that returns an Object"
/// source: http://blogs.msdn.com/b/kcwalina/archive/2007/07/18/ducknotation.aspx
/// the gain is that is does not call interface members on structures which is expensive
/// and does not put it into try/finally block with Dispose in the finally
/// the purpose of this test is to show how big the difference is because of that
/// and hopefully in the future prove that we gained similar performance
/// </summary>
public bool TestPerfOfForEachLoop(Tester tester)
{
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount),
array => {
int sum = 0;
foreach (var number in array) {
sum += number;
}
return sum;
});
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount).Slice(),
slice => {
int sum = 0;
foreach (var number in slice) {
sum += number;
}
return sum;
});
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount).ToList(),
list => {
int sum = 0;
foreach (var number in list) {
sum += number;
}
return sum;
});
return true;
}
/// <summary>
/// the compiler does not optimize foreach loops for collections when they are used via interfaces
/// it might call interface members on structures which is expensive
/// and it does put it into try/finally block with Dispose in the finally
/// the purpose of this test is to show how big the difference is because of that
/// and hopefully in the future prove that we gained similar performance
/// </summary>
public bool TestPerfOfForEachLoopWhenUsedViaInterface(Tester tester)
{
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount),
Sum);
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount).Slice(),
slice => Sum(slice));
ExecuteAndMeasure(
GenerateRandomNumbers(ElementsCount).ToList(),
Sum);
return true;
}
private static int ExecuteAndMeasure<T>(T data, Func<T, int> test)
{
Tester.CleanUpMemory();
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
int sum = 0;
for (int i = 0; i < ElementsCount; i++) {
sum += test.Invoke(data);;
}
stopwatch.Stop();
Console.WriteLine(" - {0}: {1}", new string((typeof(T).Name + " ").Take(7).ToArray()), stopwatch.Elapsed);
return sum;
}
/// <summary>
/// we generate new set of data every time just to make sure that each of them is cached in CPU cached in similar way
/// </summary>
private static int[] GenerateRandomNumbers(int count)
{
var ints = new int[count];
var random = new Random(1234);
for (int i = 0; i < ints.Length; i++) {
ints[i] = random.Next();
}
return ints;
}
/// <summary>
/// iterates explicit on IEnumerable instead of calling .Sum() extension method,
/// which implementation might try to cast it to array etc. or use other tricks
/// </summary>
private static int Sum(IEnumerable<int> numbers)
{
int sum = 0;
foreach (var number in numbers) {
sum += number;
}
return sum;
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.PointOfService;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace PosPrinterSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario2_ErrorHandling : Page
{
private MainPage rootPage;
PosPrinter printer = null;
ClaimedPosPrinter claimedPrinter = null;
bool IsAnImportantTransaction = true;
public Scenario2_ErrorHandling()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
ResetTheScenarioState();
}
/// <summary>
/// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame
/// </summary>
/// <param name="e">Provides data for the OnNavigatingFrom callback that can be used to cancel a navigation
/// request from origination</param>
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
ResetTheScenarioState();
}
private void ResetTheScenarioState()
{
//Remove releasedevicerequested handler and dispose claimed printer object.
if (claimedPrinter != null)
{
claimedPrinter.ReleaseDeviceRequested -= ClaimedPrinter_ReleaseDeviceRequested;
claimedPrinter.Dispose();
claimedPrinter = null;
}
printer = null;
}
/// <summary>
/// Creates multiple tasks, first to find a receipt printer, then to claim the printer and then to enable and add releasedevicerequested event handler.
/// </summary>
async void FindClaimEnable_Click(object sender, RoutedEventArgs e)
{
if (await FindReceiptPrinter())
{
if (await ClaimPrinter())
{
await EnableAsync();
}
}
}
async void PrintLine_Click(object sender, RoutedEventArgs e)
{
await PrintLineAndCheckForErrors();
}
/// <summary>
/// Prints the line that is in the textbox. Then checks for any error conditions and reports the same to user.
/// </summary>
private async Task<bool> PrintLineAndCheckForErrors()
{
if (!IsPrinterClaimed())
{
return false;
}
ReceiptPrintJob job = claimedPrinter.Receipt.CreateJob();
job.PrintLine(txtPrintLine.Text);
if (await job.ExecuteAsync())
{
rootPage.NotifyUser("Printed line", NotifyType.StatusMessage);
return true;
}
else
{
if (claimedPrinter.Receipt.IsCartridgeEmpty)
{
rootPage.NotifyUser("Printer is out of ink. Please replace cartridge.", NotifyType.StatusMessage);
}
else if (claimedPrinter.Receipt.IsCartridgeRemoved)
{
rootPage.NotifyUser("Printer cartridge is missing. Please replace cartridge.", NotifyType.StatusMessage);
}
else if (claimedPrinter.Receipt.IsCoverOpen)
{
rootPage.NotifyUser("Printer cover is open. Please close it.", NotifyType.StatusMessage);
}
else if (claimedPrinter.Receipt.IsHeadCleaning)
{
rootPage.NotifyUser("Printer is currently cleaning the cartridge. Please wait until cleaning has completed.", NotifyType.StatusMessage);
}
else if (claimedPrinter.Receipt.IsPaperEmpty)
{
rootPage.NotifyUser("Printer is out of paper. Please insert a new roll.", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Was not able to print line", NotifyType.StatusMessage);
}
}
return false;
}
private void EndScenario_Click(object sender, RoutedEventArgs e)
{
ResetTheScenarioState();
rootPage.NotifyUser("Disconnected Printer", NotifyType.StatusMessage);
}
/// <summary>
/// Actual claim method task that claims the printer asynchronously
/// </summary>
private async Task<bool> ClaimPrinter()
{
if (claimedPrinter == null)
{
claimedPrinter = await printer.ClaimPrinterAsync();
if (claimedPrinter != null)
{
rootPage.NotifyUser("Claimed Printer", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Claim Printer failed", NotifyType.ErrorMessage);
return false;
}
}
return true;
}
/// <summary>
/// Enable the claimed printer.
/// </summary>
private async Task<bool> EnableAsync()
{
if (claimedPrinter == null)
{
claimedPrinter.ReleaseDeviceRequested += ClaimedPrinter_ReleaseDeviceRequested;
rootPage.NotifyUser("No Claimed Printer to enable", NotifyType.ErrorMessage);
return false;
}
if (!await claimedPrinter.EnableAsync())
{
rootPage.NotifyUser("Could not enable printer", NotifyType.ErrorMessage);
return false;
}
rootPage.NotifyUser("Enabled Printer", NotifyType.StatusMessage);
return true;
}
/// <summary>
/// Check to make sure we still have claim on printer
/// </summary>
private bool IsPrinterClaimed()
{
if (printer == null)
{
rootPage.NotifyUser("Need to find printer first", NotifyType.ErrorMessage);
return false;
}
if (claimedPrinter == null)
{
rootPage.NotifyUser("No claimed printer.", NotifyType.ErrorMessage);
return false;
}
if (claimedPrinter.Receipt == null)
{
rootPage.NotifyUser("No receipt printer object in claimed printer.", NotifyType.ErrorMessage);
return false;
}
return true;
}
/// <summary>
/// GetDeviceSelector method returns the string needed to identify a PosPrinter. This is passed to FindAllAsync method to get the list of devices currently available and we connect the first device.
/// </summary>
private async Task<bool> FindReceiptPrinter()
{
if (printer == null)
{
rootPage.NotifyUser("Finding printer", NotifyType.StatusMessage);
DeviceInformationCollection deviceCollection = await DeviceInformation.FindAllAsync(PosPrinter.GetDeviceSelector());
if (deviceCollection != null && deviceCollection.Count > 0)
{
DeviceInformation deviceInfo = deviceCollection[0];
printer = await PosPrinter.FromIdAsync(deviceInfo.Id);
if (printer != null)
{
if (printer.Capabilities.Receipt.IsPrinterPresent)
{
rootPage.NotifyUser("Got Printer with Device Id : " + printer.DeviceId, NotifyType.StatusMessage);
return true;
}
}
else
{
rootPage.NotifyUser("No Printer found", NotifyType.ErrorMessage);
return false;
}
}
else
{
rootPage.NotifyUser("No devices returned by FindAllAsync.", NotifyType.ErrorMessage);
return false;
}
}
return true;
}
async void ClaimedPrinter_ReleaseDeviceRequested(ClaimedPosPrinter sender, PosPrinterReleaseDeviceRequestedEventArgs args)
{
if (IsAnImportantTransaction)
{
await sender.RetainDeviceAsync();
}
else
{
ResetTheScenarioState();
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/6/2009 10:14:34 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace DotSpatial.Data
{
public class BgdRaster<T> : Raster<T> where T : IComparable<T>, IEquatable<T>
{
#region Constructors
/// <summary>
/// A BgdRaster in created this way probably expects to open a file using the "Open" method,
/// which allows for progress handlers or other things to be set before what might be a
/// time consuming read-value process.
/// </summary>
public BgdRaster()
{
}
/// <summary>
/// Creates a new instance of a BGD raster, attempting to store the entire structure in memory if possible.
/// </summary>
/// <param name="numRows"></param>
/// <param name="numColumns"></param>
public BgdRaster(int numRows, int numColumns)
: base(numRows, numColumns)
{
}
/// <summary>
/// This creates a new BGD raster.
/// </summary>
/// <param name="fileName"></param>
/// <param name="numRows"></param>
/// <param name="numColumns"></param>
public BgdRaster(string fileName, int numRows, int numColumns)
: base(numRows, numColumns)
{
if (File.Exists(fileName)) File.Delete(fileName);
base.Filename = fileName;
base.NumRowsInFile = numRows;
base.NumColumnsInFile = numColumns;
//base.IsInRam = false;
WriteHeader(fileName);
}
#endregion
#region Methods
/// <summary>
/// This Method should be overrridden by classes, and provides the primary ability.
/// </summary>
/// <param name="xOff">The horizontal offset of the area to read values from.</param>
/// <param name="yOff">The vertical offset of the window to read values from.</param>
/// <param name="sizeX">The number of values to read into the buffer.</param>
/// <param name="sizeY">The vertical size of the window to read into the buffer.</param>
/// <returns>A jagged array of type T.</returns>
public override T[][] ReadRaster(int xOff, int yOff, int sizeX, int sizeY)
{
FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read, NumColumns * ByteSize);
ProgressMeter pm = new ProgressMeter(ProgressHandler,
DataStrings.ReadingValuesFrom_S.Replace("%S", Filename), NumRows);
fs.Seek(HeaderSize, SeekOrigin.Begin);
// Position the binary reader at the top of the "window"
fs.Seek(yOff * NumColumnsInFile * ByteSize, SeekOrigin.Current);
BinaryReader br = new BinaryReader(fs);
T[][] result = new T[NumRows][];
int endX = xOff + sizeX;
for (int row = 0; row < sizeY; row++)
{
result[row] = new T[sizeX];
// Position the binary reader at the beginning of the window
fs.Seek(ByteSize * xOff, SeekOrigin.Current);
byte[] values = br.ReadBytes(sizeX * ByteSize);
Buffer.BlockCopy(values, 0, result[row], 0, ByteSize * sizeX);
pm.CurrentValue = row;
fs.Seek(ByteSize * (NumColumnsInFile - endX), SeekOrigin.Current);
}
br.Close();
return result;
}
/// <summary>
/// Most reading is optimized to read in a block at a time and process it. This method is designed
/// for seeking through the file. It should work faster than the buffered methods in cases where
/// an unusually arranged collection of values are required. Sorting the list before calling
/// this should significantly improve performance.
/// </summary>
/// <param name="indices">A list or array of long values that are (Row * NumRowsInFile + Column)</param>
public override List<T> GetValuesT(IEnumerable<long> indices)
{
if (IsInRam) return base.GetValuesT(indices);
#if DEBUG
var sw = new Stopwatch();
sw.Start();
#endif
var result = new List<T>();
using (var fs = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read, ByteSize))
{
fs.Seek(HeaderSize, SeekOrigin.Begin);
using (var br = new BinaryReader(fs))
{
foreach (long index in indices)
{
var offset = HeaderSize + index*ByteSize;
// Position the binary reader at the top of the "window"
fs.Seek(offset, SeekOrigin.Begin);
var values = br.ReadBytes(ByteSize);
var x = new T[1];
Buffer.BlockCopy(values, 0, x, 0, ByteSize);
result.Add(x[0]);
}
}
}
#if DEBUG
sw.Stop();
Debug.WriteLine("Time to read values from file:" + sw.ElapsedMilliseconds);
#endif
return result;
}
/// <summary>
/// Writes the bgd content from the specified jagged array of values to the file.
/// </summary>
/// <param name="buffer">The data</param>
/// <param name="xOff">The horizontal offset</param>
/// <param name="yOff">The vertical offset</param>
/// <param name="xSize">The number of values to write horizontally</param>
/// <param name="ySize">The number of values to write vertically</param>
public override void WriteRaster(T[][] buffer, int xOff, int yOff, int xSize, int ySize)
{
var pm = new ProgressMeter(ProgressHandler,
DataStrings.ReadingValuesFrom_S.Replace("%S", Filename), NumRowsInFile) { StartValue = yOff };
using (var fs = new FileStream(Filename, FileMode.Open, FileAccess.Write, FileShare.Write,
NumColumns*ByteSize))
{
fs.Seek(HeaderSize, SeekOrigin.Begin);
// Position the binary reader at the top of the "window"
long offset = yOff*(long) NumColumnsInFile*ByteSize;
fs.Seek(offset, SeekOrigin.Current);
using (var br = new BinaryWriter(fs))
{
int endX = xOff + xSize;
for (int row = 0; row < ySize; row++)
{
// Position the binary reader at the beginning of the window
fs.Seek(ByteSize*xOff, SeekOrigin.Current);
byte[] values = new byte[xSize*ByteSize];
Buffer.BlockCopy(buffer[row], 0, values, 0, xSize*ByteSize);
br.Write(values);
pm.CurrentValue = row + yOff;
fs.Seek(ByteSize*(NumColumnsInFile - endX), SeekOrigin.Current);
}
}
}
}
/// <summary>
/// Copies the raster header, and if copyValues is true, the values to the specified file </summary>
/// <param name="fileName">The full path of the file to copy content to to</param>
/// <param name="copyValues">Boolean, true if this should copy values as well as just header information</param>
public override void Copy(string fileName, bool copyValues)
{
if (copyValues)
{
Write(fileName);
}
else
{
WriteHeader(fileName);
T[] blank = new T[NumColumnsInFile];
T val = (T)Convert.ChangeType(NoDataValue, typeof(T));
for (int col = 0; col < NumColumnsInFile; col++)
{
blank[col] = val;
}
for (int row = 0; row < NumRowsInFile; row++)
{
WriteRow(blank, row);
}
}
}
/// <summary>
/// Opens the specified file
/// </summary>
public override void Open()
{
NoDataValue = Global.ToDouble(Global.MinimumValue<T>()); // Sets it to the appropriate minimum for the int datatype
ReadHeader(Filename);
StartRow = 0;
EndRow = NumRows - 1;
StartColumn = 0;
EndColumn = NumColumns - 1;
NumColumnsInFile = NumColumns;
NumRowsInFile = NumRows;
NumValueCells = 0;
Value = new ValueGrid<T>(this);
DataType = typeof(T);
if (base.NumColumnsInFile * base.NumRowsInFile < 64000000)
{
base.IsInRam = true;
Data = ReadRaster();
base.GetStatistics();
}
else
{
base.IsInRam = false;
// Don't read in any data at this point. Let the user use ReadRaster for specific blocks.
}
}
/// <summary>
/// Saves the content from this file using the current fileName and header information
/// </summary>
public override void Save()
{
Write(Filename);
}
/// <summary>
/// If no file exists, this writes the header and no-data values. If a file exists, it will assume
/// that data already has been filled in the file and will attempt to insert the data values
/// as a window into the file. If you want to create a copy of the file and values, just use
/// System.IO.File.Copy, it almost certainly would be much more optimized.
/// </summary>
private void Write(string fileName)
{
ProgressMeter pm = new ProgressMeter(ProgressHandler, "Writing values to " + Filename, NumRows);
long expectedByteCount = NumRows * NumColumns * ByteSize;
if (expectedByteCount < 1000000) pm.StepPercent = 5;
if (expectedByteCount < 5000000) pm.StepPercent = 10;
if (expectedByteCount < 100000) pm.StepPercent = 50;
if (File.Exists(fileName))
{
FileInfo fi = new FileInfo(Filename);
// if the following test fails, then the target raster doesn't fit the bill for pasting into, so clear it and write a new one.
if (fi.Length == HeaderSize + ByteSize * NumColumnsInFile * NumRowsInFile)
{
WriteHeader(fileName);
WriteRaster(Data);
return;
}
// If we got here, either the file didn't exist or didn't match the specifications correctly, so write a new one.
Debug.WriteLine("The size of the file was " + fi.Length + " which didn't match the expected " +
HeaderSize + ByteSize * NumColumnsInFile * NumRowsInFile);
}
if (File.Exists(Filename)) File.Delete(Filename);
WriteHeader(fileName);
// Open as append and it will automatically skip the header for us.
using (var bw =new BinaryWriter(new FileStream(Filename, FileMode.Append, FileAccess.Write, FileShare.None,ByteSize*NumColumnsInFile)))
{
// the row and column counters here are relative to the whole file, not just the window that is currently in memory.
pm.EndValue = NumRowsInFile;
for (int row = 0; row < NumRowsInFile; row++)
{
byte[] rawBytes = new byte[NumColumnsInFile*ByteSize];
T[] nd = new T[1];
nd[0] = (T) Convert.ChangeType(NoDataValue, typeof (T));
Buffer.BlockCopy(Data[row - StartRow], 0, rawBytes, StartColumn*ByteSize, NumColumns*ByteSize);
for (int col = 0; col < StartColumn; col++)
{
Buffer.BlockCopy(nd, 0, rawBytes, col*ByteSize, ByteSize);
}
for (int col = EndColumn + 1; col < NumColumnsInFile; col++)
{
Buffer.BlockCopy(nd, 0, rawBytes, col*ByteSize, ByteSize);
}
bw.Write(rawBytes);
pm.CurrentValue = row;
}
}
pm.Reset();
}
/// <summary>
/// Writes the header to the fileName
/// </summary>
public override void WriteHeader()
{
WriteHeader(Filename);
}
/// <summary>
/// The string fileName where this will begin to write data by clearing the existing file
/// </summary>
public void WriteHeader(string fileName)
{
var dt = GetRasterDataType();
if (dt == RasterDataType.INVALID)
{
throw new Exception("Invalid DataType");
}
using (var bw = new BinaryWriter(new FileStream(fileName, FileMode.OpenOrCreate)))
{
bw.Write(NumColumnsInFile);
bw.Write(NumRowsInFile);
bw.Write(CellWidth);
bw.Write(CellHeight);
bw.Write(Xllcenter);
bw.Write(Yllcenter);
bw.Write((int) dt);
var nd = new byte[ByteSize];
var nds = new[] {(T) Convert.ChangeType(NoDataValue, typeof (T))};
Buffer.BlockCopy(nds, 0, nd, 0, ByteSize);
bw.Write(nd);
// These are each 256 bytes because they are ASCII encoded, not the standard DotNet Unicode
byte[] proj = new byte[255];
if (Projection != null)
{
byte[] temp = Encoding.Default.GetBytes(Projection.ToProj4String());
int len = Math.Min(temp.Length, 255);
for (int i = 0; i < len; i++)
{
proj[i] = temp[i];
}
string prj = Path.ChangeExtension(Filename, ".prj");
if (File.Exists(prj))
{
File.Delete(prj);
}
var fi = new FileInfo(prj);
using (var tw = fi.CreateText())
{
tw.WriteLine(Projection.ToEsriString());
}
}
bw.Write(proj);
byte[] note = new byte[255];
if (Notes != null)
{
byte[] temp = Encoding.Default.GetBytes(Notes);
int len = Math.Min(temp.Length, 255);
for (int i = 0; i < len; i++)
{
note[i] = temp[i];
}
}
bw.Write(note);
}
}
private RasterDataType GetRasterDataType()
{
if (DataType == typeof(byte))
return RasterDataType.BYTE;
if (DataType == typeof(short))
return RasterDataType.SHORT;
if (DataType == typeof (int))
return RasterDataType.INTEGER;
if (DataType == typeof(long))
return RasterDataType.LONG;
if (DataType == typeof(float))
return RasterDataType.SINGLE;
if (DataType == typeof(double))
return RasterDataType.DOUBLE;
if (DataType == typeof(sbyte))
return RasterDataType.SBYTE;
if (DataType == typeof(ushort))
return RasterDataType.USHORT;
if (DataType == typeof(uint))
return RasterDataType.UINTEGER;
if (DataType == typeof(ulong))
return RasterDataType.ULONG;
if (DataType == typeof(bool))
return RasterDataType.BOOL;
return RasterDataType.INVALID;
}
#endregion
#region Properties
/// <summary>
/// Gets the size of the header. There is one no-data value in the header.
/// </summary>
public virtual int HeaderSize
{
get { return 554 + ByteSize; }
}
/// <summary>
/// Writes the header, regardless of which subtype of binary raster this is written for
/// </summary>
/// <param name="fileName">The string fileName specifying what file to load</param>
public void ReadHeader(string fileName)
{
using (var br = new BinaryReader(new FileStream(fileName, FileMode.Open)))
{
StartColumn = 0;
NumColumns = br.ReadInt32();
NumColumnsInFile = NumColumns;
EndColumn = NumColumns - 1;
StartRow = 0;
NumRows = br.ReadInt32();
NumRowsInFile = NumRows;
EndRow = NumRows - 1;
Bounds = new RasterBounds(NumRows, NumColumns, new[] {0.0, 1.0, 0.0, NumRows, 0.0, -1.0});
CellWidth = br.ReadDouble();
Bounds.AffineCoefficients[5] = -br.ReadDouble(); // dy
Xllcenter = br.ReadDouble();
Yllcenter = br.ReadDouble();
br.ReadInt32(); // Read RasterDataType only to skip it since we know the type already.
byte[] noDataBytes = br.ReadBytes(ByteSize);
var nd = new T[1];
Buffer.BlockCopy(noDataBytes, 0, nd, 0, ByteSize);
NoDataValue = Global.ToDouble(nd[0]);
string proj = Encoding.Default.GetString(br.ReadBytes(255)).Replace('\0', ' ').Trim();
ProjectionString = proj;
Notes = Encoding.Default.GetString(br.ReadBytes(255)).Replace('\0', ' ').Trim();
if (Notes.Length == 0) Notes = null;
}
string prj = Path.ChangeExtension(Filename, ".prj");
if (File.Exists(prj))
{
using (var sr = new StreamReader(prj))
{
ProjectionString = sr.ReadToEnd();
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Runtime;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using Internal.Reflection.Augments;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
namespace System
{
// WARNING: Bartok hard-codes offsets to the delegate fields, so it's notion of where fields are may
// differ from the runtime's notion. Bartok honors sequential and explicit layout directives, so I've
// ordered the fields in such a way as to match the runtime's layout and then just tacked on this
// sequential layout directive so that Bartok matches it.
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("Target method(s) = {GetTargetMethodsDescriptionForDebugger()}")]
public abstract partial class Delegate : ICloneable, ISerializable
{
// This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a
// "protected-and-internal" rather than "internal" but C# has no keyword for the former.
internal Delegate()
{
// ! Do NOT put any code here. Delegate constructers are not guaranteed to be executed.
}
// V1 API: Create closed instance delegates. Method name matching is case sensitive.
protected Delegate(Object target, String method)
{
// This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an
// overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal
// implementation of CreateDelegate below, and does not invoke this constructor.
// The constructor is just for API compatibility with the public contract of the Delegate class.
throw new PlatformNotSupportedException();
}
// V1 API: Create open static delegates. Method name matching is case insensitive.
protected Delegate(Type target, String method)
{
// This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an
// overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal
// implementation of CreateDelegate below, and does not invoke this constructor.
// The constructor is just for API compatibility with the public contract of the Delegate class.
throw new PlatformNotSupportedException();
}
// New Delegate Implementation
protected internal object m_firstParameter;
protected internal object m_helperObject;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")]
protected internal IntPtr m_extraFunctionPointerOrData;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")]
protected internal IntPtr m_functionPointer;
[ThreadStatic]
protected static string s_DefaultValueString;
// WARNING: These constants are also declared in System.Private.TypeLoader\Internal\Runtime\TypeLoader\CallConverterThunk.cs
// Do not change their values without updating the values in the calling convention converter component
protected const int MulticastThunk = 0;
protected const int ClosedStaticThunk = 1;
protected const int OpenStaticThunk = 2;
protected const int ClosedInstanceThunkOverGenericMethod = 3; // This may not exist
protected const int DelegateInvokeThunk = 4;
protected const int OpenInstanceThunk = 5; // This may not exist
protected const int ReversePinvokeThunk = 6; // This may not exist
protected const int ObjectArrayThunk = 7; // This may not exist
//
// If the thunk does not exist, the function will return IntPtr.Zero.
protected virtual IntPtr GetThunk(int whichThunk)
{
#if DEBUG
// The GetThunk function should be overriden on all delegate types, except for universal
// canonical delegates which use calling convention converter thunks to marshal arguments
// for the delegate call. If we execute this version of GetThunk, we can at least assert
// that the current delegate type is a generic type.
Debug.Assert(this.EETypePtr.IsGeneric);
#endif
return TypeLoaderExports.GetDelegateThunk(this, whichThunk);
}
//
// If there is a default value string, the overridden function should set the
// s_DefaultValueString field and return true.
protected virtual bool LoadDefaultValueString() { return false; }
/// <summary>
/// Used by various parts of the runtime as a replacement for Delegate.Method
///
/// The Interop layer uses this to distinguish between different methods on a
/// single type, and to get the function pointer for delegates to static functions
///
/// The reflection apis use this api to figure out what MethodInfo is related
/// to a delegate.
///
/// </summary>
/// <param name="typeOfFirstParameterIfInstanceDelegate">
/// This value indicates which type an delegate's function pointer is associated with
/// This value is ONLY set for delegates where the function pointer points at an instance method
/// </param>
/// <param name="isOpenResolver">
/// This value indicates if the returned pointer is an open resolver structure.
/// </param>
/// <param name="isInterpreterEntrypoint">
/// Delegate points to an object array thunk (the delegate wraps a Func<object[], object> delegate). This
/// is typically a delegate pointing to the LINQ expression interpreter.
/// </param>
/// <returns></returns>
unsafe internal IntPtr GetFunctionPointer(out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate, out bool isOpenResolver, out bool isInterpreterEntrypoint)
{
typeOfFirstParameterIfInstanceDelegate = default(RuntimeTypeHandle);
isOpenResolver = false;
isInterpreterEntrypoint = false;
if (GetThunk(MulticastThunk) == m_functionPointer)
{
return IntPtr.Zero;
}
else if (GetThunk(ObjectArrayThunk) == m_functionPointer)
{
isInterpreterEntrypoint = true;
return IntPtr.Zero;
}
else if (m_extraFunctionPointerOrData != IntPtr.Zero)
{
if (GetThunk(OpenInstanceThunk) == m_functionPointer)
{
typeOfFirstParameterIfInstanceDelegate = ((OpenMethodResolver*)m_extraFunctionPointerOrData)->DeclaringType;
isOpenResolver = true;
}
return m_extraFunctionPointerOrData;
}
else
{
if (m_firstParameter != null)
typeOfFirstParameterIfInstanceDelegate = new RuntimeTypeHandle(m_firstParameter.EETypePtr);
// TODO! Implementation issue for generic invokes here ... we need another IntPtr for uniqueness.
return m_functionPointer;
}
}
// @todo: Not an api but some NativeThreadPool code still depends on it.
internal IntPtr GetNativeFunctionPointer()
{
if (GetThunk(ReversePinvokeThunk) != m_functionPointer)
{
throw new InvalidOperationException("GetNativeFunctionPointer may only be used on a reverse pinvoke delegate");
}
return m_extraFunctionPointerOrData;
}
// This function is known to the IL Transformer.
protected void InitializeClosedInstance(object firstParameter, IntPtr functionPointer)
{
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
m_functionPointer = functionPointer;
m_firstParameter = firstParameter;
}
// This function is known to the IL Transformer.
protected void InitializeClosedInstanceSlow(object firstParameter, IntPtr functionPointer)
{
// This method is like InitializeClosedInstance, but it handles ALL cases. In particular, it handles generic method with fun function pointers.
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer))
{
m_functionPointer = functionPointer;
m_firstParameter = firstParameter;
}
else
{
m_firstParameter = this;
m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod);
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
}
}
// This function is known to the compiler.
protected void InitializeClosedInstanceWithGVMResolution(object firstParameter, RuntimeMethodHandle tokenOfGenericVirtualMethod)
{
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
IntPtr functionResolution = TypeLoaderExports.GVMLookupForSlot(firstParameter, tokenOfGenericVirtualMethod);
if (functionResolution == IntPtr.Zero)
{
// TODO! What to do when GVM resolution fails. Should never happen
throw new InvalidOperationException();
}
if (!FunctionPointerOps.IsGenericMethodPointer(functionResolution))
{
m_functionPointer = functionResolution;
m_firstParameter = firstParameter;
}
else
{
m_firstParameter = this;
m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod);
m_extraFunctionPointerOrData = functionResolution;
m_helperObject = firstParameter;
}
return;
}
private void InitializeClosedInstanceToInterface(object firstParameter, IntPtr dispatchCell)
{
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
m_functionPointer = RuntimeImports.RhpResolveInterfaceMethod(firstParameter, dispatchCell);
m_firstParameter = firstParameter;
}
// This is used to implement MethodInfo.CreateDelegate() in a desktop-compatible way. Yes, the desktop really
// let you use that api to invoke an instance method with a null 'this'.
private void InitializeClosedInstanceWithoutNullCheck(object firstParameter, IntPtr functionPointer)
{
if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer))
{
m_functionPointer = functionPointer;
m_firstParameter = firstParameter;
}
else
{
m_firstParameter = this;
m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod);
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
}
}
// This function is known to the compiler backend.
protected void InitializeClosedStaticThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
m_functionPointer = functionPointerThunk;
m_firstParameter = this;
}
// This function is known to the compiler backend.
protected void InitializeClosedStaticWithoutThunk(object firstParameter, IntPtr functionPointer)
{
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
m_functionPointer = GetThunk(ClosedStaticThunk);
m_firstParameter = this;
}
// This function is known to the compiler backend.
protected void InitializeOpenStaticThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
m_extraFunctionPointerOrData = functionPointer;
}
// This function is known to the compiler backend.
protected void InitializeOpenStaticWithoutThunk(object firstParameter, IntPtr functionPointer)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = GetThunk(OpenStaticThunk);
m_extraFunctionPointerOrData = functionPointer;
}
// This function is known to the compiler backend.
protected void InitializeReversePInvokeThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
m_extraFunctionPointerOrData = functionPointer;
}
// This function is known to the compiler backend.
protected void InitializeReversePInvokeWithoutThunk(object firstParameter, IntPtr functionPointer)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = GetThunk(ReversePinvokeThunk);
m_extraFunctionPointerOrData = functionPointer;
}
// This function is known to the compiler backend.
protected void InitializeOpenInstanceThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
OpenMethodResolver instanceMethodResolver = new OpenMethodResolver(default(RuntimeTypeHandle), functionPointer, default(GCHandle), 0);
m_extraFunctionPointerOrData = instanceMethodResolver.ToIntPtr();
}
// This function is known to the compiler backend.
protected void InitializeOpenInstanceWithoutThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = GetThunk(OpenInstanceThunk);
OpenMethodResolver instanceMethodResolver = new OpenMethodResolver(default(RuntimeTypeHandle), functionPointer, default(GCHandle), 0);
m_extraFunctionPointerOrData = instanceMethodResolver.ToIntPtr();
}
protected void InitializeOpenInstanceThunkDynamic(IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
m_extraFunctionPointerOrData = functionPointer;
}
internal void SetClosedStaticFirstParameter(object firstParameter)
{
// Closed static delegates place a value in m_helperObject that they pass to the target method.
Debug.Assert(m_functionPointer == GetThunk(ClosedStaticThunk));
m_helperObject = firstParameter;
}
// This function is only ever called by the open instance method thunk, and in that case,
// m_extraFunctionPointerOrData always points to an OpenMethodResolver
[MethodImpl(MethodImplOptions.NoInlining)]
protected IntPtr GetActualTargetFunctionPointer(object thisObject)
{
return OpenMethodResolver.ResolveMethod(m_extraFunctionPointerOrData, thisObject);
}
public override int GetHashCode()
{
return GetType().GetHashCode();
}
private bool IsDynamicDelegate()
{
if (this.GetThunk(MulticastThunk) == IntPtr.Zero)
{
return true;
}
return false;
}
[DebuggerGuidedStepThroughAttribute]
protected virtual object DynamicInvokeImpl(object[] args)
{
if (IsDynamicDelegate())
{
// DynamicDelegate case
object result = ((Func<object[], object>)m_helperObject)(args);
DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
return result;
}
else
{
IntPtr invokeThunk = this.GetThunk(DelegateInvokeThunk);
#if PROJECTN
object result = InvokeUtils.CallDynamicInvokeMethod(this.m_firstParameter, this.m_functionPointer, this, invokeThunk, IntPtr.Zero, this, args, binderBundle: null, wrapInTargetInvocationException: true);
#else
IntPtr genericDictionary = IntPtr.Zero;
if (FunctionPointerOps.IsGenericMethodPointer(invokeThunk))
{
unsafe
{
GenericMethodDescriptor* descriptor = FunctionPointerOps.ConvertToGenericDescriptor(invokeThunk);
genericDictionary = descriptor->InstantiationArgument;
invokeThunk = descriptor->MethodFunctionPointer;
}
}
object result = InvokeUtils.CallDynamicInvokeMethod(this.m_firstParameter, this.m_functionPointer, null, invokeThunk, genericDictionary, this, args, binderBundle: null, wrapInTargetInvocationException: true, invokeMethodHelperIsThisCall: false);
#endif
DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
return result;
}
}
[DebuggerGuidedStepThroughAttribute]
public object DynamicInvoke(params object[] args)
{
object result = DynamicInvokeImpl(args);
DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
return result;
}
public static unsafe Delegate Combine(Delegate a, Delegate b)
{
if (a == null)
return b;
if (b == null)
return a;
return a.CombineImpl(b);
}
public static Delegate Remove(Delegate source, Delegate value)
{
if (source == null)
return null;
if (value == null)
return source;
if (!InternalEqualTypes(source, value))
throw new ArgumentException(SR.Arg_DlgtTypeMis);
return source.RemoveImpl(value);
}
public static Delegate RemoveAll(Delegate source, Delegate value)
{
Delegate newDelegate = null;
do
{
newDelegate = source;
source = Remove(source, value);
}
while (newDelegate != source);
return newDelegate;
}
// Used to support the C# compiler in implementing the "+" operator for delegates
public static Delegate Combine(params Delegate[] delegates)
{
if ((delegates == null) || (delegates.Length == 0))
return null;
Delegate d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
{
d = Combine(d, delegates[i]);
}
return d;
}
private MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int invocationCount, bool thisIsMultiCastAlready)
{
// First, allocate a new multicast delegate just like this one, i.e. same type as the this object
MulticastDelegate result = (MulticastDelegate)RuntimeImports.RhNewObject(this.EETypePtr);
// Performance optimization - if this already points to a true multicast delegate,
// copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them
if (thisIsMultiCastAlready)
{
result.m_functionPointer = this.m_functionPointer;
}
else
{
result.m_functionPointer = GetThunk(MulticastThunk);
}
result.m_firstParameter = result;
result.m_helperObject = invocationList;
result.m_extraFunctionPointerOrData = (IntPtr)invocationCount;
return result;
}
internal MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int invocationCount)
{
return NewMulticastDelegate(invocationList, invocationCount, false);
}
private bool TrySetSlot(Delegate[] a, int index, Delegate o)
{
if (a[index] == null && System.Threading.Interlocked.CompareExchange<Delegate>(ref a[index], o, null) == null)
return true;
// The slot may be already set because we have added and removed the same method before.
// Optimize this case, because it's cheaper than copying the array.
if (a[index] != null)
{
MulticastDelegate d = (MulticastDelegate)o;
MulticastDelegate dd = (MulticastDelegate)a[index];
if (Object.ReferenceEquals(dd.m_firstParameter, d.m_firstParameter) &&
Object.ReferenceEquals(dd.m_helperObject, d.m_helperObject) &&
dd.m_extraFunctionPointerOrData == d.m_extraFunctionPointerOrData &&
dd.m_functionPointer == d.m_functionPointer)
{
return true;
}
}
return false;
}
// This method will combine this delegate with the passed delegate
// to form a new delegate.
protected virtual Delegate CombineImpl(Delegate d)
{
if ((Object)d == null) // cast to object for a more efficient test
return this;
// Verify that the types are the same...
if (!InternalEqualTypes(this, d))
throw new ArgumentException();
if (IsDynamicDelegate() && d.IsDynamicDelegate())
{
throw new InvalidOperationException();
}
MulticastDelegate dFollow = (MulticastDelegate)d;
Delegate[] resultList;
int followCount = 1;
Delegate[] followList = dFollow.m_helperObject as Delegate[];
if (followList != null)
followCount = (int)dFollow.m_extraFunctionPointerOrData;
int resultCount;
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList == null)
{
resultCount = 1 + followCount;
resultList = new Delegate[resultCount];
resultList[0] = this;
if (followList == null)
{
resultList[1] = dFollow;
}
else
{
for (int i = 0; i < followCount; i++)
resultList[1 + i] = followList[i];
}
return NewMulticastDelegate(resultList, resultCount);
}
else
{
int invocationCount = (int)m_extraFunctionPointerOrData;
resultCount = invocationCount + followCount;
resultList = null;
if (resultCount <= invocationList.Length)
{
resultList = invocationList;
if (followList == null)
{
if (!TrySetSlot(resultList, invocationCount, dFollow))
resultList = null;
}
else
{
for (int i = 0; i < followCount; i++)
{
if (!TrySetSlot(resultList, invocationCount + i, followList[i]))
{
resultList = null;
break;
}
}
}
}
if (resultList == null)
{
int allocCount = invocationList.Length;
while (allocCount < resultCount)
allocCount *= 2;
resultList = new Delegate[allocCount];
for (int i = 0; i < invocationCount; i++)
resultList[i] = invocationList[i];
if (followList == null)
{
resultList[invocationCount] = dFollow;
}
else
{
for (int i = 0; i < followCount; i++)
resultList[invocationCount + i] = followList[i];
}
}
return NewMulticastDelegate(resultList, resultCount, true);
}
}
private Delegate[] DeleteFromInvocationList(Delegate[] invocationList, int invocationCount, int deleteIndex, int deleteCount)
{
Delegate[] thisInvocationList = m_helperObject as Delegate[];
int allocCount = thisInvocationList.Length;
while (allocCount / 2 >= invocationCount - deleteCount)
allocCount /= 2;
Delegate[] newInvocationList = new Delegate[allocCount];
for (int i = 0; i < deleteIndex; i++)
newInvocationList[i] = invocationList[i];
for (int i = deleteIndex + deleteCount; i < invocationCount; i++)
newInvocationList[i - deleteCount] = invocationList[i];
return newInvocationList;
}
private bool EqualInvocationLists(Delegate[] a, Delegate[] b, int start, int count)
{
for (int i = 0; i < count; i++)
{
if (!(a[start + i].Equals(b[i])))
return false;
}
return true;
}
// This method currently looks backward on the invocation list
// for an element that has Delegate based equality with value. (Doesn't
// look at the invocation list.) If this is found we remove it from
// this list and return a new delegate. If its not found a copy of the
// current list is returned.
protected virtual Delegate RemoveImpl(Delegate d)
{
// There is a special case were we are removing using a delegate as
// the value we need to check for this case
//
MulticastDelegate v = d as MulticastDelegate;
if (v == null)
return this;
if (v.m_helperObject as Delegate[] == null)
{
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList == null)
{
// they are both not real Multicast
if (this.Equals(d))
return null;
}
else
{
int invocationCount = (int)m_extraFunctionPointerOrData;
for (int i = invocationCount; --i >= 0;)
{
if (d.Equals(invocationList[i]))
{
if (invocationCount == 2)
{
// Special case - only one value left, either at the beginning or the end
return invocationList[1 - i];
}
else
{
Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1);
return NewMulticastDelegate(list, invocationCount - 1, true);
}
}
}
}
}
else
{
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList != null)
{
int invocationCount = (int)m_extraFunctionPointerOrData;
int vInvocationCount = (int)v.m_extraFunctionPointerOrData;
for (int i = invocationCount - vInvocationCount; i >= 0; i--)
{
if (EqualInvocationLists(invocationList, v.m_helperObject as Delegate[], i, vInvocationCount))
{
if (invocationCount - vInvocationCount == 0)
{
// Special case - no values left
return null;
}
else if (invocationCount - vInvocationCount == 1)
{
// Special case - only one value left, either at the beginning or the end
return invocationList[i != 0 ? 0 : invocationCount - 1];
}
else
{
Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount);
return NewMulticastDelegate(list, invocationCount - vInvocationCount, true);
}
}
}
}
}
return this;
}
public virtual Delegate[] GetInvocationList()
{
Delegate[] del;
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList == null)
{
del = new Delegate[1];
del[0] = this;
}
else
{
// Create an array of delegate copies and each
// element into the array
int invocationCount = (int)m_extraFunctionPointerOrData;
del = new Delegate[invocationCount];
for (int i = 0; i < del.Length; i++)
del[i] = invocationList[i];
}
return del;
}
public MethodInfo Method
{
get
{
return GetMethodImpl();
}
}
protected virtual MethodInfo GetMethodImpl()
{
return RuntimeAugments.Callbacks.GetDelegateMethod(this);
}
public override bool Equals(Object obj)
{
// It is expected that all real uses of the Equals method will hit the MulticastDelegate.Equals logic instead of this
// therefore, instead of duplicating the desktop behavior where direct calls to this Equals function do not behave
// correctly, we'll just throw here.
throw new PlatformNotSupportedException();
}
public static bool operator ==(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 == null;
return d1.Equals(d2);
}
public static bool operator !=(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 != null;
return !d1.Equals(d2);
}
public Object Target
{
get
{
// Multi-cast delegates return the Target of the last delegate in the list
if (m_functionPointer == GetThunk(MulticastThunk))
{
Delegate[] invocationList = (Delegate[])m_helperObject;
int invocationCount = (int)m_extraFunctionPointerOrData;
return invocationList[invocationCount - 1].Target;
}
// Closed static delegates place a value in m_helperObject that they pass to the target method.
if (m_functionPointer == GetThunk(ClosedStaticThunk) ||
m_functionPointer == GetThunk(ClosedInstanceThunkOverGenericMethod) ||
m_functionPointer == GetThunk(ObjectArrayThunk))
return m_helperObject;
// Other non-closed thunks can be identified as the m_firstParameter field points at this.
if (Object.ReferenceEquals(m_firstParameter, this))
{
return null;
}
// Closed instance delegates place a value in m_firstParameter, and we've ruled out all other types of delegates
return m_firstParameter;
}
}
// V2 api: Creates open or closed delegates to static or instance methods - relaxed signature checking allowed.
public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method) => CreateDelegate(type, firstArgument, method, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, firstArgument, method, throwOnBindFailure);
// V1 api: Creates open delegates to static or instance methods - relaxed signature checking allowed.
public static Delegate CreateDelegate(Type type, MethodInfo method) => CreateDelegate(type, method, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, method, throwOnBindFailure);
// V1 api: Creates closed delegates to instance methods only, relaxed signature checking disallowed.
public static Delegate CreateDelegate(Type type, object target, string method) => CreateDelegate(type, target, method, ignoreCase: false, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase) => CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure);
// V1 api: Creates open delegates to static methods only, relaxed signature checking disallowed.
public static Delegate CreateDelegate(Type type, Type target, string method) => CreateDelegate(type, target, method, ignoreCase: false, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase) => CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure);
public virtual object Clone()
{
return MemberwiseClone();
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException(SR.Serialization_DelegatesNotSupported);
}
internal bool IsOpenStatic
{
get
{
return GetThunk(OpenStaticThunk) == m_functionPointer;
}
}
internal static bool InternalEqualTypes(object a, object b)
{
return a.EETypePtr == b.EETypePtr;
}
// Returns a new delegate of the specified type whose implementation is provied by the
// provided delegate.
internal static Delegate CreateObjectArrayDelegate(Type t, Func<object[], object> handler)
{
EETypePtr delegateEEType;
if (!t.TryGetEEType(out delegateEEType))
{
throw new InvalidOperationException();
}
if (!delegateEEType.IsDefType || delegateEEType.IsGenericTypeDefinition)
{
throw new InvalidOperationException();
}
Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType));
IntPtr objArrayThunk = del.GetThunk(Delegate.ObjectArrayThunk);
if (objArrayThunk == IntPtr.Zero)
{
throw new InvalidOperationException();
}
del.m_helperObject = handler;
del.m_functionPointer = objArrayThunk;
del.m_firstParameter = del;
return del;
}
//
// Internal (and quite unsafe) helper to create delegates of an arbitrary type. This is used to support Reflection invoke.
//
// Note that delegates constructed the normal way do not come through here. The IL transformer generates the equivalent of
// this code customized for each delegate type.
//
internal static Delegate CreateDelegate(EETypePtr delegateEEType, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isOpen)
{
Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType));
// What? No constructor call? That's right, and it's not an oversight. All "construction" work happens in
// the Initialize() methods. This helper has a hard dependency on this invariant.
if (isStatic)
{
if (isOpen)
{
IntPtr thunk = del.GetThunk(Delegate.OpenStaticThunk);
del.InitializeOpenStaticThunk(null, ldftnResult, thunk);
}
else
{
IntPtr thunk = del.GetThunk(Delegate.ClosedStaticThunk);
del.InitializeClosedStaticThunk(thisObject, ldftnResult, thunk);
}
}
else
{
if (isOpen)
{
IntPtr thunk = del.GetThunk(Delegate.OpenInstanceThunk);
del.InitializeOpenInstanceThunkDynamic(ldftnResult, thunk);
}
else
{
del.InitializeClosedInstanceWithoutNullCheck(thisObject, ldftnResult);
}
}
return del;
}
private string GetTargetMethodsDescriptionForDebugger()
{
if (m_functionPointer == GetThunk(MulticastThunk))
{
// Multi-cast delegates return the Target of the last delegate in the list
Delegate[] invocationList = (Delegate[])m_helperObject;
int invocationCount = (int)m_extraFunctionPointerOrData;
StringBuilder builder = new StringBuilder();
for (int c = 0; c < invocationCount; c++)
{
if (c != 0)
builder.Append(", ");
builder.Append(invocationList[c].GetTargetMethodsDescriptionForDebugger());
}
return builder.ToString();
}
else
{
RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate;
IntPtr functionPointer = GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out bool _, out bool _);
if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer))
{
return DebuggerFunctionPointerFormattingHook(functionPointer, typeOfFirstParameterIfInstanceDelegate);
}
else
{
unsafe
{
GenericMethodDescriptor* pointerDef = FunctionPointerOps.ConvertToGenericDescriptor(functionPointer);
return DebuggerFunctionPointerFormattingHook(pointerDef->InstantiationArgument, typeOfFirstParameterIfInstanceDelegate);
}
}
}
}
private static string DebuggerFunctionPointerFormattingHook(IntPtr functionPointer, RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate)
{
// This method will be hooked by the debugger and the debugger will cause it to return a description for the function pointer
throw new NotSupportedException();
}
}
}
| |
namespace Nancy.Diagnostics
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Nancy.Bootstrapper;
using Nancy.Configuration;
using Nancy.Conventions;
using Nancy.Cookies;
using Nancy.Cryptography;
using Nancy.Culture;
using Nancy.Json;
using Nancy.Localization;
using Nancy.ModelBinding;
using Nancy.Responses;
using Nancy.Responses.Negotiation;
using Nancy.Routing;
using Nancy.Routing.Constraints;
using Nancy.Routing.Trie;
/// <summary>
/// Pipeline hook to handle diagnostics dashboard requests.
/// </summary>
public static class DiagnosticsHook
{
private static readonly CancellationToken CancellationToken = new CancellationToken();
private const string PipelineKey = "__Diagnostics";
internal const string ItemsKey = "DIAGS_REQUEST";
/// <summary>
/// Enables the diagnostics dashboard and will intercept all requests that are passed to
/// the condigured paths.
/// </summary>
public static void Enable(IPipelines pipelines, IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable<IResponseProcessor> responseProcessors, IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable<IRouteMetadataProvider> routeMetadataProviders, ITextResource textResource, INancyEnvironment environment, ITypeCatalog typeCatalog, IAssemblyCatalog assemblyCatalog, AcceptHeaderCoercionConventions acceptHeaderCoercionConventions)
{
var diagnosticsConfiguration =
environment.GetValue<DiagnosticsConfiguration>();
var diagnosticsEnvironment =
GetDiagnosticsEnvironment();
var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment, typeCatalog, assemblyCatalog);
var diagnosticsRouteCache = new RouteCache(
diagnosticsModuleCatalog,
new DefaultNancyContextFactory(cultureService, requestTraceFactory, textResource, environment),
new DefaultRouteSegmentExtractor(),
new DefaultRouteDescriptionProvider(),
cultureService,
routeMetadataProviders);
var diagnosticsRouteResolver = new DefaultRouteResolver(
diagnosticsModuleCatalog,
new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator, diagnosticsEnvironment, environment),
diagnosticsRouteCache,
new RouteResolverTrie(new TrieNodeFactory(routeSegmentConstraints)),
environment);
var diagnosticResponseNegotiator = new DefaultResponseNegotiator(responseProcessors, acceptHeaderCoercionConventions);
var diagnosticRouteInvoker = new DefaultRouteInvoker(diagnosticResponseNegotiator);
var serializer = new DefaultObjectSerializer();
pipelines.BeforeRequest.AddItemToStartOfPipeline(
new PipelineItem<Func<NancyContext, Response>>(
PipelineKey,
ctx =>
{
if (!ctx.ControlPanelEnabled)
{
return null;
}
if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase))
{
return null;
}
if (!diagnosticsConfiguration.Enabled)
{
return HttpStatusCode.NotFound;
}
ctx.Items[ItemsKey] = true;
var resourcePrefix =
string.Concat(diagnosticsConfiguration.Path, "/Resources/");
if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase))
{
var resourceNamespace = "Nancy.Diagnostics.Resources";
var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty;
if (!string.IsNullOrEmpty(path))
{
resourceNamespace += string.Format(".{0}", path.Replace(Path.DirectorySeparatorChar, '.'));
}
return new EmbeddedFileResponse(
typeof(DiagnosticsHook).GetTypeInfo().Assembly,
resourceNamespace,
Path.GetFileName(ctx.Request.Url.Path));
}
RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx);
return ValidateConfiguration(diagnosticsConfiguration)
? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer, diagnosticsEnvironment, diagnosticRouteInvoker)
: new DiagnosticsViewRenderer(ctx, environment)["help"];
}));
}
/// <summary>
/// Gets a special <see cref="INancyEnvironment"/> instance that is separate from the
/// one used by the application.
/// </summary>
/// <returns></returns>
private static INancyEnvironment GetDiagnosticsEnvironment()
{
var diagnosticsEnvironment =
new DefaultNancyEnvironment();
diagnosticsEnvironment.Globalization(new[] { "en-US" });
diagnosticsEnvironment.Json(retainCasing: false);
diagnosticsEnvironment.AddValue(ViewConfiguration.Default);
diagnosticsEnvironment.Tracing(
enabled: true,
displayErrorTraces: true);
return diagnosticsEnvironment;
}
private static bool ValidateConfiguration(DiagnosticsConfiguration configuration)
{
return !string.IsNullOrWhiteSpace(configuration.Password) &&
!string.IsNullOrWhiteSpace(configuration.CookieName) &&
!string.IsNullOrWhiteSpace(configuration.Path) &&
configuration.SlidingTimeout != 0;
}
/// <summary>
/// Disables the specified pipelines.
/// <seealso cref="IPipelines"/>
/// </summary>
/// <param name="pipelines">The pipelines.</param>
public static void Disable(IPipelines pipelines)
{
pipelines.BeforeRequest.RemoveByName(PipelineKey);
}
private static Response GetDiagnosticsLoginView(NancyContext ctx, INancyEnvironment environment)
{
var renderer = new DiagnosticsViewRenderer(ctx, environment);
return renderer["login"];
}
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer, INancyEnvironment environment, IRouteInvoker routeInvoker)
{
var session = GetSession(ctx, diagnosticsConfiguration, serializer);
if (session == null)
{
var view = GetDiagnosticsLoginView(ctx, environment);
view.WithCookie(
new NancyCookie(diagnosticsConfiguration.CookieName, string.Empty, true) { Expires = DateTime.Now.AddDays(-1) });
return view;
}
var resolveResult = routeResolver.Resolve(ctx);
ctx.Parameters = resolveResult.Parameters;
ExecuteRoutePreReq(ctx, CancellationToken, resolveResult.Before);
if (ctx.Response == null)
{
var routeResult = routeInvoker.Invoke(resolveResult.Route, CancellationToken, resolveResult.Parameters, ctx);
ctx.Response = routeResult.Result;
}
if (ctx.Request.Method.Equals("HEAD", StringComparison.OrdinalIgnoreCase))
{
ctx.Response = new HeadResponse(ctx.Response);
}
if (resolveResult.After != null)
{
resolveResult.After.Invoke(ctx, CancellationToken);
}
AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer);
return ctx.Response;
}
private static void AddUpdateSessionCookie(DiagnosticsSession session, NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
{
if (context.Response == null)
{
return;
}
session.Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout);
var serializedSession = serializer.Serialize(session);
var encryptedSession = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Encrypt(serializedSession);
var hmacBytes = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);
var hmacString = Convert.ToBase64String(hmacBytes);
var cookie = new NancyCookie(diagnosticsConfiguration.CookieName, string.Format("{1}{0}", encryptedSession, hmacString), true);
context.Response.WithCookie(cookie);
}
private static DiagnosticsSession GetSession(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
{
if (context.Request == null)
{
return null;
}
if (IsLoginRequest(context, diagnosticsConfiguration))
{
return ProcessLogin(context, diagnosticsConfiguration, serializer);
}
string encryptedValue;
if (!context.Request.Cookies.TryGetValue(diagnosticsConfiguration.CookieName, out encryptedValue))
{
return null;
}
var hmacStringLength = Base64Helpers.GetBase64Length(diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);
var encryptedSession = encryptedValue.Substring(hmacStringLength);
var hmacString = encryptedValue.Substring(0, hmacStringLength);
var hmacBytes = Convert.FromBase64String(hmacString);
var newHmac = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);
var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);
if (!hmacValid)
{
return null;
}
var decryptedValue = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Decrypt(encryptedSession);
var session = serializer.Deserialize(decryptedValue) as DiagnosticsSession;
if (session == null || session.Expiry < DateTimeOffset.Now || !SessionPasswordValid(session, diagnosticsConfiguration.Password))
{
return null;
}
return session;
}
private static bool SessionPasswordValid(DiagnosticsSession session, string realPassword)
{
var newHash = DiagnosticsSession.GenerateSaltedHash(realPassword, session.Salt);
return (newHash.Length == session.Hash.Length && newHash.SequenceEqual(session.Hash));
}
private static DiagnosticsSession ProcessLogin(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
{
string password = context.Request.Form.Password;
if (!string.Equals(password, diagnosticsConfiguration.Password, StringComparison.Ordinal))
{
return null;
}
var salt = DiagnosticsSession.GenerateRandomSalt();
var hash = DiagnosticsSession.GenerateSaltedHash(password, salt);
var session = new DiagnosticsSession
{
Hash = hash,
Salt = salt,
Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout)
};
return session;
}
private static bool IsLoginRequest(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration)
{
return context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase) &&
context.Request.Url.BasePath.TrimEnd('/').EndsWith(diagnosticsConfiguration.Path) &&
context.Request.Url.Path == "/";
}
private static void ExecuteRoutePreReq(NancyContext context, CancellationToken cancellationToken, BeforePipeline resolveResultPreReq)
{
if (resolveResultPreReq == null)
{
return;
}
var resolveResultPreReqResponse = resolveResultPreReq.Invoke(context, cancellationToken).Result;
if (resolveResultPreReqResponse != null)
{
context.Response = resolveResultPreReqResponse;
}
}
private static void RewriteDiagnosticsUrl(DiagnosticsConfiguration diagnosticsConfiguration, NancyContext ctx)
{
ctx.Request.Url.BasePath =
string.Concat(ctx.Request.Url.BasePath, diagnosticsConfiguration.Path);
ctx.Request.Url.Path =
ctx.Request.Url.Path.Substring(diagnosticsConfiguration.Path.Length);
if (ctx.Request.Url.Path.Length.Equals(0))
{
ctx.Request.Url.Path = "/";
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="StoreItemCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Metadata.Edm
{
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Common.Utils;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Versioning;
using System.Xml;
/// <summary>
/// Class for representing a collection of items in Store space.
/// </summary>
[CLSCompliant(false)]
public sealed partial class StoreItemCollection : ItemCollection
{
#region Fields
double _schemaVersion = XmlConstants.UndefinedVersion;
// Cache for primitive type maps for Edm to provider
private readonly CacheForPrimitiveTypes _primitiveTypeMaps = new CacheForPrimitiveTypes();
private readonly Memoizer<EdmFunction, EdmFunction> _cachedCTypeFunction;
private readonly DbProviderManifest _providerManifest;
private readonly string _providerManifestToken;
private readonly DbProviderFactory _providerFactory;
// Storing the query cache manager in the store item collection since all queries are currently bound to the
// store. So storing it in StoreItemCollection makes sense. Also, since query cache requires version and other
// stuff of the provider, we can assume that the connection is always open and we have the store metadata.
// Also we can use the same cache manager both for Entity Client and Object Query, since query cache has
// no reference to any metadata in OSpace. Also we assume that ObjectMaterializer loads the assembly
// before it tries to do object materialization, since we might not have loaded an assembly in another workspace
// where this store item collection is getting reused
private readonly System.Data.Common.QueryCache.QueryCacheManager _queryCacheManager = System.Data.Common.QueryCache.QueryCacheManager.Create();
#endregion
#region Constructors
// used by EntityStoreSchemaGenerator to start with an empty (primitive types only) StoreItemCollection and
// add types discovered from the database
internal StoreItemCollection(DbProviderFactory factory, DbProviderManifest manifest, string providerManifestToken)
: base(DataSpace.SSpace)
{
Debug.Assert(factory != null, "factory is null");
Debug.Assert(manifest != null, "manifest is null");
_providerFactory = factory;
_providerManifest = manifest;
_providerManifestToken = providerManifestToken;
_cachedCTypeFunction = new Memoizer<EdmFunction, EdmFunction>(ConvertFunctionSignatureToCType, null);
LoadProviderManifest(_providerManifest, true /*checkForSystemNamespace*/);
}
/// <summary>
/// constructor that loads the metadata files from the specified xmlReaders, and returns the list of errors
/// encountered during load as the out parameter errors.
///
/// Publicly available from System.Data.Entity.Desgin.dll
/// </summary>
/// <param name="xmlReaders">xmlReaders where the CDM schemas are loaded</param>
/// <param name="filePaths">the paths where the files can be found that match the xml readers collection</param>
/// <param name="errors">An out parameter to return the collection of errors encountered while loading</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] // referenced by System.Data.Entity.Design.dll
internal StoreItemCollection(IEnumerable<XmlReader> xmlReaders,
System.Collections.ObjectModel.ReadOnlyCollection<string> filePaths,
out IList<EdmSchemaError> errors)
: base(DataSpace.SSpace)
{
// we will check the parameters for this internal ctor becuase
// it is pretty much publicly exposed through the MetadataItemCollectionFactory
// in System.Data.Entity.Design
EntityUtil.CheckArgumentNull(xmlReaders, "xmlReaders");
EntityUtil.CheckArgumentContainsNull(ref xmlReaders, "xmlReaders");
EntityUtil.CheckArgumentEmpty(ref xmlReaders, Strings.StoreItemCollectionMustHaveOneArtifact, "xmlReader");
// filePaths is allowed to be null
errors = this.Init(xmlReaders, filePaths, false,
out _providerManifest,
out _providerFactory,
out _providerManifestToken,
out _cachedCTypeFunction);
}
/// <summary>
/// constructor that loads the metadata files from the specified xmlReaders, and returns the list of errors
/// encountered during load as the out parameter errors.
///
/// Publicly available from System.Data.Entity.Desgin.dll
/// </summary>
/// <param name="xmlReaders">xmlReaders where the CDM schemas are loaded</param>
/// <param name="filePaths">the paths where the files can be found that match the xml readers collection</param>
internal StoreItemCollection(IEnumerable<XmlReader> xmlReaders,
IEnumerable<string> filePaths)
: base(DataSpace.SSpace)
{
EntityUtil.CheckArgumentNull(filePaths, "filePaths");
EntityUtil.CheckArgumentEmpty(ref xmlReaders, Strings.StoreItemCollectionMustHaveOneArtifact, "xmlReader");
this.Init(xmlReaders, filePaths, true,
out _providerManifest,
out _providerFactory,
out _providerManifestToken,
out _cachedCTypeFunction);
}
/// <summary>
/// Public constructor that loads the metadata files from the specified xmlReaders.
/// Throws when encounter errors.
/// </summary>
/// <param name="xmlReaders">xmlReaders where the CDM schemas are loaded</param>
public StoreItemCollection(IEnumerable<XmlReader> xmlReaders)
: base(DataSpace.SSpace)
{
EntityUtil.CheckArgumentNull(xmlReaders, "xmlReaders");
EntityUtil.CheckArgumentEmpty(ref xmlReaders, Strings.StoreItemCollectionMustHaveOneArtifact, "xmlReader");
MetadataArtifactLoader composite = MetadataArtifactLoader.CreateCompositeFromXmlReaders(xmlReaders);
this.Init(composite.GetReaders(),
composite.GetPaths(), true,
out _providerManifest,
out _providerFactory,
out _providerManifestToken,
out _cachedCTypeFunction);
}
/// <summary>
/// Constructs the new instance of StoreItemCollection
/// with the list of CDM files provided.
/// </summary>
/// <param name="filePaths">paths where the CDM schemas are loaded</param>
/// <exception cref="ArgumentException"> Thrown if path name is not valid</exception>
/// <exception cref="System.ArgumentNullException">thrown if paths argument is null</exception>
/// <exception cref="System.Data.MetadataException">For errors related to invalid schemas.</exception>
[ResourceExposure(ResourceScope.Machine)] //Exposes the file path names which are a Machine resource
[ResourceConsumption(ResourceScope.Machine)] //For MetadataArtifactLoader.CreateCompositeFromFilePaths method call but we do not create the file paths in this method
public StoreItemCollection(params string[] filePaths)
: base(DataSpace.SSpace)
{
EntityUtil.CheckArgumentNull(filePaths, "filePaths");
IEnumerable<string> enumerableFilePaths = filePaths;
EntityUtil.CheckArgumentEmpty(ref enumerableFilePaths, Strings.StoreItemCollectionMustHaveOneArtifact, "filePaths");
// Wrap the file paths in instances of the MetadataArtifactLoader class, which provides
// an abstraction and a uniform interface over a diverse set of metadata artifacts.
//
MetadataArtifactLoader composite = null;
List<XmlReader> readers = null;
try
{
composite = MetadataArtifactLoader.CreateCompositeFromFilePaths(enumerableFilePaths, XmlConstants.SSpaceSchemaExtension);
readers = composite.CreateReaders(DataSpace.SSpace);
IEnumerable<XmlReader> ieReaders = readers.AsEnumerable();
EntityUtil.CheckArgumentEmpty(ref ieReaders, Strings.StoreItemCollectionMustHaveOneArtifact, "filePaths");
this.Init(readers,
composite.GetPaths(DataSpace.SSpace), true,
out _providerManifest,
out _providerFactory,
out _providerManifestToken,
out _cachedCTypeFunction);
}
finally
{
if (readers != null)
{
Helper.DisposeXmlReaders(readers);
}
}
}
private IList<EdmSchemaError> Init(IEnumerable<XmlReader> xmlReaders,
IEnumerable<string> filePaths, bool throwOnError,
out DbProviderManifest providerManifest,
out DbProviderFactory providerFactory,
out string providerManifestToken,
out Memoizer<EdmFunction, EdmFunction> cachedCTypeFunction)
{
EntityUtil.CheckArgumentNull(xmlReaders, "xmlReaders");
// 'filePaths' can be null
cachedCTypeFunction = new Memoizer<EdmFunction, EdmFunction>(ConvertFunctionSignatureToCType, null);
Loader loader = new Loader(xmlReaders, filePaths, throwOnError);
providerFactory = loader.ProviderFactory;
providerManifest = loader.ProviderManifest;
providerManifestToken = loader.ProviderManifestToken;
// load the items into the colleciton
if (!loader.HasNonWarningErrors)
{
LoadProviderManifest(loader.ProviderManifest, true /* check for system namespace */);
List<EdmSchemaError> errorList = EdmItemCollection.LoadItems(_providerManifest, loader.Schemas, this);
foreach (var error in errorList)
{
loader.Errors.Add(error);
}
if (throwOnError && errorList.Count != 0)
loader.ThrowOnNonWarningErrors();
}
return loader.Errors;
}
#endregion
#region Properties
/// <summary>
/// Returns the query cache manager
/// </summary>
internal System.Data.Common.QueryCache.QueryCacheManager QueryCacheManager
{
get { return _queryCacheManager; }
}
internal DbProviderFactory StoreProviderFactory
{
get
{
return _providerFactory;
}
}
internal DbProviderManifest StoreProviderManifest
{
get
{
return _providerManifest;
}
}
internal string StoreProviderManifestToken
{
get
{
return _providerManifestToken;
}
}
/// <summary>
/// Version of this StoreItemCollection represents.
/// </summary>
public Double StoreSchemaVersion
{
get
{
return _schemaVersion;
}
internal set
{
_schemaVersion = value;
}
}
#endregion
#region Methods
/// <summary>
/// Get the list of primitive types for the given space
/// </summary>
/// <returns></returns>
public System.Collections.ObjectModel.ReadOnlyCollection<PrimitiveType> GetPrimitiveTypes()
{
return _primitiveTypeMaps.GetTypes();
}
/// <summary>
/// Given the canonical primitive type, get the mapping primitive type in the given dataspace
/// </summary>
/// <param name="primitiveTypeKind">canonical primitive type</param>
/// <returns>The mapped scalar type</returns>
internal override PrimitiveType GetMappedPrimitiveType(PrimitiveTypeKind primitiveTypeKind)
{
PrimitiveType type = null;
_primitiveTypeMaps.TryGetType(primitiveTypeKind, null, out type);
return type;
}
/// <summary>
/// checks if the schemaKey refers to the provider manifest schema key
/// and if true, loads the provider manifest
/// </summary>
/// <param name="connection">The connection where the store manifest is loaded from</param>
/// <param name="checkForSystemNamespace">Check for System namespace</param>
/// <returns>The provider manifest object that was loaded</returns>
private void LoadProviderManifest(DbProviderManifest storeManifest,
bool checkForSystemNamespace)
{
foreach (PrimitiveType primitiveType in storeManifest.GetStoreTypes())
{
//Add it to the collection and the primitive type maps
this.AddInternal(primitiveType);
_primitiveTypeMaps.Add(primitiveType);
}
foreach (EdmFunction function in storeManifest.GetStoreFunctions())
{
AddInternal(function);
}
}
#endregion
/// <summary>
/// Get all the overloads of the function with the given name, this method is used for internal perspective
/// </summary>
/// <param name="functionName">The full name of the function</param>
/// <param name="ignoreCase">true for case-insensitive lookup</param>
/// <returns>A collection of all the functions with the given name in the given data space</returns>
/// <exception cref="System.ArgumentNullException">Thrown if functionaName argument passed in is null</exception>
internal System.Collections.ObjectModel.ReadOnlyCollection<EdmFunction> GetCTypeFunctions(string functionName, bool ignoreCase)
{
System.Collections.ObjectModel.ReadOnlyCollection<EdmFunction> functionOverloads;
if (this.FunctionLookUpTable.TryGetValue(functionName, out functionOverloads))
{
functionOverloads = ConvertToCTypeFunctions(functionOverloads);
if (ignoreCase)
{
return functionOverloads;
}
return GetCaseSensitiveFunctions(functionOverloads, functionName);
}
return Helper.EmptyEdmFunctionReadOnlyCollection;
}
private System.Collections.ObjectModel.ReadOnlyCollection<EdmFunction> ConvertToCTypeFunctions(
System.Collections.ObjectModel.ReadOnlyCollection<EdmFunction> functionOverloads)
{
List<EdmFunction> cTypeFunctions = new List<EdmFunction>();
foreach (var sTypeFunction in functionOverloads)
{
cTypeFunctions.Add(ConvertToCTypeFunction(sTypeFunction));
}
return cTypeFunctions.AsReadOnly();
}
internal EdmFunction ConvertToCTypeFunction(EdmFunction sTypeFunction)
{
return this._cachedCTypeFunction.Evaluate(sTypeFunction);
}
/// <summary>
/// Convert the S type function parameters and returnType to C types.
/// </summary>
private EdmFunction ConvertFunctionSignatureToCType(EdmFunction sTypeFunction)
{
Debug.Assert(sTypeFunction.DataSpace == Edm.DataSpace.SSpace, "sTypeFunction.DataSpace == Edm.DataSpace.SSpace");
if (sTypeFunction.IsFromProviderManifest)
{
return sTypeFunction;
}
FunctionParameter returnParameter = null;
if (sTypeFunction.ReturnParameter != null)
{
TypeUsage edmTypeUsageReturnParameter =
MetadataHelper.ConvertStoreTypeUsageToEdmTypeUsage(sTypeFunction.ReturnParameter.TypeUsage);
returnParameter =
new FunctionParameter(
sTypeFunction.ReturnParameter.Name,
edmTypeUsageReturnParameter,
sTypeFunction.ReturnParameter.GetParameterMode());
}
List<FunctionParameter> parameters = new List<FunctionParameter>();
if (sTypeFunction.Parameters.Count > 0)
{
foreach (var parameter in sTypeFunction.Parameters)
{
TypeUsage edmTypeUsage = MetadataHelper.ConvertStoreTypeUsageToEdmTypeUsage(parameter.TypeUsage);
FunctionParameter edmTypeParameter = new FunctionParameter(parameter.Name, edmTypeUsage, parameter.GetParameterMode());
parameters.Add(edmTypeParameter);
}
}
FunctionParameter[] returnParameters =
returnParameter == null ? new FunctionParameter[0] : new FunctionParameter[] { returnParameter };
EdmFunction edmFunction = new EdmFunction(sTypeFunction.Name,
sTypeFunction.NamespaceName,
DataSpace.CSpace,
new EdmFunctionPayload
{
Schema = sTypeFunction.Schema,
StoreFunctionName = sTypeFunction.StoreFunctionNameAttribute,
CommandText = sTypeFunction.CommandTextAttribute,
IsAggregate = sTypeFunction.AggregateAttribute,
IsBuiltIn = sTypeFunction.BuiltInAttribute,
IsNiladic = sTypeFunction.NiladicFunctionAttribute,
IsComposable = sTypeFunction.IsComposableAttribute,
IsFromProviderManifest = sTypeFunction.IsFromProviderManifest,
IsCachedStoreFunction = true,
IsFunctionImport = sTypeFunction.IsFunctionImport,
ReturnParameters = returnParameters,
Parameters = parameters.ToArray(),
ParameterTypeSemantics = sTypeFunction.ParameterTypeSemanticsAttribute,
});
edmFunction.SetReadOnly();
return edmFunction;
}
}//---- ItemCollection
}//----
| |
// 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 Xunit;
namespace System.Text.Tests
{
public static partial class NegativeEncodingTests
{
public static IEnumerable<object[]> Encodings_TestData()
{
yield return new object[] { new UnicodeEncoding(false, false) };
yield return new object[] { new UnicodeEncoding(true, false) };
yield return new object[] { new UnicodeEncoding(true, true) };
yield return new object[] { new UnicodeEncoding(true, true) };
yield return new object[] { new UTF7Encoding(true) };
yield return new object[] { new UTF7Encoding(false) };
yield return new object[] { new UTF8Encoding(true, true) };
yield return new object[] { new UTF8Encoding(false, true) };
yield return new object[] { new UTF8Encoding(true, false) };
yield return new object[] { new UTF8Encoding(false, false) };
yield return new object[] { new ASCIIEncoding() };
yield return new object[] { new UTF32Encoding(true, true, true) };
yield return new object[] { new UTF32Encoding(true, true, false) };
yield return new object[] { new UTF32Encoding(true, false, false) };
yield return new object[] { new UTF32Encoding(true, false, true) };
yield return new object[] { new UTF32Encoding(false, true, true) };
yield return new object[] { new UTF32Encoding(false, true, false) };
yield return new object[] { new UTF32Encoding(false, false, false) };
yield return new object[] { new UTF32Encoding(false, false, true) };
yield return new object[] { Encoding.GetEncoding("latin1") };
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static unsafe void GetByteCount_Invalid(Encoding encoding)
{
// Chars is null
Assert.Throws<ArgumentNullException>(encoding is ASCIIEncoding ? "chars" : "s", () => encoding.GetByteCount((string)null));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount((char[])null));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount((char[])null, 0, 0));
// Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetByteCount(new char[3], -1, 0));
// Count < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetByteCount(new char[3], 0, -1));
// Index + count > chars.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 0, 4));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 1, 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 2, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 3, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetByteCount(new char[3], 4, 0));
char[] chars = new char[3];
fixed (char* pChars = chars)
{
char* pCharsLocal = pChars;
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetByteCount(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetByteCount(pCharsLocal, -1));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static unsafe void GetBytes_Invalid(Encoding encoding)
{
string expectedStringParamName = encoding is ASCIIEncoding ? "chars" : "s";
// Source is null
AssertExtensions.Throws<ArgumentNullException>("s", () => encoding.GetBytes((string)null));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null, 0, 0));
Assert.Throws<ArgumentNullException>(expectedStringParamName, () => encoding.GetBytes((string)null, 0, 0, new byte[1], 0));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char[])null, 0, 0, new byte[1], 0));
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes("abc", 0, 3, null, 0));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes(new char[3], 0, 3, null, 0));
// Char index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetBytes(new char[1], -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetBytes("a", -1, 0, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetBytes(new char[1], -1, 0, new byte[1], 0));
// Char count < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetBytes(new char[1], 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes("a", 0, -1, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes(new char[1], 0, -1, new byte[1], 0));
// Char index + count > source.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 2, 0));
Assert.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 2, 0, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 2, 0, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 1, 1));
Assert.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 1, 1, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 1, 1, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 0, 2));
Assert.Throws<ArgumentOutOfRangeException>(expectedStringParamName, () => encoding.GetBytes("a", 0, 2, new byte[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoding.GetBytes(new char[1], 0, 2, new byte[1], 0));
// Byte index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes("a", 0, 1, new byte[1], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes(new char[1], 0, 1, new byte[1], -1));
// Byte index > bytes.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes("a", 0, 1, new byte[1], 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetBytes(new char[1], 0, 1, new byte[1], 2));
// Bytes does not have enough capacity to accomodate result
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("a", 0, 1, new byte[0], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("abc", 0, 3, new byte[1], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("\uD800\uDC00", 0, 2, new byte[1], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(new char[1], 0, 1, new byte[0], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(new char[3], 0, 3, new byte[1], 0));
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes("\uD800\uDC00".ToCharArray(), 0, 2, new byte[1], 0));
char[] chars = new char[3];
byte[] bytes = new byte[3];
byte[] smallBytes = new byte[1];
fixed (char* pChars = chars)
fixed (byte* pBytes = bytes)
fixed (byte* pSmallBytes = smallBytes)
{
char* pCharsLocal = pChars;
byte* pBytesLocal = pBytes;
byte* pSmallBytesLocal = pSmallBytes;
// Bytes or chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetBytes((char*)null, 0, pBytesLocal, bytes.Length));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetBytes(pCharsLocal, chars.Length, (byte*)null, bytes.Length));
// CharCount or byteCount is negative
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetBytes(pCharsLocal, -1, pBytesLocal, bytes.Length));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetBytes(pCharsLocal, chars.Length, pBytesLocal, -1));
// Bytes does not have enough capacity to accomodate result
AssertExtensions.Throws<ArgumentException>("bytes", () => encoding.GetBytes(pCharsLocal, chars.Length, pSmallBytesLocal, smallBytes.Length));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static unsafe void GetCharCount_Invalid(Encoding encoding)
{
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null, 0, 0));
// Index or count < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetCharCount(new byte[4], -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetCharCount(new byte[4], 0, -1));
// Index + count > bytes.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 5, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 4, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 3, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 2, 3));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 1, 4));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetCharCount(new byte[4], 0, 5));
byte[] bytes = new byte[4];
fixed (byte* pBytes = bytes)
{
byte* pBytesLocal = pBytes;
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetCharCount(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetCharCount(pBytesLocal, -1));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static unsafe void GetChars_Invalid(Encoding encoding)
{
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null, 0, 0));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars(null, 0, 0, new char[0], 0));
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetChars(new byte[4], 0, 4, null, 0));
// Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoding.GetChars(new byte[4], -1, 4));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoding.GetChars(new byte[4], -1, 4, new char[1], 0));
// Count < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoding.GetChars(new byte[4], 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetChars(new byte[4], 0, -1, new char[1], 0));
// Count > bytes.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 0, 5));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 0, 5, new char[1], 0));
// Index + count > bytes.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 5, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 5, 0, new char[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 4, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 4, 1, new char[1], 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 3, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetChars(new byte[4], 3, 2, new char[1], 0));
// CharIndex < 0 or >= chars.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetChars(new byte[4], 0, 4, new char[1], -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoding.GetChars(new byte[4], 0, 4, new char[1], 2));
// Chars does not have enough capacity to accomodate result
AssertExtensions.Throws<ArgumentException>("chars", () => encoding.GetChars(new byte[4], 0, 4, new char[1], 1));
byte[] bytes = new byte[encoding.GetMaxByteCount(2)];
char[] chars = new char[4];
char[] smallChars = new char[1];
fixed (byte* pBytes = bytes)
fixed (char* pChars = chars)
fixed (char* pSmallChars = smallChars)
{
byte* pBytesLocal = pBytes;
char* pCharsLocal = pChars;
char* pSmallCharsLocal = pSmallChars;
// Bytes or chars is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetChars((byte*)null, 0, pCharsLocal, chars.Length));
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoding.GetChars(pBytesLocal, bytes.Length, (char*)null, chars.Length));
// ByteCount or charCount is negative
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetChars(pBytesLocal, -1, pCharsLocal, chars.Length));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetChars(pBytesLocal, bytes.Length, pCharsLocal, -1));
// Chars does not have enough capacity to accomodate result
AssertExtensions.Throws<ArgumentException>("chars", () => encoding.GetChars(pBytesLocal, bytes.Length, pSmallCharsLocal, smallChars.Length));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static void GetMaxByteCount_Invalid(Encoding encoding)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(-1));
if (!encoding.IsSingleByte)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(int.MaxValue / 2));
}
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoding.GetMaxByteCount(int.MaxValue));
// Make sure that GetMaxByteCount respects the MaxCharCount property of EncoderFallback
// However, Utf7Encoding ignores this
if (!(encoding is UTF7Encoding))
{
Encoding customizedMaxCharCountEncoding = Encoding.GetEncoding(encoding.CodePage, new HighMaxCharCountEncoderFallback(), DecoderFallback.ReplacementFallback);
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => customizedMaxCharCountEncoding.GetMaxByteCount(2));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static void GetMaxCharCount_Invalid(Encoding encoding)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetMaxCharCount(-1));
// TODO: find a more generic way to find what byteCount is invalid
if (encoding is UTF8Encoding)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoding.GetMaxCharCount(int.MaxValue));
}
// Make sure that GetMaxCharCount respects the MaxCharCount property of DecoderFallback
// However, Utf7Encoding ignores this
if (!(encoding is UTF7Encoding) && !(encoding is UTF32Encoding))
{
Encoding customizedMaxCharCountEncoding = Encoding.GetEncoding(encoding.CodePage, EncoderFallback.ReplacementFallback, new HighMaxCharCountDecoderFallback());
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => customizedMaxCharCountEncoding.GetMaxCharCount(2));
}
}
[Theory]
[MemberData(nameof(Encodings_TestData))]
public static void GetString_Invalid(Encoding encoding)
{
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetString(null));
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoding.GetString(null, 0, 0));
// Index or count < 0
Assert.Throws<ArgumentOutOfRangeException>(encoding is ASCIIEncoding ? "byteIndex" : "index", () => encoding.GetString(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(encoding is ASCIIEncoding ? "byteCount" : "count", () => encoding.GetString(new byte[1], 0, -1));
// Index + count > bytes.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 2, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoding.GetString(new byte[1], 0, 2));
}
public static unsafe void Encode_Invalid(Encoding encoding, string chars, int index, int count)
{
Assert.Equal(EncoderFallback.ExceptionFallback, encoding.EncoderFallback);
char[] charsArray = chars.ToCharArray();
byte[] bytes = new byte[encoding.GetMaxByteCount(count)];
if (index == 0 && count == chars.Length)
{
Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(chars));
Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(charsArray));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(chars));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray));
}
Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(charsArray, index, count));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray, index, count));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(chars, index, count, bytes, 0));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(charsArray, index, count, bytes, 0));
fixed (char* pChars = chars)
fixed (byte* pBytes = bytes)
{
char* pCharsLocal = pChars;
byte* pBytesLocal = pBytes;
Assert.Throws<EncoderFallbackException>(() => encoding.GetByteCount(pCharsLocal + index, count));
Assert.Throws<EncoderFallbackException>(() => encoding.GetBytes(pCharsLocal + index, count, pBytesLocal, bytes.Length));
}
}
public static unsafe void Decode_Invalid(Encoding encoding, byte[] bytes, int index, int count)
{
Assert.Equal(DecoderFallback.ExceptionFallback, encoding.DecoderFallback);
char[] chars = new char[encoding.GetMaxCharCount(count)];
if (index == 0 && count == bytes.Length)
{
Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(bytes));
Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes));
Assert.Throws<DecoderFallbackException>(() => encoding.GetString(bytes));
}
Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(bytes, index, count));
Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes, index, count));
Assert.Throws<DecoderFallbackException>(() => encoding.GetString(bytes, index, count));
Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(bytes, index, count, chars, 0));
fixed (byte* pBytes = bytes)
fixed (char* pChars = chars)
{
byte* pBytesLocal = pBytes;
char* pCharsLocal = pChars;
Assert.Throws<DecoderFallbackException>(() => encoding.GetCharCount(pBytesLocal + index, count));
Assert.Throws<DecoderFallbackException>(() => encoding.GetChars(pBytesLocal + index, count, pCharsLocal, chars.Length));
Assert.Throws<DecoderFallbackException>(() => encoding.GetString(pBytesLocal + index, count));
}
}
public static IEnumerable<object[]> Encoders_TestData()
{
foreach (object[] encodingTestData in Encodings_TestData())
{
Encoding encoding = (Encoding)encodingTestData[0];
yield return new object[] { encoding.GetEncoder(), true };
yield return new object[] { encoding.GetEncoder(), false };
}
}
[Theory]
[MemberData(nameof(Encoders_TestData))]
public static void Encoder_GetByteCount_Invalid(Encoder encoder, bool flush)
{
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.GetByteCount(null, 0, 0, flush));
// Index is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => encoder.GetByteCount(new char[4], -1, 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 5, 0, flush));
// Count is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => encoder.GetByteCount(new char[4], 0, -1, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 0, 5, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetByteCount(new char[4], 1, 4, flush));
}
[Theory]
[MemberData(nameof(Encoders_TestData))]
public static void Encoder_GetBytes_Invalid(Encoder encoder, bool flush)
{
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.GetBytes(null, 0, 0, new byte[4], 0, flush));
// CharIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoder.GetBytes(new char[4], -1, 0, new byte[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 5, 0, new byte[4], 0, flush));
// CharCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoder.GetBytes(new char[4], 0, -1, new byte[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 0, 5, new byte[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.GetBytes(new char[4], 1, 4, new byte[4], 0, flush));
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoder.GetBytes(new char[1], 0, 1, null, 0, flush));
// ByteIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.GetBytes(new char[1], 0, 1, new byte[4], -1, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.GetBytes(new char[1], 0, 1, new byte[4], 5, flush));
// Bytes does not have enough space
int byteCount = encoder.GetByteCount(new char[] { 'a' }, 0, 1, flush);
AssertExtensions.Throws<ArgumentException>("bytes", () => encoder.GetBytes(new char[] { 'a' }, 0, 1, new byte[byteCount - 1], 0, flush));
}
[Theory]
[MemberData(nameof(Encoders_TestData))]
public static void Encoder_Convert_Invalid(Encoder encoder, bool flush)
{
int charsUsed = 0;
int bytesUsed = 0;
bool completed = false;
Action verifyOutParams = () =>
{
Assert.Equal(0, charsUsed);
Assert.Equal(0, bytesUsed);
Assert.False(completed);
};
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => encoder.Convert(null, 0, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// CharIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => encoder.Convert(new char[4], -1, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 5, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// CharCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => encoder.Convert(new char[4], 0, -1, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 0, 5, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 1, 4, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => encoder.Convert(new char[1], 0, 1, null, 0, 0, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// ByteIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => encoder.Convert(new char[1], 0, 0, new byte[4], -1, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 5, 0, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// ByteCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => encoder.Convert(new char[1], 0, 0, new byte[4], 0, -1, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 0, 5, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 1, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// Bytes does not have enough space
int byteCount = encoder.GetByteCount(new char[] { 'a' }, 0, 1, flush);
AssertExtensions.Throws<ArgumentException>("bytes", () => encoder.Convert(new char[] { 'a' }, 0, 1, new byte[byteCount - 1], 0, byteCount - 1, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
}
public static IEnumerable<object[]> Decoders_TestData()
{
foreach (object[] encodingTestData in Encodings_TestData())
{
Encoding encoding = (Encoding)encodingTestData[0];
yield return new object[] { encoding, encoding.GetDecoder(), true };
yield return new object[] { encoding, encoding.GetDecoder(), false };
}
}
[Theory]
[MemberData(nameof(Decoders_TestData))]
public static void Decoder_GetCharCount_Invalid(Encoding _, Decoder decoder, bool flush)
{
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.GetCharCount(null, 0, 0, flush));
// Index is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => decoder.GetCharCount(new byte[4], -1, 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 5, 0, flush));
// Count is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => decoder.GetCharCount(new byte[4], 0, -1, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 0, 5, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetCharCount(new byte[4], 1, 4, flush));
}
[Theory]
[MemberData(nameof(Decoders_TestData))]
public static void Decoder_GetChars_Invalid(Encoding _, Decoder decoder, bool flush)
{
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.GetChars(null, 0, 0, new char[4], 0, flush));
// ByteIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => decoder.GetChars(new byte[4], -1, 0, new char[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte[4], 5, 0, new char[4], 0, flush));
// ByteCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => decoder.GetChars(new byte[4], 0, -1, new char[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte[4], 0, 5, new char[4], 0, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.GetChars(new byte
[4], 1, 4, new char[4], 0, flush));
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => decoder.GetChars(new byte[1], 0, 1, null, 0, flush));
// CharIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.GetChars(new byte[1], 0, 1, new char[4], -1, flush));
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.GetChars(new byte[1], 0, 1, new char[4], 5, flush));
// Chars does not have enough space
int charCount = decoder.GetCharCount(new byte[4], 0, 4, flush);
AssertExtensions.Throws<ArgumentException>("chars", () => decoder.GetChars(new byte[4], 0, 4, new char[charCount - 1], 0, flush));
}
[Theory]
[MemberData(nameof(Decoders_TestData))]
public static void Decoder_Convert_Invalid(Encoding encoding, Decoder decoder, bool flush)
{
int bytesUsed = 0;
int charsUsed = 0;
bool completed = false;
Action verifyOutParams = () =>
{
Assert.Equal(0, bytesUsed);
Assert.Equal(0, charsUsed);
Assert.False(completed);
};
// Bytes is null
AssertExtensions.Throws<ArgumentNullException>("bytes", () => decoder.Convert(null, 0, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// ByteIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteIndex", () => decoder.Convert(new byte[4], -1, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 5, 0, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// ByteCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("byteCount", () => decoder.Convert(new byte[4], 0, -1, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 0, 5, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytes", () => decoder.Convert(new byte[4], 1, 4, new char[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// Chars is null
AssertExtensions.Throws<ArgumentNullException>("chars", () => decoder.Convert(new byte[1], 0, 1, null, 0, 0, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// CharIndex is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charIndex", () => decoder.Convert(new byte[1], 0, 0, new char[4], -1, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 5, 0, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// CharCount is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => decoder.Convert(new byte[1], 0, 0, new char[4], 0, -1, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 0, 5, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
AssertExtensions.Throws<ArgumentOutOfRangeException>("chars", () => decoder.Convert(new byte[1], 0, 0, new char[4], 1, 4, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
// Chars does not have enough space
AssertExtensions.Throws<ArgumentException>("chars", () => decoder.Convert(new byte[4], 0, 4, new char[0], 0, 0, flush, out charsUsed, out bytesUsed, out completed));
verifyOutParams();
}
}
public class HighMaxCharCountEncoderFallback : EncoderFallback
{
public override int MaxCharCount => int.MaxValue;
public override EncoderFallbackBuffer CreateFallbackBuffer() => ReplacementFallback.CreateFallbackBuffer();
}
public class HighMaxCharCountDecoderFallback : DecoderFallback
{
public override int MaxCharCount => int.MaxValue;
public override DecoderFallbackBuffer CreateFallbackBuffer() => ReplacementFallback.CreateFallbackBuffer();
}
}
| |
namespace ExpandingHeaderGroupsStack
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.menuOffice2010 = new System.Windows.Forms.ToolStripMenuItem();
this.menuOffice2007 = new System.Windows.Forms.ToolStripMenuItem();
this.menuSparkle = new System.Windows.Forms.ToolStripMenuItem();
this.menuSystem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStrip = new System.Windows.Forms.ToolStrip();
this.toolOffice2010 = new System.Windows.Forms.ToolStripButton();
this.toolOffice2007 = new System.Windows.Forms.ToolStripButton();
this.toolSparkle = new System.Windows.Forms.ToolStripButton();
this.toolSystem = new System.Windows.Forms.ToolStripButton();
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.kryptonPanelMain = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.kryptonGroupFiller = new ComponentFactory.Krypton.Toolkit.KryptonGroup();
this.textBoxFiller = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.kryptonBorderEdgeBottom = new ComponentFactory.Krypton.Toolkit.KryptonBorderEdge();
this.kryptonHeaderBottom = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup();
this.buttonSpecBottom = new ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup();
this.kryptonButtonPrevious = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.textBoxFind = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.kryptonButtonNext = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.labelFind = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonBorderEdgeTop = new ComponentFactory.Krypton.Toolkit.KryptonBorderEdge();
this.kryptonHeaderTop = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup();
this.buttonSpecHeaderGroup1 = new ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup();
this.textBox3 = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.textBox2 = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.labelPosition = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.labelAge = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.textBox1 = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.textBoxFirstName = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.labelLastName = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.labelFirstName = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonManager = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components);
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.menuStrip.SuspendLayout();
this.toolStrip.SuspendLayout();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanelMain)).BeginInit();
this.kryptonPanelMain.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonGroupFiller)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonGroupFiller.Panel)).BeginInit();
this.kryptonGroupFiller.Panel.SuspendLayout();
this.kryptonGroupFiller.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderBottom)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderBottom.Panel)).BeginInit();
this.kryptonHeaderBottom.Panel.SuspendLayout();
this.kryptonHeaderBottom.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderTop)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderTop.Panel)).BeginInit();
this.kryptonHeaderTop.Panel.SuspendLayout();
this.kryptonHeaderTop.SuspendLayout();
this.SuspendLayout();
//
// menuStrip
//
this.menuStrip.Font = new System.Drawing.Font("Segoe UI", 9F);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem1});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(352, 24);
this.menuStrip.TabIndex = 0;
this.menuStrip.Text = "menuStrip";
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuOffice2010,
this.menuOffice2007,
this.menuSparkle,
this.menuSystem,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(37, 20);
this.toolStripMenuItem1.Text = "File";
//
// menuOffice2010
//
this.menuOffice2010.Checked = true;
this.menuOffice2010.CheckState = System.Windows.Forms.CheckState.Checked;
this.menuOffice2010.Name = "menuOffice2010";
this.menuOffice2010.Size = new System.Drawing.Size(167, 22);
this.menuOffice2010.Text = "Office 2010 - Blue";
this.menuOffice2010.Click += new System.EventHandler(this.toolOffice2010_Click);
//
// menuOffice2007
//
this.menuOffice2007.Name = "menuOffice2007";
this.menuOffice2007.Size = new System.Drawing.Size(167, 22);
this.menuOffice2007.Text = "Office 2007 - Blue";
this.menuOffice2007.Click += new System.EventHandler(this.toolOffice2007_Click);
//
// menuSparkle
//
this.menuSparkle.Name = "menuSparkle";
this.menuSparkle.Size = new System.Drawing.Size(167, 22);
this.menuSparkle.Text = "Sparkle - Blue";
this.menuSparkle.Click += new System.EventHandler(this.toolSparkle_Click);
//
// menuSystem
//
this.menuSystem.Name = "menuSystem";
this.menuSystem.Size = new System.Drawing.Size(167, 22);
this.menuSystem.Text = "System";
this.menuSystem.Click += new System.EventHandler(this.toolSystem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(164, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(167, 22);
this.exitToolStripMenuItem.Text = "Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// toolStrip
//
this.toolStrip.Dock = System.Windows.Forms.DockStyle.None;
this.toolStrip.Font = new System.Drawing.Font("Segoe UI", 9F);
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolOffice2010,
this.toolOffice2007,
this.toolSparkle,
this.toolSystem});
this.toolStrip.Location = new System.Drawing.Point(3, 0);
this.toolStrip.Name = "toolStrip";
this.toolStrip.Size = new System.Drawing.Size(211, 25);
this.toolStrip.TabIndex = 1;
this.toolStrip.Text = "toolStrip";
//
// toolOffice2010
//
this.toolOffice2010.Checked = true;
this.toolOffice2010.CheckState = System.Windows.Forms.CheckState.Checked;
this.toolOffice2010.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolOffice2010.Image = ((System.Drawing.Image)(resources.GetObject("toolOffice2010.Image")));
this.toolOffice2010.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolOffice2010.Name = "toolOffice2010";
this.toolOffice2010.Size = new System.Drawing.Size(35, 22);
this.toolOffice2010.Text = "2010";
this.toolOffice2010.Click += new System.EventHandler(this.toolOffice2010_Click);
//
// toolOffice2007
//
this.toolOffice2007.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolOffice2007.Image = ((System.Drawing.Image)(resources.GetObject("toolOffice2007.Image")));
this.toolOffice2007.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolOffice2007.Name = "toolOffice2007";
this.toolOffice2007.Size = new System.Drawing.Size(35, 22);
this.toolOffice2007.Text = "2007";
this.toolOffice2007.Click += new System.EventHandler(this.toolOffice2007_Click);
//
// toolSparkle
//
this.toolSparkle.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolSparkle.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolSparkle.Name = "toolSparkle";
this.toolSparkle.Size = new System.Drawing.Size(49, 22);
this.toolSparkle.Text = "Sparkle";
this.toolSparkle.Click += new System.EventHandler(this.toolSparkle_Click);
//
// toolSystem
//
this.toolSystem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolSystem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolSystem.Name = "toolSystem";
this.toolSystem.Size = new System.Drawing.Size(49, 22);
this.toolSystem.Text = "System";
this.toolSystem.Click += new System.EventHandler(this.toolSystem_Click);
//
// toolStripContainer1
//
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.Controls.Add(this.kryptonPanelMain);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(352, 295);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 24);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.Size = new System.Drawing.Size(352, 320);
this.toolStripContainer1.TabIndex = 2;
this.toolStripContainer1.Text = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip);
//
// kryptonPanelMain
//
this.kryptonPanelMain.Controls.Add(this.kryptonGroupFiller);
this.kryptonPanelMain.Controls.Add(this.kryptonBorderEdgeBottom);
this.kryptonPanelMain.Controls.Add(this.kryptonHeaderBottom);
this.kryptonPanelMain.Controls.Add(this.kryptonBorderEdgeTop);
this.kryptonPanelMain.Controls.Add(this.kryptonHeaderTop);
this.kryptonPanelMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonPanelMain.Location = new System.Drawing.Point(0, 0);
this.kryptonPanelMain.Name = "kryptonPanelMain";
this.kryptonPanelMain.Padding = new System.Windows.Forms.Padding(5);
this.kryptonPanelMain.Size = new System.Drawing.Size(352, 295);
this.kryptonPanelMain.TabIndex = 0;
//
// kryptonGroupFiller
//
this.kryptonGroupFiller.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonGroupFiller.Location = new System.Drawing.Point(5, 98);
this.kryptonGroupFiller.Name = "kryptonGroupFiller";
//
// kryptonGroupFiller.Panel
//
this.kryptonGroupFiller.Panel.Controls.Add(this.textBoxFiller);
this.kryptonGroupFiller.Panel.Padding = new System.Windows.Forms.Padding(3);
this.kryptonGroupFiller.Size = new System.Drawing.Size(342, 120);
this.kryptonGroupFiller.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonGroupFiller.StateCommon.Border.GraphicsHint = ComponentFactory.Krypton.Toolkit.PaletteGraphicsHint.None;
this.kryptonGroupFiller.TabIndex = 1;
//
// textBoxFiller
//
this.textBoxFiller.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxFiller.Location = new System.Drawing.Point(3, 3);
this.textBoxFiller.Multiline = true;
this.textBoxFiller.Name = "textBoxFiller";
this.textBoxFiller.Size = new System.Drawing.Size(334, 114);
this.textBoxFiller.StateCommon.Border.Draw = ComponentFactory.Krypton.Toolkit.InheritBool.False;
this.textBoxFiller.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.textBoxFiller.TabIndex = 0;
this.textBoxFiller.Text = resources.GetString("textBoxFiller.Text");
//
// kryptonBorderEdgeBottom
//
this.kryptonBorderEdgeBottom.Dock = System.Windows.Forms.DockStyle.Bottom;
this.kryptonBorderEdgeBottom.Location = new System.Drawing.Point(5, 218);
this.kryptonBorderEdgeBottom.Name = "kryptonBorderEdgeBottom";
this.kryptonBorderEdgeBottom.Size = new System.Drawing.Size(342, 1);
this.kryptonBorderEdgeBottom.StateCommon.GraphicsHint = ComponentFactory.Krypton.Toolkit.PaletteGraphicsHint.None;
this.kryptonBorderEdgeBottom.Text = "kryptonBorderEdge1";
//
// kryptonHeaderBottom
//
this.kryptonHeaderBottom.AutoSize = true;
this.kryptonHeaderBottom.ButtonSpecs.AddRange(new ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup[] {
this.buttonSpecBottom});
this.kryptonHeaderBottom.CollapseTarget = ComponentFactory.Krypton.Toolkit.HeaderGroupCollapsedTarget.CollapsedToSecondary;
this.kryptonHeaderBottom.Dock = System.Windows.Forms.DockStyle.Bottom;
this.kryptonHeaderBottom.GroupBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.PanelAlternate;
this.kryptonHeaderBottom.HeaderStyleSecondary = ComponentFactory.Krypton.Toolkit.HeaderStyle.Primary;
this.kryptonHeaderBottom.HeaderVisiblePrimary = false;
this.kryptonHeaderBottom.Location = new System.Drawing.Point(5, 219);
this.kryptonHeaderBottom.Name = "kryptonHeaderBottom";
//
// kryptonHeaderBottom.Panel
//
this.kryptonHeaderBottom.Panel.Controls.Add(this.kryptonButtonPrevious);
this.kryptonHeaderBottom.Panel.Controls.Add(this.textBoxFind);
this.kryptonHeaderBottom.Panel.Controls.Add(this.kryptonButtonNext);
this.kryptonHeaderBottom.Panel.Controls.Add(this.labelFind);
this.kryptonHeaderBottom.Panel.Padding = new System.Windows.Forms.Padding(5);
this.kryptonHeaderBottom.Size = new System.Drawing.Size(342, 71);
this.kryptonHeaderBottom.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)(((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonHeaderBottom.TabIndex = 2;
this.kryptonHeaderBottom.ValuesPrimary.Heading = "";
this.kryptonHeaderBottom.ValuesPrimary.Image = null;
this.kryptonHeaderBottom.ValuesSecondary.Heading = "Bottom HeaderGroup";
this.kryptonHeaderBottom.ValuesSecondary.Image = ((System.Drawing.Image)(resources.GetObject("kryptonHeaderBottom.ValuesSecondary.Image")));
this.kryptonHeaderBottom.CollapsedChanged += new System.EventHandler(this.kryptonHeaderBottom_CollapsedChanged);
//
// buttonSpecBottom
//
this.buttonSpecBottom.HeaderLocation = ComponentFactory.Krypton.Toolkit.HeaderLocation.SecondaryHeader;
this.buttonSpecBottom.Type = ComponentFactory.Krypton.Toolkit.PaletteButtonSpecStyle.ArrowDown;
this.buttonSpecBottom.UniqueName = "A07748CCD08E4E46A07748CCD08E4E46";
//
// kryptonButtonPrevious
//
this.kryptonButtonPrevious.AutoSize = true;
this.kryptonButtonPrevious.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kryptonButtonPrevious.Location = new System.Drawing.Point(229, 10);
this.kryptonButtonPrevious.Name = "kryptonButtonPrevious";
this.kryptonButtonPrevious.Size = new System.Drawing.Size(44, 23);
this.kryptonButtonPrevious.TabIndex = 5;
this.kryptonButtonPrevious.Values.Text = "< Prev";
//
// textBoxFind
//
this.textBoxFind.Location = new System.Drawing.Point(49, 10);
this.textBoxFind.Name = "textBoxFind";
this.textBoxFind.Size = new System.Drawing.Size(171, 20);
this.textBoxFind.TabIndex = 4;
this.textBoxFind.Text = "example string";
//
// kryptonButtonNext
//
this.kryptonButtonNext.AutoSize = true;
this.kryptonButtonNext.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kryptonButtonNext.Location = new System.Drawing.Point(283, 10);
this.kryptonButtonNext.Name = "kryptonButtonNext";
this.kryptonButtonNext.Size = new System.Drawing.Size(46, 23);
this.kryptonButtonNext.TabIndex = 6;
this.kryptonButtonNext.Values.Text = "Next >";
//
// labelFind
//
this.labelFind.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel;
this.labelFind.Location = new System.Drawing.Point(11, 11);
this.labelFind.Name = "labelFind";
this.labelFind.Size = new System.Drawing.Size(32, 19);
this.labelFind.TabIndex = 3;
this.labelFind.Values.Text = "Text";
//
// kryptonBorderEdgeTop
//
this.kryptonBorderEdgeTop.Dock = System.Windows.Forms.DockStyle.Top;
this.kryptonBorderEdgeTop.Location = new System.Drawing.Point(5, 97);
this.kryptonBorderEdgeTop.Name = "kryptonBorderEdgeTop";
this.kryptonBorderEdgeTop.Size = new System.Drawing.Size(342, 1);
this.kryptonBorderEdgeTop.StateCommon.GraphicsHint = ComponentFactory.Krypton.Toolkit.PaletteGraphicsHint.None;
this.kryptonBorderEdgeTop.Text = "kryptonBorderEdge1";
//
// kryptonHeaderTop
//
this.kryptonHeaderTop.AutoSize = true;
this.kryptonHeaderTop.ButtonSpecs.AddRange(new ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup[] {
this.buttonSpecHeaderGroup1});
this.kryptonHeaderTop.Dock = System.Windows.Forms.DockStyle.Top;
this.kryptonHeaderTop.GroupBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.PanelAlternate;
this.kryptonHeaderTop.HeaderVisibleSecondary = false;
this.kryptonHeaderTop.Location = new System.Drawing.Point(5, 5);
this.kryptonHeaderTop.Name = "kryptonHeaderTop";
//
// kryptonHeaderTop.Panel
//
this.kryptonHeaderTop.Panel.Controls.Add(this.textBox3);
this.kryptonHeaderTop.Panel.Controls.Add(this.textBox2);
this.kryptonHeaderTop.Panel.Controls.Add(this.labelPosition);
this.kryptonHeaderTop.Panel.Controls.Add(this.labelAge);
this.kryptonHeaderTop.Panel.Controls.Add(this.textBox1);
this.kryptonHeaderTop.Panel.Controls.Add(this.textBoxFirstName);
this.kryptonHeaderTop.Panel.Controls.Add(this.labelLastName);
this.kryptonHeaderTop.Panel.Controls.Add(this.labelFirstName);
this.kryptonHeaderTop.Panel.Padding = new System.Windows.Forms.Padding(5);
this.kryptonHeaderTop.Size = new System.Drawing.Size(342, 92);
this.kryptonHeaderTop.StateCommon.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)(((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonHeaderTop.TabIndex = 0;
this.kryptonHeaderTop.ValuesPrimary.Heading = "Top HeaderGroup";
this.kryptonHeaderTop.ValuesPrimary.Image = ((System.Drawing.Image)(resources.GetObject("kryptonHeaderTop.ValuesPrimary.Image")));
this.kryptonHeaderTop.CollapsedChanged += new System.EventHandler(this.kryptonHeaderTop_CollapsedChanged);
//
// buttonSpecHeaderGroup1
//
this.buttonSpecHeaderGroup1.Type = ComponentFactory.Krypton.Toolkit.PaletteButtonSpecStyle.ArrowUp;
this.buttonSpecHeaderGroup1.UniqueName = "A07748CCD08E4E46A07748CCD08E4E46";
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(236, 34);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(94, 20);
this.textBox3.TabIndex = 10;
this.textBox3.Text = "Roman Emperor";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(236, 7);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(94, 20);
this.textBox2.TabIndex = 7;
this.textBox2.Text = "24";
//
// labelPosition
//
this.labelPosition.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel;
this.labelPosition.Location = new System.Drawing.Point(183, 35);
this.labelPosition.Name = "labelPosition";
this.labelPosition.Size = new System.Drawing.Size(52, 19);
this.labelPosition.TabIndex = 12;
this.labelPosition.Values.Text = "Position";
//
// labelAge
//
this.labelAge.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel;
this.labelAge.Location = new System.Drawing.Point(182, 10);
this.labelAge.Name = "labelAge";
this.labelAge.Size = new System.Drawing.Size(31, 19);
this.labelAge.TabIndex = 11;
this.labelAge.Values.Text = "Age";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(81, 34);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(89, 20);
this.textBox1.TabIndex = 8;
this.textBox1.Text = "Ceaser";
//
// textBoxFirstName
//
this.textBoxFirstName.Location = new System.Drawing.Point(81, 7);
this.textBoxFirstName.Name = "textBoxFirstName";
this.textBoxFirstName.Size = new System.Drawing.Size(89, 20);
this.textBoxFirstName.TabIndex = 5;
this.textBoxFirstName.Text = "Augustus";
//
// labelLastName
//
this.labelLastName.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel;
this.labelLastName.Location = new System.Drawing.Point(11, 35);
this.labelLastName.Name = "labelLastName";
this.labelLastName.Size = new System.Drawing.Size(65, 19);
this.labelLastName.TabIndex = 9;
this.labelLastName.Values.Text = "Last Name";
//
// labelFirstName
//
this.labelFirstName.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel;
this.labelFirstName.Location = new System.Drawing.Point(11, 10);
this.labelFirstName.Name = "labelFirstName";
this.labelFirstName.Size = new System.Drawing.Size(66, 19);
this.labelFirstName.TabIndex = 6;
this.labelFirstName.Values.Text = "First Name";
//
// statusStrip1
//
this.statusStrip1.Font = new System.Drawing.Font("Segoe UI", 9F);
this.statusStrip1.Location = new System.Drawing.Point(0, 344);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode;
this.statusStrip1.Size = new System.Drawing.Size(352, 22);
this.statusStrip1.TabIndex = 3;
this.statusStrip1.Text = "statusStrip1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(352, 366);
this.Controls.Add(this.toolStripContainer1);
this.Controls.Add(this.menuStrip);
this.Controls.Add(this.statusStrip1);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(360, 372);
this.Name = "Form1";
this.Text = "Expanding HeaderGroups (Stack)";
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanelMain)).EndInit();
this.kryptonPanelMain.ResumeLayout(false);
this.kryptonPanelMain.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonGroupFiller.Panel)).EndInit();
this.kryptonGroupFiller.Panel.ResumeLayout(false);
this.kryptonGroupFiller.Panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonGroupFiller)).EndInit();
this.kryptonGroupFiller.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderBottom.Panel)).EndInit();
this.kryptonHeaderBottom.Panel.ResumeLayout(false);
this.kryptonHeaderBottom.Panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderBottom)).EndInit();
this.kryptonHeaderBottom.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderTop.Panel)).EndInit();
this.kryptonHeaderTop.Panel.ResumeLayout(false);
this.kryptonHeaderTop.Panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderTop)).EndInit();
this.kryptonHeaderTop.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanelMain;
private ComponentFactory.Krypton.Toolkit.KryptonGroup kryptonGroupFiller;
private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderTop;
private ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup buttonSpecHeaderGroup1;
private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderBottom;
private ComponentFactory.Krypton.Toolkit.ButtonSpecHeaderGroup buttonSpecBottom;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBoxFiller;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBox3;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBox2;
private ComponentFactory.Krypton.Toolkit.KryptonLabel labelPosition;
private ComponentFactory.Krypton.Toolkit.KryptonLabel labelAge;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBox1;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBoxFirstName;
private ComponentFactory.Krypton.Toolkit.KryptonLabel labelLastName;
private ComponentFactory.Krypton.Toolkit.KryptonLabel labelFirstName;
private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonPrevious;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox textBoxFind;
private ComponentFactory.Krypton.Toolkit.KryptonButton kryptonButtonNext;
private ComponentFactory.Krypton.Toolkit.KryptonLabel labelFind;
private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager;
private System.Windows.Forms.ToolStripButton toolSystem;
private System.Windows.Forms.ToolStripButton toolSparkle;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem menuSystem;
private System.Windows.Forms.ToolStripMenuItem menuSparkle;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private ComponentFactory.Krypton.Toolkit.KryptonBorderEdge kryptonBorderEdgeBottom;
private ComponentFactory.Krypton.Toolkit.KryptonBorderEdge kryptonBorderEdgeTop;
private System.Windows.Forms.ToolStripMenuItem menuOffice2010;
private System.Windows.Forms.ToolStripMenuItem menuOffice2007;
private System.Windows.Forms.ToolStripButton toolOffice2010;
private System.Windows.Forms.ToolStripButton toolOffice2007;
private System.Windows.Forms.StatusStrip statusStrip1;
}
}
| |
using System;
using System.Collections.Generic;
namespace Aardvark.Base
{
/// <summary>
/// A least-recently-used cache, with specifyable capacity and per-item size-, read-, and delete
/// function. The indexer is used to access items. Capacity can be changed on the fly. All
/// operations are synchronized for use in multi-threaded applications.
/// </summary>
public class LruCache<TKey, TValue>
{
private class Entry
{
public long Time;
public long Size;
public int Index;
public TKey Key;
public TValue Value;
public Action DeleteAct;
}
private object m_lock;
private Dict<TKey, Entry> m_cache;
private List<Entry> m_heap;
private Func<TKey, long> m_sizeFun;
private Func<TKey,TValue> m_readFun;
private Action<TKey,TValue> m_deleteAct;
private long m_capacity;
private long m_time;
private long m_size;
/// <summary>
/// Creates an LruCache with the specified capacity, per-item (Key) size function,
/// per-item (Key) read function, and per-item (key/value) delete action.
/// The indexer is used to access items. Capacity can be changed on the fly. All
/// operations are synchronized for use in multi-threaded applications.
/// </summary>
public LruCache(
long capacity,
Func<TKey, long> sizeFun,
Func<TKey,TValue> readFun,
Action<TKey, TValue> deleteAct = null
)
{
m_lock = new object();
m_cache = new Dict<TKey, Entry>();
m_heap = new List<Entry>();
m_sizeFun = sizeFun;
m_readFun = readFun;
m_deleteAct = deleteAct;
m_capacity = capacity;
m_time = 0;
m_size = 0;
}
public LruCache(
long capacity
)
{
m_lock = new object();
m_cache = new Dict<TKey, Entry>();
m_heap = new List<Entry>();
m_sizeFun = null;
m_readFun = null;
m_deleteAct = null;
m_capacity = capacity;
m_time = 0;
m_size = 0;
}
public long Capacity
{
get
{
return m_capacity;
}
set
{
lock (m_lock)
{
m_capacity = value;
Shrink(m_size);
}
}
}
private void Shrink(long size)
{
while (size > m_capacity)
{
var removeKey = Dequeue(m_heap).Key;
if (m_cache.TryRemove(removeKey, out Entry entry))
{
m_deleteAct?.Invoke(removeKey, entry.Value);
entry.DeleteAct?.Invoke();
size -= entry.Size;
}
else
throw new InvalidOperationException("tried to remove an item that is not in the cache");
// this should never ever happen!
}
m_size = size;
}
/// <summary>
/// Accessing items in the cache. If an item is not encountred in the cache,
/// it is read using the read function that was specified on cache creation.
/// </summary>
public TValue this [TKey key]
{
get
{
Entry entry;
lock (m_lock)
{
if (m_cache.TryGetValue(key, out entry))
{
entry.Time = ++m_time;
Sink(m_heap, entry.Index);
}
else
{
var size = m_sizeFun(key);
Shrink(m_size + size);
entry = new Entry
{
Time = ++m_time, Size = size, Key = key, Value = m_readFun(key)
};
m_cache[key] = entry;
Enqueue(m_heap, entry);
}
}
return entry.Value;
}
}
public TValue GetOrAdd(TKey key, long size, Func<TValue> valueFun, Action deleteAct = null)
{
lock (m_lock)
{
if (m_cache.TryGetValue(key, out Entry entry))
{
entry.Time = ++m_time;
Sink(m_heap, entry.Index);
}
else
{
Shrink(m_size + size);
entry = new Entry
{
Time = ++m_time,
Size = size,
Key = key,
Value = valueFun(),
DeleteAct = deleteAct,
};
m_cache[key] = entry;
Enqueue(m_heap, entry);
}
return entry.Value;
}
}
/// <summary>
/// Remove the entry with the supplied key from the hash.
/// Returns true on success and puts the value of the
/// entry into the out parameter.
/// </summary>
public bool TryRemove(TKey key, out TValue value)
{
lock (m_lock)
{
if (m_cache.TryRemove(key, out Entry entry))
{
m_size -= entry.Size;
RemoveAt(m_heap, entry.Index);
if (m_deleteAct != null)
m_deleteAct(key, entry.Value);
value = entry.Value;
return true;
}
value = default;
return false;
}
}
/// <summary>
/// Remove the entry with the supplied key from the hash.
/// Returns true on success.
/// </summary>
public bool Remove(TKey key)
{
lock (m_lock)
{
if (m_cache.TryRemove(key, out Entry entry))
{
m_size -= entry.Size;
RemoveAt(m_heap, entry.Index);
m_deleteAct?.Invoke(key, entry.Value);
entry.DeleteAct?.Invoke();
return true;
}
return false;
}
}
/// <summary>
/// Reomves an arbitrary element from the heap, and maintains the heap
/// conditions.
/// </summary>
private static void RemoveAt(List<Entry> heap, int index)
{
var count = heap.Count;
if (count == 1) { heap.Clear(); return; }
var element = heap[--count];
heap.RemoveAt(count);
if (index == count) return;
int i = index;
while (i > 0)
{
int i2 = (i - 1) / 2;
if (element.Time > heap[i2].Time) break;
heap[i] = heap[i2];
heap[i].Index = i;
i = i2;
}
if (i == index)
{
int i1 = 2 * i + 1;
while (i1 < count) // at least one child
{
int i2 = i1 + 1;
int ni = (i2 < count // two children?
&& heap[i1].Time > heap[i2].Time)
? i2 : i1; // smaller child
if (heap[ni].Time > element.Time) break;
heap[i] = heap[ni];
heap[i].Index = i;
i = ni; i1 = 2 * i + 1;
}
}
heap[i] = element;
heap[i].Index = i;
}
private static void Enqueue(List<Entry> heap, Entry entry)
{
int i = heap.Count;
heap.Add(entry);
entry.Index = i;
while (i > 0)
{
int i2 = (i - 1) / 2;
if (entry.Time > heap[i2].Time) break;
heap[i] = heap[i2];
heap[i].Index = i;
i = i2;
}
heap[i] = entry;
heap[i].Index = i;
}
/// <summary>
/// Removes and returns the item at the top of the heap (i.e. the
/// 0th position of the list).
/// </summary>
private static Entry Dequeue(List<Entry> heap)
{
var result = heap[0];
var count = heap.Count;
if (count == 1) { heap.Clear(); return result; }
var entry = heap[--count];
heap.RemoveAt(count);
int i = 0, i1 = 1;
while (i1 < count) // at least one child
{
int i2 = i1 + 1;
int ni = (i2 < count // two children?
&& heap[i1].Time > heap[i2].Time)
? i2 : i1; // smaller child
if (heap[ni].Time > entry.Time) break;
heap[i] = heap[ni];
heap[i].Index = i; // track index
i = ni; i1 = 2 * i + 1;
}
heap[i] = entry;
heap[i].Index = i; // track index
return result;
}
/// <summary>
/// Sinks an item.
/// </summary>
private static void Sink(List<Entry> heap, int i)
{
var count = heap.Count;
var entry = heap[i];
int i1 = 2 * i + 1;
while (i1 < count) // at least one child
{
int i2 = i1 + 1;
int ni = (i2 < count // two children?
&& heap[i1].Time > heap[i2].Time)
? i2 : i1; // smaller child
if (heap[ni].Time > entry.Time) break;
heap[i] = heap[ni];
heap[i].Index = i; // track index
i = ni; i1 = 2 * i + 1;
}
heap[i] = entry;
heap[i].Index = i; // track index
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Dynamic.Utils;
namespace System.Linq.Expressions.Compiler
{
// The part of the LambdaCompiler dealing with low level control flow
// break, continue, return, exceptions, etc
internal partial class LambdaCompiler
{
private LabelInfo EnsureLabel(LabelTarget node)
{
LabelInfo result;
if (!_labelInfo.TryGetValue(node, out result))
{
_labelInfo.Add(node, result = new LabelInfo(_ilg, node, false));
}
return result;
}
private LabelInfo ReferenceLabel(LabelTarget node)
{
LabelInfo result = EnsureLabel(node);
result.Reference(_labelBlock);
return result;
}
private LabelInfo DefineLabel(LabelTarget node)
{
if (node == null)
{
return new LabelInfo(_ilg, null, false);
}
LabelInfo result = EnsureLabel(node);
result.Define(_labelBlock);
return result;
}
private void PushLabelBlock(LabelScopeKind type)
{
_labelBlock = new LabelScopeInfo(_labelBlock, type);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")]
private void PopLabelBlock(LabelScopeKind kind)
{
Debug.Assert(_labelBlock != null && _labelBlock.Kind == kind);
_labelBlock = _labelBlock.Parent;
}
private void EmitLabelExpression(Expression expr, CompilationFlags flags)
{
var node = (LabelExpression)expr;
Debug.Assert(node.Target != null);
// If we're an immediate child of a block, our label will already
// be defined. If not, we need to define our own block so this
// label isn't exposed except to its own child expression.
LabelInfo label = null;
if (_labelBlock.Kind == LabelScopeKind.Block)
{
_labelBlock.TryGetLabelInfo(node.Target, out label);
// We're in a block but didn't find our label, try switch
if (label == null && _labelBlock.Parent.Kind == LabelScopeKind.Switch)
{
_labelBlock.Parent.TryGetLabelInfo(node.Target, out label);
}
// if we're in a switch or block, we should've found the label
Debug.Assert(label != null);
}
if (label == null)
{
label = DefineLabel(node.Target);
}
if (node.DefaultValue != null)
{
if (node.Target.Type == typeof(void))
{
EmitExpressionAsVoid(node.DefaultValue, flags);
}
else
{
flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart);
EmitExpression(node.DefaultValue, flags);
}
}
label.Mark();
}
private void EmitGotoExpression(Expression expr, CompilationFlags flags)
{
var node = (GotoExpression)expr;
LabelInfo labelInfo = ReferenceLabel(node.Target);
CompilationFlags tailCall = flags & CompilationFlags.EmitAsTailCallMask;
if (tailCall != CompilationFlags.EmitAsNoTail)
{
// Since tail call flags are not passed into EmitTryExpression, CanReturn
// means the goto will be emitted as Ret. Therefore we can emit the goto's
// default value with tail call. This can be improved by detecting if the
// target label is equivalent to the return label.
tailCall = labelInfo.CanReturn ? CompilationFlags.EmitAsTail : CompilationFlags.EmitAsNoTail;
flags = UpdateEmitAsTailCallFlag(flags, tailCall);
}
if (node.Value != null)
{
if (node.Target.Type == typeof(void))
{
EmitExpressionAsVoid(node.Value, flags);
}
else
{
flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart);
EmitExpression(node.Value, flags);
}
}
labelInfo.EmitJump();
EmitUnreachable(node, flags);
}
// We need to push default(T), unless we're emitting ourselves as
// void. Even though the code is unreachable, we still have to
// generate correct IL. We can get rid of this once we have better
// reachability analysis.
private void EmitUnreachable(Expression node, CompilationFlags flags)
{
if (node.Type != typeof(void) && (flags & CompilationFlags.EmitAsVoidType) == 0)
{
_ilg.EmitDefault(node.Type, this);
}
}
private bool TryPushLabelBlock(Expression node)
{
// Anything that is "statement-like" -- e.g. has no associated
// stack state can be jumped into, with the exception of try-blocks
// We indicate this by a "Block"
//
// Otherwise, we push an "Expression" to indicate that it can't be
// jumped into
switch (node.NodeType)
{
default:
if (_labelBlock.Kind != LabelScopeKind.Expression)
{
PushLabelBlock(LabelScopeKind.Expression);
return true;
}
return false;
case ExpressionType.Label:
// LabelExpression is a bit special, if it's directly in a
// block it becomes associate with the block's scope. Same
// thing if it's in a switch case body.
if (_labelBlock.Kind == LabelScopeKind.Block)
{
LabelTarget label = ((LabelExpression)node).Target;
if (_labelBlock.ContainsTarget(label))
{
return false;
}
if (_labelBlock.Parent.Kind == LabelScopeKind.Switch &&
_labelBlock.Parent.ContainsTarget(label))
{
return false;
}
}
PushLabelBlock(LabelScopeKind.Statement);
return true;
case ExpressionType.Block:
if (node is SpilledExpressionBlock)
{
// treat it as an expression
goto default;
}
PushLabelBlock(LabelScopeKind.Block);
// Labels defined immediately in the block are valid for
// the whole block.
if (_labelBlock.Parent.Kind != LabelScopeKind.Switch)
{
DefineBlockLabels(node);
}
return true;
case ExpressionType.Switch:
PushLabelBlock(LabelScopeKind.Switch);
// Define labels inside of the switch cases so they are in
// scope for the whole switch. This allows "goto case" and
// "goto default" to be considered as local jumps.
var @switch = (SwitchExpression)node;
foreach (SwitchCase c in @switch.Cases)
{
DefineBlockLabels(c.Body);
}
DefineBlockLabels(@switch.DefaultBody);
return true;
// Remove this when Convert(Void) goes away.
case ExpressionType.Convert:
if (node.Type != typeof(void))
{
// treat it as an expression
goto default;
}
PushLabelBlock(LabelScopeKind.Statement);
return true;
case ExpressionType.Conditional:
case ExpressionType.Loop:
case ExpressionType.Goto:
PushLabelBlock(LabelScopeKind.Statement);
return true;
}
}
private void DefineBlockLabels(Expression node)
{
var block = node as BlockExpression;
if (block == null || block is SpilledExpressionBlock)
{
return;
}
for (int i = 0, n = block.ExpressionCount; i < n; i++)
{
Expression e = block.GetExpression(i);
var label = e as LabelExpression;
if (label != null)
{
DefineLabel(label.Target);
}
}
}
// See if this lambda has a return label
// If so, we'll create it now and mark it as allowing the "ret" opcode
// This allows us to generate better IL
private void AddReturnLabel(LambdaExpression lambda)
{
Expression expression = lambda.Body;
while (true)
{
switch (expression.NodeType)
{
default:
// Didn't find return label
return;
case ExpressionType.Label:
// Found the label. We can directly return from this place
// only if the label type is reference assignable to the lambda return type.
LabelTarget label = ((LabelExpression)expression).Target;
_labelInfo.Add(label, new LabelInfo(_ilg, label, TypeUtils.AreReferenceAssignable(lambda.ReturnType, label.Type)));
return;
case ExpressionType.Block:
// Look in the last significant expression of a block
var body = (BlockExpression)expression;
// omit empty and debuginfo at the end of the block since they
// are not going to emit any IL
if (body.ExpressionCount == 0)
{
return;
}
for (int i = body.ExpressionCount - 1; i >= 0; i--)
{
expression = body.GetExpression(i);
if (Significant(expression))
{
break;
}
}
continue;
}
}
}
}
}
| |
/****************************************************************************/
/* */
/* The Mondo Libraries */
/* */
/* Namespace: Mondo.Common */
/* File: FileSpec.cs */
/* Class(es): FileSpec */
/* Purpose: A file specification */
/* */
/* Original Author: Jim Lightfoot */
/* Creation Date: 12 Nov 2005 */
/* */
/* Copyright (c) 2005 - Jim Lightfoot, All rights reserved */
/* */
/* Licensed under the MIT license: */
/* http://www.opensource.org/licenses/mit-license.php */
/* */
/****************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Net;
using System.IO;
using System.Threading;
using Mondo.Xml;
namespace Mondo.Common
{
/****************************************************************************/
/****************************************************************************/
public interface IProgress
{
void SetProgress(string strItem);
void AddProgressCount(int nItems);
void ClearProgressCount();
}
/****************************************************************************/
/****************************************************************************/
public interface IPath
{
string FullPath {get;}
}
/****************************************************************************/
/****************************************************************************/
public interface IStorage
{
string LoadFile(string strFileName);
byte[] GetFile(string strFileName);
void DropData(string strDestFileName, object objData, bool bOverwrite);
}
/****************************************************************************/
/****************************************************************************/
public abstract class FileSpec : IPath, IStorage
{
private string m_strFolder = "";
private string m_strFileName = "";
private bool m_bSingleFile = false;
private string m_strSeparator = "";
private IProgress m_objProgress = null;
/****************************************************************************/
protected FileSpec(string strPath, string strSeparator)
{
m_strSeparator = strSeparator;
string strRevisedPath = strPath.Trim();
string strExtension = Path.GetExtension(strPath);
if(strExtension == "")
{
strRevisedPath = strRevisedPath.EnsureLastChar(m_strSeparator);
strRevisedPath += "*.*";
}
m_strFolder = Path.GetDirectoryName(strRevisedPath);
m_strFolder = m_strFolder.EnsureLastChar(m_strSeparator);
m_strFileName = Path.GetFileName(strRevisedPath);
if(strSeparator == "\\")
m_strFolder = m_strFolder.Replace("//", "\\\\");
else
m_strFolder = m_strFolder.Replace("\\\\", "//").Replace("\\", "/");
m_bSingleFile = !m_strFileName.Contains("*") && !m_strFileName.Contains("?");
}
/****************************************************************************/
public static FileSpec Create(string strPath)
{
// if(strPath.ToLower().StartsWith("ftp"))
// return(new FtpFileSpec(strPath));
return(new DiskFileSpec(strPath));
}
/****************************************************************************/
public virtual string DirectoryName {get{return(m_strFolder);}}
public string FileName {get{return(m_strFileName);}}
public string FullPath {get{return(m_strFolder + m_strFileName);}}
public bool SingleFile {get{return(m_bSingleFile);}}
public IProgress Progress {get{return(m_objProgress);} set {m_objProgress = value;}}
/****************************************************************************/
public virtual bool IsRootFolder
{
get
{
string strFolder = Path.GetDirectoryName(this.DirectoryName).ToLower();
return(strFolder == Directory.GetDirectoryRoot(strFolder));
}
}
/****************************************************************************/
public virtual void CopyTo(FileSpec objDestination, bool bOverwrite)
{
IEnumerable aFiles = this.GetFiles(false);
foreach(string strSourceFilePath in aFiles)
{
if(m_objProgress != null)
m_objProgress.SetProgress(strSourceFilePath);
objDestination.DropFile(this, strSourceFilePath, bOverwrite);
}
return;
}
/****************************************************************************/
public virtual bool FileExists()
{
if(this.SingleFile)
return(FileExists(this.FullPath));
return(true);
}
/****************************************************************************/
public virtual bool FolderExists()
{
return(true);
}
/****************************************************************************/
public abstract ICollection GetFiles(bool bSubFolders);
public abstract ICollection GetFolders(bool bSubFolders);
public abstract bool FileExists(string strFileName);
public abstract void DropFile(FileSpec objSpec, string strFileName, bool bOverwrite);
public abstract void DropData(string strDestFileName, object objData, bool bOverwrite);
public abstract void DeleteAll();
public abstract void Delete(string strFileName);
public abstract void DeleteFolder();
public abstract byte[] GetFile(string strFileName);
public abstract string LoadFile(string strFileName);
public abstract DateTime GetFileDate(string strFileName);
public abstract DateTime GetModifiedDate(string strFileName);
public abstract DateTime FileDate {get;}
public abstract long FileSize {get;}
public abstract Stream GetStream(string strFileName);
public abstract FileSpec CreateSingleFileSpec(string strFileName);
/****************************************************************************/
public virtual IComparer<string> ModificationDateComparer
{
get {return(new CompareModificationDates(this));}
}
/****************************************************************************/
/****************************************************************************/
public class CompareModificationDates : IComparer<string>
{
private FileSpec m_objSpec;
/****************************************************************************/
public CompareModificationDates(FileSpec objSpec)
{
m_objSpec = objSpec;
}
/****************************************************************************/
public int Compare(string x, string y)
{
return(m_objSpec.GetModifiedDate(x).CompareTo(m_objSpec.GetModifiedDate(y)));
}
}
}
/****************************************************************************/
/****************************************************************************/
public class DiskFileSpec : FileSpec
{
private bool m_bSubFolders = true;
private Dictionary<string, string> m_aExcludeExtensions = new Dictionary<string, string>(7);
/****************************************************************************/
public DiskFileSpec(string strPath) : base(strPath.Replace("/", "\\"), "\\")
{
}
/****************************************************************************/
public int FileCount
{
get
{
// ??? temp (doesn't include subfolders)
return(this.GetFiles(false).Count);
}
}
/****************************************************************************/
public bool CopySubFolders
{
get {return(m_bSubFolders);}
set {m_bSubFolders = value;}
}
/****************************************************************************/
public override DateTime GetFileDate(string strFileName)
{
return(File.GetCreationTime(strFileName));
}
/****************************************************************************/
public override DateTime GetModifiedDate(string strFileName)
{
return(File.GetLastWriteTime(strFileName));
}
/****************************************************************************/
public override DateTime FileDate
{
get {return(File.GetCreationTime(this.FullPath));}
}
/****************************************************************************/
public override long FileSize
{
get
{
try
{
return(new FileInfo(this.FullPath).Length);
}
catch
{
return(0);
}
}
}
/****************************************************************************/
public override FileSpec CreateSingleFileSpec(string strFileName)
{
string strFolder = Path.GetDirectoryName(strFileName);
if(strFolder != "")
return(new DiskFileSpec(strFileName));
return(new DiskFileSpec(this.DirectoryName + Path.GetFileName(strFileName)));
}
/****************************************************************************/
public override Stream GetStream(string strFileName)
{
return(File.OpenRead(strFileName));
}
/****************************************************************************/
public override bool FileExists(string strFileName)
{
return(File.Exists(strFileName));
}
/****************************************************************************/
public override bool FolderExists()
{
return(Directory.Exists(this.DirectoryName));
}
/****************************************************************************/
public override void CopyTo(FileSpec objDestination, bool bOverwrite)
{
if(objDestination is DiskFileSpec)
CopyToFile(objDestination as DiskFileSpec, bOverwrite);
else
base.CopyTo(objDestination, bOverwrite);
}
/****************************************************************************/
public void ExcludeExtension(string strExtension)
{
m_aExcludeExtensions.Add(strExtension.ToLower().EnsureStartsWith("."), "");
}
/****************************************************************************/
public override void DropData(string strDestFileName, object objData, bool bOverwrite)
{
if(objData is byte[])
DiskFile.ToFile(objData as byte[], this.DirectoryName + strDestFileName, bOverwrite);
else if(objData is Stream)
DiskFile.ToFile(objData as Stream, this.DirectoryName + strDestFileName, bOverwrite);
else
DiskFile.ToFile(objData.ToString(), this.DirectoryName + strDestFileName, bOverwrite);
}
/****************************************************************************/
public override void DropFile(FileSpec objSpec, string strFileName, bool bOverwrite)
{
// Do nothing because this will never get called
}
/****************************************************************************/
public override byte[] GetFile(string strFileName)
{
if(!strFileName.Contains(Path.DirectorySeparatorChar.ToString()))
strFileName = this.DirectoryName + strFileName;
return(DiskFile.LoadBytes(strFileName));
}
/****************************************************************************/
public override string LoadFile(string strFileName)
{
if(!strFileName.Contains(Path.DirectorySeparatorChar.ToString()))
strFileName = this.DirectoryName + strFileName;
return(DiskFile.LoadFile(strFileName));
}
/****************************************************************************/
public override void Delete(string strFileName)
{
try
{
File.Delete(strFileName);
#if DEBUG
Console.WriteLine("Deleted " + strFileName);
#endif
}
catch(Exception ex)
{
cDebug.Capture(ex);
throw;
}
}
/****************************************************************************/
public override void DeleteFolder()
{
Directory.Delete(this.DirectoryName);
}
/****************************************************************************/
public override void DeleteAll()
{
IEnumerable aFiles = this.GetFiles(false);
foreach(string strFileName in aFiles)
Delete(strFileName);
return;
}
/****************************************************************************/
public void DeleteAllAsync()
{
IEnumerable aFiles = this.GetFiles(false);
foreach(string strFileName in aFiles)
AsyncDeleteFile(strFileName);
return;
}
/*************************************************************************/
public static void AsyncDeleteFile(string strFileName)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(_AsyncDeleteFile), strFileName);
}
/*************************************************************************/
public static void _AsyncDeleteFile(object state)
{
try
{
string strFileName = state.ToString();
if(File.Exists(strFileName))
{
int nTrys = 0;
while(++nTrys <= 20)
{
try
{
File.Delete(strFileName);
return;
}
catch
{
}
System.Threading.Thread.Sleep(100);
}
}
}
catch
{
}
}
/****************************************************************************/
private bool Excluded(string strFileName)
{
if(m_aExcludeExtensions.Count > 0)
{
string strExtension = Path.GetExtension(strFileName).ToLower();
return(m_aExcludeExtensions.ContainsKey(strExtension));
}
return(false);
}
/****************************************************************************/
private void CopyToFile(DiskFileSpec objDestination, bool bOverwrite)
{
if(this.DirectoryName != objDestination.DirectoryName)
{
if(this.SingleFile)
{
string strSource = this.DirectoryName + this.FileName;
string strDestination = objDestination.FileName;
if(strDestination == "*.*")
strDestination = this.FileName;
strDestination = objDestination.DirectoryName + strDestination;
if(this.Progress != null)
this.Progress.SetProgress(strSource);
DiskFile.CopyFile(strSource, strDestination, bOverwrite);
}
else
{
IEnumerable aFiles = this.GetFiles(false);
foreach(string strSourceFilePath in aFiles)
{
string strFileName = Path.GetFileName(strSourceFilePath);
if(!Excluded(strFileName))
{
if(this.Progress != null)
this.Progress.SetProgress(strSourceFilePath);
DiskFile.CopyFile(strSourceFilePath, objDestination.DirectoryName + strFileName, bOverwrite);
}
}
if(this.CopySubFolders)
{
string[] aSubFolders = Directory.GetDirectories(this.DirectoryName);
foreach(string strSubFolder in aSubFolders)
{
DiskFileSpec objFrom = new DiskFileSpec(strSubFolder);
int iIndex = strSubFolder.LastIndexOf("\\");
DiskFileSpec objTo = null;
objFrom.Progress = this.Progress;
if(iIndex != -1)
objTo = new DiskFileSpec(objDestination.DirectoryName + strSubFolder.Remove(0, iIndex + 1));
objFrom.CopySubFolders = true;
objFrom.m_aExcludeExtensions = this.m_aExcludeExtensions;
objFrom.CopyTo(objTo, bOverwrite);
}
}
}
}
}
/****************************************************************************/
public override ICollection GetFiles(bool bSubFolders)
{
if(this.SingleFile)
{
List<string> aFiles = new List<string>();
aFiles.Add(this.DirectoryName + this.FileName);
return(aFiles);
}
return(Directory.GetFiles(this.DirectoryName, this.FileName, bSubFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
}
/****************************************************************************/
public override ICollection GetFolders(bool bSubFolders)
{
return(Directory.GetDirectories(this.DirectoryName, "*.*", bSubFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace Kent.Boogaart.HelperTrinity
{
/// <summary>
/// Provides helper methods for asserting arguments.
/// </summary>
/// <remarks>
/// <para>
/// This class provides helper methods for asserting the validity of arguments. It can be used to reduce the number of
/// laborious <c>if</c>, <c>throw</c> sequences in your code.
/// </para>
/// </remarks>
/// <example>
/// The following code ensures that the <c>name</c> argument is not <see langword="null"/>:
/// <code>
/// internal void DisplayDetails(string name)
/// {
/// ArgumentHelper.AssertNotNull(name, "name");
/// //now we know that name is not null
/// ...
/// }
/// </code>
/// </example>
/// <example>
/// The following code ensures that the <c>name</c> argument is not <see langword="null"/> or an empty <c>string</c>:
/// <code>
/// internal void DisplayDetails(string name)
/// {
/// ArgumentHelper.AssertNotNullOrEmpty(name, "name", true);
/// //now we know that name is not null and is not an empty string (or blank)
/// ...
/// }
/// </code>
/// </example>
/// <example>
/// The following code ensures that the <c>day</c> parameter is a valid member of its enumeration:
/// <code>
/// internal void DisplayInformation(DayOfWeek day)
/// {
/// ArgumentHelper.AssertEnumMember(day);
/// //now we know that day is a valid member of DayOfWeek
/// ...
/// }
/// </code>
/// </example>
/// <example>
/// The following code ensures that the <c>day</c> parameter is either DayOfWeek.Monday or DayOfWeek.Thursday:
/// <code>
/// internal void DisplayInformation(DayOfWeek day)
/// {
/// ArgumentHelper.AssertEnumMember(day, DayOfWeek.Monday, DayOfWeek.Thursday);
/// //now we know that day is either Monday or Thursday
/// ...
/// }
/// </code>
/// </example>
/// <example>
/// The following code ensures that the <c>bindingFlags</c> parameter is either BindingFlags.Public, BindingFlags.NonPublic
/// or both:
/// <code>
/// internal void GetInformation(BindingFlags bindingFlags)
/// {
/// ArgumentHelper.AssertEnumMember(bindingFlags, BindingFlags.Public, BindingFlags.NonPublic);
/// //now we know that bindingFlags is either Public, NonPublic or both
/// ...
/// }
/// </code>
/// </example>
/// <example>
/// The following code ensures that the <c>bindingFlags</c> parameter is either BindingFlags.Public, BindingFlags.NonPublic,
/// both or neither (BindingFlags.None):
/// <code>
/// internal void GetInformation(BindingFlags bindingFlags)
/// {
/// ArgumentHelper.AssertEnumMember(bindingFlags, BindingFlags.Public, BindingFlags.NonPublic, BindingFlags.None);
/// //now we know that bindingFlags is either Public, NonPublic, both or neither
/// ...
/// }
/// </code>
/// </example>
internal static class ArgumentHelper
{
[DebuggerHidden]
internal static void AssertNotNull<T>(T arg, string argName)
where T : class
{
if (arg == null)
{
throw new ArgumentNullException(argName);
}
}
[DebuggerHidden]
internal static void AssertNotNull<T>(Nullable<T> arg, string argName)
where T : struct
{
if (!arg.HasValue)
{
throw new ArgumentNullException(argName);
}
}
[DebuggerHidden]
internal static void AssertGenericArgumentNotNull<T>(T arg, string argName)
{
Type type = typeof(T);
if (!type.IsValueType || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>))))
{
AssertNotNull((object) arg, argName);
}
}
[DebuggerHidden]
internal static void AssertNotNull<T>(IEnumerable<T> arg, string argName, bool assertContentsNotNull)
{
//make sure the enumerable item itself isn't null
AssertNotNull(arg, argName);
if (assertContentsNotNull && typeof(T).IsClass)
{
//make sure each item in the enumeration isn't null
foreach (T item in arg)
{
if (item == null)
{
throw new ArgumentException("An item inside the enumeration was null.", argName);
}
}
}
}
[DebuggerHidden]
internal static void AssertNotNullOrEmpty(string arg, string argName)
{
AssertNotNullOrEmpty(arg, argName, false);
}
[DebuggerHidden]
internal static void AssertNotNullOrEmpty(string arg, string argName, bool trim)
{
if (string.IsNullOrEmpty(arg) || (trim && IsOnlyWhitespace(arg)))
{
throw new ArgumentException("Cannot be null or empty.", argName);
}
}
[DebuggerHidden]
// [CLSCompliant(false)]
internal static void AssertEnumMember<TEnum>(TEnum enumValue, string argName)
where TEnum : struct, IConvertible
{
if (Attribute.IsDefined(typeof(TEnum), typeof(FlagsAttribute), false))
{
//flag enumeration - we can only get here if TEnum is a valid enumeration type, since the FlagsAttribute can
//only be applied to enumerations
bool throwEx;
long longValue = enumValue.ToInt64(CultureInfo.InvariantCulture);
if (longValue == 0)
{
//only throw if zero isn't defined in the enum - we have to convert zero to the underlying type of the enum
throwEx = !Enum.IsDefined(typeof(TEnum), ((IConvertible) 0).ToType(Enum.GetUnderlyingType(typeof(TEnum)), CultureInfo.InvariantCulture));
}
else
{
foreach (TEnum value in Enum.GetValues(typeof(TEnum)))
{
longValue &= ~value.ToInt64(CultureInfo.InvariantCulture);
}
//throw if there is a value left over after removing all valid values
throwEx = (longValue != 0);
}
if (throwEx)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Enum value '{0}' is not valid for flags enumeration '{1}'.",
enumValue, typeof(TEnum).FullName), argName);
}
}
else
{
//not a flag enumeration
if (!Enum.IsDefined(typeof(TEnum), enumValue))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Enum value '{0}' is not defined for enumeration '{1}'.",
enumValue, typeof(TEnum).FullName), argName);
}
}
}
[DebuggerHidden]
// [CLSCompliant(false)]
internal static void AssertEnumMember<TEnum>(TEnum enumValue, string argName, params TEnum[] validValues)
where TEnum : struct, IConvertible
{
AssertNotNull(validValues, "validValues");
if (Attribute.IsDefined(typeof(TEnum), typeof(FlagsAttribute), false))
{
//flag enumeration
bool throwEx;
long longValue = enumValue.ToInt64(CultureInfo.InvariantCulture);
if (longValue == 0)
{
//only throw if zero isn't permitted by the valid values
throwEx = true;
foreach (TEnum value in validValues)
{
if (value.ToInt64(CultureInfo.InvariantCulture) == 0)
{
throwEx = false;
break;
}
}
}
else
{
foreach (TEnum value in validValues)
{
longValue &= ~value.ToInt64(CultureInfo.InvariantCulture);
}
//throw if there is a value left over after removing all valid values
throwEx = (longValue != 0);
}
if (throwEx)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Enum value '{0}' is not allowed for flags enumeration '{1}'.",
enumValue, typeof(TEnum).FullName), argName);
}
}
else
{
//not a flag enumeration
foreach (TEnum value in validValues)
{
if (enumValue.Equals(value))
{
return;
}
}
//at this point we know an exception is required - however, we want to tailor the message based on whether the
//specified value is undefined or simply not allowed
if (!Enum.IsDefined(typeof(TEnum), enumValue))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Enum value '{0}' is not defined for enumeration '{1}'.",
enumValue, typeof(TEnum).FullName), argName);
}
else
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Enum value '{0}' is defined for enumeration '{1}' but it is not permitted in this context.",
enumValue, typeof(TEnum).FullName), argName);
}
}
}
private static bool IsOnlyWhitespace(string arg)
{
Debug.Assert(arg != null);
foreach (char c in arg)
{
if (!char.IsWhiteSpace(c))
{
return false;
}
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
///<summary>
///System.Globalization.CharUnicodeInfo.GetUnicodeCategory(System.Char)
///</summary>
public class CharUnicodeInfoGetUnicodeCategory
{
public static int Main()
{
CharUnicodeInfoGetUnicodeCategory testObj = new CharUnicodeInfoGetUnicodeCategory();
TestLibrary.TestFramework.BeginTestCase("for method of System.Globalization.CharUnicodeInfo.GetUnicodeCategory");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
retVal = PosTest14() && retVal;
retVal = PosTest15() && retVal;
retVal = PosTest16() && retVal;
retVal = PosTest17() && retVal;
retVal = PosTest18() && retVal;
retVal = PosTest19() && retVal;
retVal = PosTest20() && retVal;
retVal = PosTest21() && retVal;
retVal = PosTest22() && retVal;
retVal = PosTest23() && retVal;
retVal = PosTest24() && retVal;
retVal = PosTest25() && retVal;
retVal = PosTest26() && retVal;
retVal = PosTest27() && retVal;
retVal = PosTest28() && retVal;
retVal = PosTest29() && retVal;
retVal = PosTest30() && retVal;
return retVal;
}
#region Test Logic
public bool PosTest1()
{
bool retVal = true;
Char ch = 'A';
int expectedValue = (int)UnicodeCategory.UppercaseLetter;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with upper letter");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ") when char is '" + ch + "'" );
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
Char ch = 'a';
int expectedValue = (int)UnicodeCategory.LowercaseLetter;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest2:Test the method with low case char");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
Char ch = '\u1fa8'; //this char is a TitlecaseLetter char
int expectedValue = (int)UnicodeCategory.TitlecaseLetter;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest3:Test the method with '\\0'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("005", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
Char ch = '\u02b0';
int expectedValue = (int)UnicodeCategory.ModifierLetter;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest4:Test the method with '\\u02b0'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("007", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
Char ch = '\u404e';
int expectedValue = (int)UnicodeCategory.OtherLetter;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest5:Test the method with '\\u404e'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("009", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
Char ch = '\u0300';
int expectedValue = (int)UnicodeCategory.NonSpacingMark;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest6:Test the method with '\\u0300'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("011", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
Char ch = '\u0903';
int expectedValue = (int)UnicodeCategory.SpacingCombiningMark;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest7:Test the method with '\\u0903'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("013", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
Char ch = '\u0488';
int expectedValue = (int)UnicodeCategory.EnclosingMark;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest8:Test the method with '\\u0488'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("017", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
Char ch = '0';
int expectedValue = (int)UnicodeCategory.DecimalDigitNumber;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest9:Test the method with '0'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("017", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
Char ch = '\u16ee';
int expectedValue = (int)UnicodeCategory.LetterNumber;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest10:Test the method with '\\u16ee'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("019", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest11()
{
bool retVal = true;
Char ch = '\u00b2';
int expectedValue = (int)UnicodeCategory.OtherNumber;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest11:Test the method with '\\u00b2'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("021", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("022", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest12()
{
bool retVal = true;
Char ch = '\u0020';
int expectedValue = (int)UnicodeCategory.SpaceSeparator;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest12:Test the method with '\\u0020'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("023", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("024", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest13()
{
bool retVal = true;
Char ch = '\u2028';
int expectedValue = (int)UnicodeCategory.LineSeparator;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest13:Test the method with '\\u2028'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("025", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("026", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest14()
{
bool retVal = true;
Char ch = '\u2029';
int expectedValue = (int)UnicodeCategory.ParagraphSeparator;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest14:Test the method with '\\u2029'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("027", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("028", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest15()
{
bool retVal = true;
Char ch = '\0';
int expectedValue = (int)UnicodeCategory.Control;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest15:Test the method with '\\0'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("029", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("030", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest16()
{
bool retVal = true;
Char ch = '\u00ad';
int expectedValue = (int)UnicodeCategory.Format;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest16:Test the method with '\\u00ad'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("031", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("032", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest17()
{
bool retVal = true;
Char ch = '\ud800';
int expectedValue = (int)UnicodeCategory.Surrogate;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest17:Test the method with '\\ud800'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("033", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("034", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest18()
{
bool retVal = true;
Char ch = '\ue000';
int expectedValue = (int)UnicodeCategory.PrivateUse;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest18:Test the method with '\\ue000'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("035", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("036", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest19()
{
bool retVal = true;
Char ch = '\u005f';
int expectedValue = (int)UnicodeCategory.ConnectorPunctuation;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest19:Test the method with '\\u005f'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("037", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("038", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest20()
{
bool retVal = true;
Char ch = '-';
int expectedValue = (int)UnicodeCategory.DashPunctuation;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest20:Test the method with '-'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("039", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("040", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest21()
{
bool retVal = true;
Char ch = '(';
int expectedValue = (int)UnicodeCategory.OpenPunctuation;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest21:Test the method with '('");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("041", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("042", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest22()
{
bool retVal = true;
Char ch = ')';
int expectedValue = (int)UnicodeCategory.ClosePunctuation;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest22:Test the method with ')'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("043", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("044", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest23()
{
bool retVal = true;
Char ch = '\u00ab';
int expectedValue = (int)UnicodeCategory.InitialQuotePunctuation;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest23:Test the method with '\\u00ab'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("045", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("046", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest24()
{
bool retVal = true;
Char ch = '\u00bb';
int expectedValue = (int)UnicodeCategory.FinalQuotePunctuation;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest24:Test the method with '\\u00bb'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("047", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("048", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest25()
{
bool retVal = true;
Char ch = '!';
int expectedValue = (int)UnicodeCategory.OtherPunctuation;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest25:Test the method with '!'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("049", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("050", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest26()
{
bool retVal = true;
Char ch = '+';
int expectedValue = (int)UnicodeCategory.MathSymbol;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest26:Test the method with '+'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("051", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("052", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest27()
{
bool retVal = true;
Char ch = '$';
int expectedValue = (int)UnicodeCategory.CurrencySymbol;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest27:Test the method with '$'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("053", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("054", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest28()
{
bool retVal = true;
Char ch = '^';
int expectedValue = (int)UnicodeCategory.ModifierSymbol;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest28:Test the method with '^'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("055", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("056", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest29()
{
bool retVal = true;
Char ch = '\u00a6';
int expectedValue = (int)UnicodeCategory.OtherSymbol;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest29:Test the method with '\\u00a6'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("057", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("058", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest30()
{
bool retVal = true;
Char ch = '\u0242';
int expectedValue = (int)UnicodeCategory.LowercaseLetter;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest30:Test the method with '\\u0242'");
try
{
actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch));
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("059", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("060", "when char is '" + ch + "',Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// Copyright 2015, 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.
// Author: api.anash@gmail.com (Anash P. Oommen)
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.v201505;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Threading;
namespace Google.Api.Ads.Dfp.Tests.v201505 {
/// <summary>
/// UnitTests for <see cref="InventoryServiceTests"/> class.
/// </summary>
[TestFixture]
public class InventoryServiceTests : BaseTests {
/// <summary>
/// UnitTests for <see cref="InventoryService"/> class.
/// </summary>
private InventoryService inventoryService;
/// <summary>
/// The ad unit 1 for running tests.
/// </summary>
private AdUnit adUnit1;
/// <summary>
/// The ad unit 2 for running tests.
/// </summary>
private AdUnit adUnit2;
/// <summary>
/// Default public constructor.
/// </summary>
public InventoryServiceTests() : base() {
}
/// <summary>
/// Initialize the test case.
/// </summary>
[SetUp]
public void Init() {
TestUtils utils = new TestUtils();
inventoryService = (InventoryService) user.GetService(DfpService.v201505.InventoryService);
adUnit1 = utils.CreateAdUnit(user);
adUnit2 = utils.CreateAdUnit(user);
}
/// <summary>
/// Test whether we can create a list of ad units.
/// </summary>
[Test]
public void TestCreateAdUnits() {
// Create ad unit 1.
AdUnit localAdUnit1 = new AdUnit();
localAdUnit1.name = string.Format("Ad_Unit_{0}", new TestUtils().GetTimeStamp());
localAdUnit1.parentId = adUnit1.id;
Size size1 = new Size();
size1.width = 300;
size1.height = 250;
AdUnitSize adUnitSize1 = new AdUnitSize();
adUnitSize1.size = size1;
adUnitSize1.environmentType = EnvironmentType.BROWSER;
localAdUnit1.adUnitSizes = new AdUnitSize[] {adUnitSize1};
// Create ad unit 2.
AdUnit localAdUnit2 = new AdUnit();
localAdUnit2.name = string.Format("Ad_Unit_{0}", new TestUtils().GetTimeStamp());
localAdUnit2.parentId = adUnit1.id;
Size size2 = new Size();
size2.width = 300;
size2.height = 250;
AdUnitSize adUnitSize2 = new AdUnitSize();
adUnitSize2.size = size2;
adUnitSize2.environmentType = EnvironmentType.BROWSER;
localAdUnit2.adUnitSizes = new AdUnitSize[] {adUnitSize2};
AdUnit[] newAdUnits = null;
Assert.DoesNotThrow(delegate() {
newAdUnits = inventoryService.createAdUnits(new AdUnit[] {localAdUnit1, localAdUnit2});
});
Assert.NotNull(newAdUnits);
Assert.AreEqual(newAdUnits.Length, 2);
Assert.AreEqual(newAdUnits[0].name, localAdUnit1.name);
Assert.AreEqual(newAdUnits[0].parentId, localAdUnit1.parentId);
Assert.AreEqual(newAdUnits[0].parentId, adUnit1.id);
Assert.AreEqual(newAdUnits[0].status, localAdUnit1.status);
Assert.AreEqual(newAdUnits[0].targetWindow, localAdUnit1.targetWindow);
Assert.AreEqual(newAdUnits[1].name, localAdUnit2.name);
Assert.AreEqual(newAdUnits[1].parentId, localAdUnit2.parentId);
Assert.AreEqual(newAdUnits[1].parentId, adUnit1.id);
Assert.AreEqual(newAdUnits[1].status, localAdUnit2.status);
Assert.AreEqual(newAdUnits[1].targetWindow, localAdUnit2.targetWindow);
}
/// <summary>
/// Test whether we can fetch a list of existing ad units that match given
/// statement.
/// </summary>
[Test]
public void TestGetAdUnitsByStatement() {
Statement statement = new Statement();
statement.query = string.Format("WHERE id = '{0}' LIMIT 1", adUnit1.id);
AdUnitPage page = null;
Assert.DoesNotThrow(delegate() {
page = inventoryService.getAdUnitsByStatement(statement);
});
Assert.NotNull(page);
Assert.NotNull(page.results);
Assert.AreEqual(page.totalResultSetSize, 1);
Assert.NotNull(page.results[0]);
Assert.AreEqual(page.results[0].name, adUnit1.name);
Assert.AreEqual(page.results[0].parentId, adUnit1.parentId);
Assert.AreEqual(page.results[0].id, adUnit1.id);
Assert.AreEqual(page.results[0].status, adUnit1.status);
Assert.AreEqual(page.results[0].targetWindow, adUnit1.targetWindow);
}
/// <summary>
/// Test whether we can deactivate an ad unit.
/// </summary>
[Test]
public void TestPerformAdUnitAction() {
Statement statement = new Statement();
statement.query = string.Format("WHERE id = '{0}' LIMIT 1", adUnit1.id);
UpdateResult result = null;
Assert.DoesNotThrow(delegate() {
result = inventoryService.performAdUnitAction(new DeactivateAdUnits(), statement);
});
Assert.NotNull(result);
Assert.AreEqual(result.numChanges, 1);
}
/// <summary>
/// Test whether we can update a list of an ad units.
/// </summary>
[Test]
public void TestUpdateAdUnits() {
List<AdUnitSize> adUnitSizes = null;
Size size = null;
// Modify ad unit 1.
adUnitSizes = new List<AdUnitSize>(adUnit1.adUnitSizes);
size = new Size();
size.width = 728;
size.height = 90;
// Create ad unit size.
AdUnitSize adUnitSize = new AdUnitSize();
adUnitSize.size = size;
adUnitSize.environmentType = EnvironmentType.BROWSER;
adUnitSizes.Add(adUnitSize);
adUnit1.adUnitSizes = adUnitSizes.ToArray();
// Modify ad unit 2.
adUnitSizes = new List<AdUnitSize>(adUnit2.adUnitSizes);
size = new Size();
size.width = 728;
size.height = 90;
// Create ad unit size.
adUnitSize = new AdUnitSize();
adUnitSize.size = size;
adUnitSize.environmentType = EnvironmentType.BROWSER;
adUnitSizes.Add(adUnitSize);
adUnit2.adUnitSizes = adUnitSizes.ToArray();
AdUnit[] newAdUnits = null;
Assert.DoesNotThrow(delegate() {
newAdUnits = inventoryService.updateAdUnits(new AdUnit[] {adUnit1, adUnit2});
});
Assert.NotNull(newAdUnits);
Assert.AreEqual(newAdUnits.Length, 2);
Assert.AreEqual(newAdUnits[0].name, adUnit1.name);
Assert.AreEqual(newAdUnits[0].parentId, adUnit1.parentId);
Assert.AreEqual(newAdUnits[0].id, adUnit1.id);
Assert.AreEqual(newAdUnits[0].status, adUnit1.status);
Assert.AreEqual(newAdUnits[0].targetWindow, adUnit1.targetWindow);
Assert.AreEqual(newAdUnits[0].adUnitSizes.Length, adUnit1.adUnitSizes.Length);
Assert.AreEqual(newAdUnits[1].name, adUnit2.name);
Assert.AreEqual(newAdUnits[1].parentId, adUnit2.parentId);
Assert.AreEqual(newAdUnits[1].id, adUnit2.id);
Assert.AreEqual(newAdUnits[1].status, adUnit2.status);
Assert.AreEqual(newAdUnits[1].targetWindow, adUnit2.targetWindow);
Assert.AreEqual(newAdUnits[1].adUnitSizes.Length, adUnit2.adUnitSizes.Length);
}
}
}
| |
using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
using LTAF.Engine;
using LTAF.Emulators;
using System.Threading;
using System.Text.RegularExpressions;
namespace LTAF
{
/// <summary>
/// Class that represents a web page as seen by the browser than can be automated.
/// </summary>
public class HtmlPage
{
private const int EXECUTE_COMMAND_TIMEOUT = 60;
private const int REFRESH_TIMEOUT_DEFAULT = 5;
private const string ERROR_APPLICATIONPATH_NULL = "'ApplicationPath' is required when creating an HtmlPage. "+
"Pass it through the constructor or make sure a valid ApplicationPathFinder has been registered with the ServiceLocator.";
private static string _aspnetErrorRegexPattern;
private static EmulatedBrowserCommandExecutorFactory _defaultFactory = new EmulatedBrowserCommandExecutorFactory();
private readonly int _threadId;
private HtmlElementCollection _elements;
private string _applicationPath = null;
/// <summary>The index of this window used to locate it in the client</summary>
internal int WindowIndex { get; set; }
/// <summary>
/// The frame hierarchy to use to reach the page under test
/// </summary>
internal List<string> FrameHierachy { get; set; }
/// <summary>
/// Constructs a new HtmlPage to interact with the page loaded in the browser
/// </summary>
public HtmlPage()
: this(null, null)
{
}
/// <summary>
/// Constructor that automatically navigates to url specified
/// </summary>
/// <param name="navigateUrl">The Url to navigate to</param>
public HtmlPage(string navigateUrl)
: this(null, navigateUrl)
{
}
/// <summary>
/// Constructs a new HtmlPage with an application path to be used to resolve relative paths
/// </summary>
/// <param name="applicationPath">Application path used to resolve relative paths</param>
public HtmlPage(Uri applicationPath)
: this(applicationPath.AbsoluteUri, null)
{
}
/// <summary>
/// Constructs a new HtmlPage with an application path to be used to resolve relative paths and navigates to target page
/// </summary>
/// <param name="applicationPath">The application path used to resolve relative paths</param>
/// <param name="navigateUrl">The Url to navigate to</param>
private HtmlPage(string applicationPath, string navigateUrl)
{
if (applicationPath == null)
{
applicationPath = ServiceLocator.ApplicationPathFinder.GetApplicationPath();
if (applicationPath == null)
{
throw new InvalidOperationException(ERROR_APPLICATIONPATH_NULL);
}
}
// ensure that DNS name of the host is punycoded (when it is necessary for
applicationPath = EnsureDnsSafePath(applicationPath);
_threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
_elements = new HtmlElementCollection(this);
_applicationPath = applicationPath;
FrameHierachy = new List<string>();
if (ServiceLocator.BrowserCommandExecutorFactory != null)
{
this.BrowserCommandExecutor = ServiceLocator.BrowserCommandExecutorFactory.CreateBrowserCommandExecutor(applicationPath, this);
}
else
{
this.BrowserCommandExecutor = _defaultFactory.CreateBrowserCommandExecutor(applicationPath, this);
}
if (navigateUrl != null)
{
this.Navigate(navigateUrl);
}
}
/// <summary>
/// Ensure that DNS name of the host is punycoded (when it is necessary)
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string EnsureDnsSafePath(string path)
{
string safePath = path;
if (!Uri.IsWellFormedUriString(path, UriKind.RelativeOrAbsolute))
{
if (!string.IsNullOrEmpty(path))
{
path = "http://" + path;
}
}
if (Uri.IsWellFormedUriString(path, UriKind.Absolute))
{
Uri uri = new Uri(path);
safePath = uri.Scheme + "://" + uri.DnsSafeHost + (uri.Port != 80 && uri.Port > 0 ? ":" + uri.Port.ToString() : "") + uri.PathAndQuery;
}
return safePath;
}
#region Properties
/// <summary>
/// The command executor to use when issuing command for this page.
/// </summary>
internal IBrowserCommandExecutor BrowserCommandExecutor
{
get;
set;
}
/// <summary>
/// The Dom elements that are exposed by this web page.
/// </summary>
public HtmlElementCollection Elements
{
get
{
return _elements;
}
}
/// <summary>
/// The root Dom element exposed by this web page
/// </summary>
public HtmlElement RootElement
{
get
{
if (this.Elements.Count == 0)
{
throw new InvalidOperationException("Dom has not been loaded, please call Navigate() before trying to access the RootElement property.");
}
return this.Elements[0];
}
}
#endregion
#region ExecuteCommand
/// <summary>
/// Execute a command on this web page.
/// </summary>
/// <param name="command">The command to execute</param>
/// <returns>BrowserInfo object containing results from the command execution</returns>
public BrowserInfo ExecuteCommand(BrowserCommand command)
{
return ExecuteCommand(null, command);
}
/// <summary>
/// Execute a command on this web page.
/// </summary>
/// <param name="source">HtmlElement that initiated this command, null if none</param>
/// <param name="command">The command to execute</param>
/// <returns>BrowserInfo object containing results from the command execution</returns>
public virtual BrowserInfo ExecuteCommand(HtmlElement source, BrowserCommand command)
{
command.Target.WindowIndex = this.WindowIndex;
if (this.WindowIndex > 0)
{
command.Description += String.Format(" (Popup window: {0})", this.WindowIndex);
}
if (this.FrameHierachy.Count > 0)
{
string[] frames = this.FrameHierachy.ToArray();
command.Description += String.Format(" (Frame: {0})", String.Join("-", frames));
command.Target.FrameHierarchy = frames;
}
command.Traces = WebTestConsole.GetTraces();
BrowserInfo browserInfo = null;
try
{
browserInfo = this.BrowserCommandExecutor.ExecuteCommand(Thread.CurrentThread.ManagedThreadId, source, command, EXECUTE_COMMAND_TIMEOUT);
}
finally
{
WebTestConsole.Clear();
}
if (browserInfo != null)
{
if (string.IsNullOrEmpty(browserInfo.ErrorMessages))
{
return browserInfo;
}
else
{
throw new WebTestException("Exception was thrown by the client engine: " + browserInfo.ErrorMessages + " when running command: " +
command.Description + " on the target: <" + command.Target.TagName + " id=" + command.Target.Id + ", index: " + command.Target.Index + ">.");
}
}
throw new TimeoutException(string.Format("BrowserCommand \"{0}\" timed out after {1} seconds(s)!", command.Description, EXECUTE_COMMAND_TIMEOUT));
}
#endregion
#region Navigate
/// <summary>
/// Navigate to a url and load its DOM.
/// </summary>
/// <param name="url">The absolute or relative url (relative to app root) to navigate to.</param>
public void Navigate(string url)
{
Navigate(url, NavigationVerification.Default);
}
/// <summary>
/// Navigate to a url and load its DOM.
/// </summary>
/// <param name="url">The absolute or relative url (relative to app root) to navigate to.</param>
/// <param name="navigationVerificationMode">NavigationVerification mode</param>
public void Navigate(string url, NavigationVerification navigationVerificationMode)
{
Navigate(url, navigationVerificationMode, 0);
}
/// <summary>
/// Returns an absolute url based on the current application path.
/// </summary>
/// <param name="url">The relative url.</param>
/// <returns>The absolute url.</returns>
protected internal string ResolveNavigateUrl(string url)
{
if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return url;
}
else if (url == "/" || String.IsNullOrEmpty(url))
{
return this._applicationPath;
}
else
{
string appPath = this._applicationPath.EndsWith("/") ? this._applicationPath : this._applicationPath + "/";
return appPath + url.TrimStart('/');
}
}
/// <summary>
/// Navigate to this web page.
/// </summary>
/// <param name="url">The absolute or relative url (relative to app root) to navigate to.</param>
/// <param name="navigationVerificationMode">NavigationVerification mode</param>
/// <param name="millisecondsWaitToLoad">Time in milliseconds after navigate to wait for page to be fully loaded.</param>
protected virtual void Navigate(string url, NavigationVerification navigationVerificationMode, int millisecondsWaitToLoad)
{
string absoluteUrl = ResolveNavigateUrl(url);
BrowserCommand command = new BrowserCommand();
command.Description = String.Format("Navigate - {0}", absoluteUrl);
command.Handler.RequiresElementFound = false;
command.Handler.ClientFunctionName = BrowserCommand.FunctionNames.NavigateToUrl;
command.Handler.SetArguments(absoluteUrl, navigationVerificationMode);
this.ExecuteCommand(command);
if (millisecondsWaitToLoad > 0)
{
System.Threading.Thread.Sleep(millisecondsWaitToLoad);
}
this.Elements.Refresh();
}
#endregion
#region GetCurrentUrl
/// <summary>
/// Returns the url of the page currently loaded
/// </summary>
/// <returns>Url of the page currently loaded</returns>
public string GetCurrentUrl()
{
BrowserCommand command = new BrowserCommand(BrowserCommand.FunctionNames.GetCurrentUrl);
command.Description = "GetCurrentUrl";
command.Handler.RequiresElementFound = false;
return this.ExecuteCommand(command).Data;
}
#endregion
#region ExecuteScript
/// <summary>
/// Evaluates a custom script expression in the context of the page under test
/// </summary>
/// <param name="scriptExpression">The javascript expression to evaluate</param>
public object ExecuteScript(string scriptExpression)
{
BrowserCommand command = new BrowserCommand();
command.Description = "ExecuteScript";
command.Handler.RequiresElementFound = false;
command.Handler.ClientFunctionName = BrowserCommand.FunctionNames.ExecuteScript;
command.Handler.SetArguments(scriptExpression);
BrowserInfo result = this.ExecuteCommand(command);
if(result == null || string.IsNullOrEmpty(result.Data))
{
return null;
}
else
{
return TestDriverPage.SystemWebExtensionsAbstractions.DeserializeJson(result.Data);
}
}
#endregion
#region WaitForAsyncPostComplete
/// <summary>
/// Method that waits until no asynchronous post is in execution
/// </summary>
public void WaitForAsyncPostComplete()
{
this.WaitForScript("Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack() == false", 1000);
}
#endregion
#region WaitForScript
/// <summary>
/// Method that waits until a custom script expression that is evaluated in the context of the
/// page under test returns true
/// </summary>
/// <param name="scriptExpression">The javascript expression to evaluate</param>
/// <param name="timeoutInSeconds">The timeout in seconds to keep trying the expression before fail.</param>
public void WaitForScript(string scriptExpression, int timeoutInSeconds)
{
BrowserCommand command = new BrowserCommand();
command.Description = "WaitForScript";
command.Handler.RequiresElementFound = false;
command.Handler.ClientFunctionName = BrowserCommand.FunctionNames.WaitForScript;
command.Handler.SetArguments(scriptExpression, timeoutInSeconds * 1000);
this.ExecuteCommand(command);
}
#endregion
#region GetPopupWindow
/// <summary>
/// Method that gets a reference to an HTML popup page
/// </summary>
/// <param name="index">Zero based index of windows opened by driver</param>
/// <param name="timeoutInSeconds">Timeout to wait for the popup window to finish loading</param>
/// <param name="waitBetweenAttemptsInMilliseconds">Milliseconds to wait between attempting to get popup page</param>
/// <returns>HtmlPage to interact with the supplied popup window</returns>
public HtmlPage GetPopupPage(int index, int timeoutInSeconds = REFRESH_TIMEOUT_DEFAULT, int waitBetweenAttemptsInMilliseconds = 500)
{
HtmlPage popupPage = new HtmlPage();
popupPage.WindowIndex = index;
Exception exception = null;
DateTime timeout = DateTime.Now.AddSeconds(timeoutInSeconds);
// Wait until the popup page can be refreshed, or until timeout
while (!TryPageRefresh(popupPage, out exception) && DateTime.Now < timeout)
{
Thread.Sleep(waitBetweenAttemptsInMilliseconds);
}
if (exception != null)
{
throw new WebTestException(
String.Format("Failed to retrieve the popup window after {0} seconds.", timeoutInSeconds),
exception);
}
return popupPage;
}
#endregion
#region GetFrameWindow
/// <summary>
/// Method that gets a reference to an HTML frame
/// </summary>
/// <param name="frameNames">One or more frame names reachable from the current page</param>
/// <returns>HtmlPage to interact with the supplied frame</returns>
public HtmlPage GetFramePage(params string[] frameNames)
{
return GetFramePage(frameNames, REFRESH_TIMEOUT_DEFAULT);
}
/// <summary>
/// Method that gets a reference to an HTML frame
/// </summary>
/// <param name="frameNames">One or more frame names reachable from the current page</param>
/// <param name="timeoutInSeconds">Timeout to wait for the target frame to finish loading</param>
/// <param name="waitBetweenAttemptsInMilliseconds">Milliseconds to wait between attempting to get frame</param>
/// <returns>HtmlPage to interact with the supplied frame</returns>
public HtmlPage GetFramePage(string[] frameNames, int timeoutInSeconds = REFRESH_TIMEOUT_DEFAULT, int waitBetweenAttemptsInMilliseconds = 500)
{
HtmlPage framePage = new HtmlPage();
framePage.FrameHierachy.AddRange(this.FrameHierachy);
framePage.FrameHierachy.AddRange(frameNames);
Exception exception = null;
DateTime timeout = DateTime.Now.AddSeconds(timeoutInSeconds);
// Wait until the frame page can be refreshed, or until timeout
while (!TryPageRefresh(framePage, out exception) && DateTime.Now < timeout)
{
Thread.Sleep(waitBetweenAttemptsInMilliseconds);
}
if (exception != null)
{
throw new WebTestException(
String.Format("Failed to retrieve the frame after {0} seconds.", timeoutInSeconds),
exception);
}
return framePage;
}
#endregion
/// <summary>
/// Helper method that attempts to refresh the elements collection of a page
/// </summary>
private bool TryPageRefresh(HtmlPage page, out Exception exception)
{
exception = null;
try
{
page.Elements.Refresh();
}
catch (Exception e)
{
exception = e;
return false;
}
return true;
}
/// <summary>
/// Returns whether the current page is an Asp.Net server error page.
/// </summary>
/// <returns>True if current page is an Asp.Net server error page, false otherwise</returns>
public virtual bool IsServerError()
{
HtmlElementFindParams findParams = new HtmlElementFindParams("h1", 0);
if (this.Elements.Exists(findParams, 0))
{
if (_aspnetErrorRegexPattern == null)
{
WebResourceReader reader = new WebResourceReader();
string aspnetErrorStringFormatter = reader.GetString("System.Web", "System.Web", "Error_Formatter_ASPNET_Error"); //Server Error in '{0}' Application.
_aspnetErrorRegexPattern = String.Format(aspnetErrorStringFormatter, ".+?");
}
HtmlElement h1 = this.Elements.Find(findParams, 0);
return Regex.IsMatch(h1.CachedInnerText, _aspnetErrorRegexPattern , RegexOptions.Singleline);
}
return false;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Diagnostics;
using Axiom.Graphics;
using Axiom.Core;
using Axiom.MathLib;
namespace Axiom.SceneManagers.Multiverse
{
public class WaterPlane : SimpleRenderable, IBoundarySemantic
{
private Boundary boundary;
private SceneNode waterSceneNode;
private float height;
private RenderOperation renderOp;
private bool currentVisible = false;
private bool inBoundary = false;
private bool isAttached = false;
public WaterPlane(float height, String name, SceneNode parentSceneNode)
{
this.height = height;
this.name = name;
// create a scene node
if (parentSceneNode == null)
{
parentSceneNode = TerrainManager.Instance.RootSceneNode;
}
waterSceneNode = parentSceneNode.CreateChildSceneNode(name);
// set up material
material = TerrainManager.Instance.WaterMaterial;
CastShadows = false;
}
public string Type
{
get
{
return ("WaterPlane");
}
}
public WaterPlane(SceneNode parentSceneNode, XmlTextReader r)
{
FromXML(r);
// create a scene node
if (parentSceneNode == null)
{
parentSceneNode = TerrainManager.Instance.RootSceneNode;
}
waterSceneNode = parentSceneNode.CreateChildSceneNode(name);
// set up material
material = TerrainManager.Instance.WaterMaterial;
}
public void ToXML(XmlTextWriter w)
{
w.WriteStartElement("boundarySemantic");
w.WriteAttributeString("type", "WaterPlane");
w.WriteElementString("height", height.ToString());
w.WriteElementString("name", name);
w.WriteEndElement();
}
private void FromXML(XmlTextReader r)
{
while (r.Read())
{
// look for the start of an element
if (r.NodeType == XmlNodeType.Element)
{
// parse that element
ParseElement(r);
}
else if (r.NodeType == XmlNodeType.EndElement)
{
// if we found an end element, it means we are at the end of the terrain description
return;
}
}
}
protected void ParseElement(XmlTextReader r)
{
// set the field in this object based on the element we just read
switch (r.Name)
{
case "height":
// read the value
r.Read();
if (r.NodeType != XmlNodeType.Text)
{
return;
}
height = float.Parse(r.Value);
break;
case "name":
// read the value
r.Read();
if (r.NodeType != XmlNodeType.Text)
{
return;
}
name = r.Value;
break;
}
// error out if we dont see an end element here
r.Read();
if (r.NodeType != XmlNodeType.EndElement)
{
return;
}
}
private void BuildBoundingBox()
{
// set up bounding box
Vector3 minBounds = boundary.Bounds.Minimum;
Vector3 maxBounds = boundary.Bounds.Maximum;
minBounds.y = height;
maxBounds.y = height;
this.box = new AxisAlignedBox(minBounds, maxBounds);
}
public void AddToBoundary(Boundary boundary)
{
inBoundary = true;
this.boundary = boundary;
BuildBoundingBox();
BuildBuffers();
PageShift();
}
public void RemoveFromBoundary()
{
inBoundary = false;
boundary = null;
if (isAttached)
{
waterSceneNode.DetachObject(this);
isAttached = false;
}
box = null;
DisposeBuffers();
}
private void BuildBuffers()
{
//
// Build the vertex buffer
//
List<Vector2> points = boundary.Points;
List<int[]> indices = boundary.Triangles;
VertexData vertexData = new VertexData();
vertexData.vertexCount = boundary.Points.Count;
vertexData.vertexStart = 0;
// set up the vertex declaration
int vDecOffset = 0;
vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float3, VertexElementSemantic.Position);
vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float3);
vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float3, VertexElementSemantic.Normal);
vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float3);
vertexData.vertexDeclaration.AddElement(0, vDecOffset, VertexElementType.Float2, VertexElementSemantic.TexCoords, 0);
vDecOffset += VertexElement.GetTypeSize(VertexElementType.Float2);
// create the hardware vertex buffer and set up the buffer binding
HardwareVertexBuffer hvBuffer = HardwareBufferManager.Instance.CreateVertexBuffer(
vertexData.vertexDeclaration.GetVertexSize(0), vertexData.vertexCount,
BufferUsage.StaticWriteOnly, false);
vertexData.vertexBufferBinding.SetBinding(0, hvBuffer);
// lock the vertex buffer
IntPtr ipBuf = hvBuffer.Lock(BufferLocking.Discard);
int bufferOff = 0;
float minx = boundary.Bounds.Minimum.x;
float minz = boundary.Bounds.Minimum.z;
unsafe
{
float* buffer = (float*)ipBuf.ToPointer();
for (int v = 0; v < vertexData.vertexCount; v++)
{
// Position
buffer[bufferOff++] = points[v].x;
buffer[bufferOff++] = height;
buffer[bufferOff++] = points[v].y;
// normals
buffer[bufferOff++] = 0;
buffer[bufferOff++] = 1;
buffer[bufferOff++] = 0;
// Texture
float tmpu = ( points[v].x - minx ) / (128 * TerrainManager.oneMeter);
float tmpv = ( points[v].y - minz )/ (128 * TerrainManager.oneMeter);
buffer[bufferOff++] = tmpu;
buffer[bufferOff++] = tmpv;
}
}
hvBuffer.Unlock();
//
// build the index buffer
//
IndexData indexData = new IndexData();
int numIndices = indices.Count * 3;
indexData.indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer(
IndexType.Size16, numIndices, BufferUsage.StaticWriteOnly);
IntPtr indexBufferPtr = indexData.indexBuffer.Lock(0, indexData.indexBuffer.Size, BufferLocking.Discard);
unsafe
{
ushort* indexBuffer = (ushort*)indexBufferPtr.ToPointer();
for (int i = 0; i < indices.Count; i++)
{
indexBuffer[i * 3] = (ushort)indices[i][0];
indexBuffer[i * 3 + 1] = (ushort)indices[i][1];
indexBuffer[i * 3 + 2] = (ushort)indices[i][2];
}
}
indexData.indexBuffer.Unlock();
indexData.indexCount = numIndices;
indexData.indexStart = 0;
renderOp = new RenderOperation();
renderOp.vertexData = vertexData;
renderOp.indexData = indexData;
renderOp.operationType = OperationType.TriangleList;
renderOp.useIndices = true;
}
#region IBoundarySemantic Members
public void PerFrameProcessing(float time, Camera camera)
{
Debug.Assert(inBoundary);
return;
}
public void PageShift()
{
Debug.Assert(inBoundary);
if (boundary.Visible != currentVisible)
{
currentVisible = boundary.Visible;
if (currentVisible)
{
waterSceneNode.AttachObject(this);
isAttached = true;
}
else
{
waterSceneNode.DetachObject(this);
isAttached = false;
}
}
}
public void BoundaryChange()
{
Debug.Assert(inBoundary);
DisposeBuffers();
renderOp = null;
BuildBuffers();
}
public float Height
{
get
{
return height;
}
set
{
height = value;
BuildBoundingBox();
waterSceneNode.NeedUpdate();
BoundaryChange();
}
}
#endregion
#region IDisposable Members
private void DisposeBuffers()
{
if (renderOp.vertexData != null)
{
renderOp.vertexData.vertexBufferBinding.GetBuffer(0).Dispose();
renderOp.vertexData = null;
}
if (renderOp.indexData != null)
{
renderOp.indexData.indexBuffer.Dispose();
renderOp.indexData = null;
}
}
public void Dispose()
{
DisposeBuffers();
waterSceneNode.Creator.DestroySceneNode(waterSceneNode.Name);
}
#endregion
public override void GetRenderOperation(RenderOperation op)
{
Debug.Assert(inBoundary);
Debug.Assert(renderOp.vertexData != null, "attempting to render heightField with no vertexData");
Debug.Assert(renderOp.indexData != null, "attempting to render heightField with no indexData");
op.useIndices = this.renderOp.useIndices;
op.operationType = this.renderOp.operationType;
op.vertexData = this.renderOp.vertexData;
op.indexData = this.renderOp.indexData;
}
public override float GetSquaredViewDepth(Axiom.Core.Camera camera)
{
// Use squared length to avoid square root
return (this.ParentNode.DerivedPosition - camera.DerivedPosition).LengthSquared;
}
public override float BoundingRadius
{
get
{
return 0f;
}
}
public override void NotifyCurrentCamera(Axiom.Core.Camera cam)
{
Debug.Assert(inBoundary);
if (((Camera)(cam)).IsObjectVisible(this.worldAABB))
{
isVisible = true;
}
else
{
isVisible = false;
return;
}
}
public override void UpdateRenderQueue(RenderQueue queue)
{
Debug.Assert(inBoundary);
if (isVisible)
{
queue.AddRenderable(this);
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcbv = Google.Cloud.BinaryAuthorization.V1;
using sys = System;
namespace Google.Cloud.BinaryAuthorization.V1
{
/// <summary>Resource name for the <c>Policy</c> resource.</summary>
public sealed partial class PolicyName : gax::IResourceName, sys::IEquatable<PolicyName>
{
/// <summary>The possible contents of <see cref="PolicyName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/policy</c>.</summary>
Project = 1,
/// <summary>A resource name with pattern <c>locations/{location}/policy</c>.</summary>
Location = 2,
}
private static gax::PathTemplate s_project = new gax::PathTemplate("projects/{project}/policy");
private static gax::PathTemplate s_location = new gax::PathTemplate("locations/{location}/policy");
/// <summary>Creates a <see cref="PolicyName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="PolicyName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static PolicyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new PolicyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="PolicyName"/> with the pattern <c>projects/{project}/policy</c>.</summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PolicyName"/> constructed from the provided ids.</returns>
public static PolicyName FromProject(string projectId) =>
new PolicyName(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>Creates a <see cref="PolicyName"/> with the pattern <c>locations/{location}/policy</c>.</summary>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PolicyName"/> constructed from the provided ids.</returns>
public static PolicyName FromLocation(string locationId) =>
new PolicyName(ResourceNameType.Location, locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PolicyName"/> with pattern
/// <c>projects/{project}/policy</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PolicyName"/> with pattern <c>projects/{project}/policy</c>.
/// </returns>
public static string Format(string projectId) => FormatProject(projectId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PolicyName"/> with pattern
/// <c>projects/{project}/policy</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PolicyName"/> with pattern <c>projects/{project}/policy</c>.
/// </returns>
public static string FormatProject(string projectId) =>
s_project.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PolicyName"/> with pattern
/// <c>locations/{location}/policy</c>.
/// </summary>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PolicyName"/> with pattern <c>locations/{location}/policy</c>.
/// </returns>
public static string FormatLocation(string locationId) =>
s_location.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)));
/// <summary>Parses the given resource name string into a new <see cref="PolicyName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/policy</c></description></item>
/// <item><description><c>locations/{location}/policy</c></description></item>
/// </list>
/// </remarks>
/// <param name="policyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="PolicyName"/> if successful.</returns>
public static PolicyName Parse(string policyName) => Parse(policyName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="PolicyName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/policy</c></description></item>
/// <item><description><c>locations/{location}/policy</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="policyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="PolicyName"/> if successful.</returns>
public static PolicyName Parse(string policyName, bool allowUnparsed) =>
TryParse(policyName, allowUnparsed, out PolicyName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PolicyName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/policy</c></description></item>
/// <item><description><c>locations/{location}/policy</c></description></item>
/// </list>
/// </remarks>
/// <param name="policyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PolicyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string policyName, out PolicyName result) => TryParse(policyName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PolicyName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/policy</c></description></item>
/// <item><description><c>locations/{location}/policy</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="policyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PolicyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string policyName, bool allowUnparsed, out PolicyName result)
{
gax::GaxPreconditions.CheckNotNull(policyName, nameof(policyName));
gax::TemplatedResourceName resourceName;
if (s_project.TryParseName(policyName, out resourceName))
{
result = FromProject(resourceName[0]);
return true;
}
if (s_location.TryParseName(policyName, out resourceName))
{
result = FromLocation(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(policyName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private PolicyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="PolicyName"/> class from the component parts of pattern
/// <c>projects/{project}/policy</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
public PolicyName(string projectId) : this(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Project: return s_project.Expand(ProjectId);
case ResourceNameType.Location: return s_location.Expand(LocationId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as PolicyName);
/// <inheritdoc/>
public bool Equals(PolicyName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(PolicyName a, PolicyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(PolicyName a, PolicyName b) => !(a == b);
}
/// <summary>Resource name for the <c>Attestor</c> resource.</summary>
public sealed partial class AttestorName : gax::IResourceName, sys::IEquatable<AttestorName>
{
/// <summary>The possible contents of <see cref="AttestorName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/attestors/{attestor}</c>.</summary>
ProjectAttestor = 1,
}
private static gax::PathTemplate s_projectAttestor = new gax::PathTemplate("projects/{project}/attestors/{attestor}");
/// <summary>Creates a <see cref="AttestorName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AttestorName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static AttestorName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AttestorName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AttestorName"/> with the pattern <c>projects/{project}/attestors/{attestor}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="attestorId">The <c>Attestor</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AttestorName"/> constructed from the provided ids.</returns>
public static AttestorName FromProjectAttestor(string projectId, string attestorId) =>
new AttestorName(ResourceNameType.ProjectAttestor, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), attestorId: gax::GaxPreconditions.CheckNotNullOrEmpty(attestorId, nameof(attestorId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AttestorName"/> with pattern
/// <c>projects/{project}/attestors/{attestor}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="attestorId">The <c>Attestor</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AttestorName"/> with pattern
/// <c>projects/{project}/attestors/{attestor}</c>.
/// </returns>
public static string Format(string projectId, string attestorId) => FormatProjectAttestor(projectId, attestorId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AttestorName"/> with pattern
/// <c>projects/{project}/attestors/{attestor}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="attestorId">The <c>Attestor</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AttestorName"/> with pattern
/// <c>projects/{project}/attestors/{attestor}</c>.
/// </returns>
public static string FormatProjectAttestor(string projectId, string attestorId) =>
s_projectAttestor.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(attestorId, nameof(attestorId)));
/// <summary>Parses the given resource name string into a new <see cref="AttestorName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/attestors/{attestor}</c></description></item>
/// </list>
/// </remarks>
/// <param name="attestorName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AttestorName"/> if successful.</returns>
public static AttestorName Parse(string attestorName) => Parse(attestorName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AttestorName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/attestors/{attestor}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="attestorName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AttestorName"/> if successful.</returns>
public static AttestorName Parse(string attestorName, bool allowUnparsed) =>
TryParse(attestorName, allowUnparsed, out AttestorName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AttestorName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/attestors/{attestor}</c></description></item>
/// </list>
/// </remarks>
/// <param name="attestorName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AttestorName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string attestorName, out AttestorName result) => TryParse(attestorName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AttestorName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/attestors/{attestor}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="attestorName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AttestorName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string attestorName, bool allowUnparsed, out AttestorName result)
{
gax::GaxPreconditions.CheckNotNull(attestorName, nameof(attestorName));
gax::TemplatedResourceName resourceName;
if (s_projectAttestor.TryParseName(attestorName, out resourceName))
{
result = FromProjectAttestor(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(attestorName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AttestorName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string attestorId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AttestorId = attestorId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AttestorName"/> class from the component parts of pattern
/// <c>projects/{project}/attestors/{attestor}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="attestorId">The <c>Attestor</c> ID. Must not be <c>null</c> or empty.</param>
public AttestorName(string projectId, string attestorId) : this(ResourceNameType.ProjectAttestor, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), attestorId: gax::GaxPreconditions.CheckNotNullOrEmpty(attestorId, nameof(attestorId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Attestor</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AttestorId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectAttestor: return s_projectAttestor.Expand(ProjectId, AttestorId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AttestorName);
/// <inheritdoc/>
public bool Equals(AttestorName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AttestorName a, AttestorName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AttestorName a, AttestorName b) => !(a == b);
}
public partial class Policy
{
/// <summary>
/// <see cref="gcbv::PolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbv::PolicyName PolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcbv::PolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Attestor
{
/// <summary>
/// <see cref="gcbv::AttestorName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcbv::AttestorName AttestorName
{
get => string.IsNullOrEmpty(Name) ? null : gcbv::AttestorName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/***************************************************************************
* GumpHtmlLocalized.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id: GumpHtmlLocalized.cs 4 2006-06-15 04:28:39Z mark $
*
***************************************************************************/
/***************************************************************************
*
* 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.
*
***************************************************************************/
using System;
using Server.Network;
namespace Server.Gumps
{
public enum GumpHtmlLocalizedType
{
Plain,
Color,
Args
}
public class GumpHtmlLocalized : GumpEntry
{
private int m_X, m_Y;
private int m_Width, m_Height;
private int m_Number;
private string m_Args;
private int m_Color;
private bool m_Background, m_Scrollbar;
private GumpHtmlLocalizedType m_Type;
public int X
{
get
{
return m_X;
}
set
{
Delta( ref m_X, value );
}
}
public int Y
{
get
{
return m_Y;
}
set
{
Delta( ref m_Y, value );
}
}
public int Width
{
get
{
return m_Width;
}
set
{
Delta( ref m_Width, value );
}
}
public int Height
{
get
{
return m_Height;
}
set
{
Delta( ref m_Height, value );
}
}
public int Number
{
get
{
return m_Number;
}
set
{
Delta( ref m_Number, value );
}
}
public string Args
{
get
{
return m_Args;
}
set
{
Delta( ref m_Args, value );
}
}
public int Color
{
get
{
return m_Color;
}
set
{
Delta( ref m_Color, value );
}
}
public bool Background
{
get
{
return m_Background;
}
set
{
Delta( ref m_Background, value );
}
}
public bool Scrollbar
{
get
{
return m_Scrollbar;
}
set
{
Delta( ref m_Scrollbar, value );
}
}
public GumpHtmlLocalizedType Type
{
get
{
return m_Type;
}
set
{
if ( m_Type != value )
{
m_Type = value;
if ( Parent != null )
Parent.Invalidate();
}
}
}
public GumpHtmlLocalized( int x, int y, int width, int height, int number, bool background, bool scrollbar )
{
m_X = x;
m_Y = y;
m_Width = width;
m_Height = height;
m_Number = number;
m_Background = background;
m_Scrollbar = scrollbar;
m_Type = GumpHtmlLocalizedType.Plain;
}
public GumpHtmlLocalized( int x, int y, int width, int height, int number, int color, bool background, bool scrollbar )
{
m_X = x;
m_Y = y;
m_Width = width;
m_Height = height;
m_Number = number;
m_Color = color;
m_Background = background;
m_Scrollbar = scrollbar;
m_Type = GumpHtmlLocalizedType.Color;
}
public GumpHtmlLocalized( int x, int y, int width, int height, int number, string args, int color, bool background, bool scrollbar )
{
// Are multiple arguments unsupported? And what about non ASCII arguments?
m_X = x;
m_Y = y;
m_Width = width;
m_Height = height;
m_Number = number;
m_Args = args;
m_Color = color;
m_Background = background;
m_Scrollbar = scrollbar;
m_Type = GumpHtmlLocalizedType.Args;
}
public override string Compile()
{
switch ( m_Type )
{
case GumpHtmlLocalizedType.Plain:
return String.Format( "{{ xmfhtmlgump {0} {1} {2} {3} {4} {5} {6} }}", m_X, m_Y, m_Width, m_Height, m_Number, m_Background ? 1 : 0, m_Scrollbar ? 1 : 0 );
case GumpHtmlLocalizedType.Color:
return String.Format( "{{ xmfhtmlgumpcolor {0} {1} {2} {3} {4} {5} {6} {7} }}", m_X, m_Y, m_Width, m_Height, m_Number, m_Background ? 1 : 0, m_Scrollbar ? 1 : 0, m_Color );
default: // GumpHtmlLocalizedType.Args
return String.Format( "{{ xmfhtmltok {0} {1} {2} {3} {4} {5} {6} {7} @{8}@ }}", m_X, m_Y, m_Width, m_Height, m_Background ? 1 : 0, m_Scrollbar ? 1 : 0, m_Color, m_Number, m_Args );
}
}
private static byte[] m_LayoutNamePlain = Gump.StringToBuffer( "xmfhtmlgump" );
private static byte[] m_LayoutNameColor = Gump.StringToBuffer( "xmfhtmlgumpcolor" );
private static byte[] m_LayoutNameArgs = Gump.StringToBuffer( "xmfhtmltok" );
public override void AppendTo( IGumpWriter disp )
{
switch ( m_Type )
{
case GumpHtmlLocalizedType.Plain:
{
disp.AppendLayout( m_LayoutNamePlain );
disp.AppendLayout( m_X );
disp.AppendLayout( m_Y );
disp.AppendLayout( m_Width );
disp.AppendLayout( m_Height );
disp.AppendLayout( m_Number );
disp.AppendLayout( m_Background );
disp.AppendLayout( m_Scrollbar );
break;
}
case GumpHtmlLocalizedType.Color:
{
disp.AppendLayout( m_LayoutNameColor );
disp.AppendLayout( m_X );
disp.AppendLayout( m_Y );
disp.AppendLayout( m_Width );
disp.AppendLayout( m_Height );
disp.AppendLayout( m_Number );
disp.AppendLayout( m_Background );
disp.AppendLayout( m_Scrollbar );
disp.AppendLayout( m_Color );
break;
}
case GumpHtmlLocalizedType.Args:
{
disp.AppendLayout( m_LayoutNameArgs );
disp.AppendLayout( m_X );
disp.AppendLayout( m_Y );
disp.AppendLayout( m_Width );
disp.AppendLayout( m_Height );
disp.AppendLayout( m_Background );
disp.AppendLayout( m_Scrollbar );
disp.AppendLayout( m_Color );
disp.AppendLayout( m_Number );
disp.AppendLayout( m_Args );
break;
}
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// ScaledSpriteBatch.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
#endregion
namespace HoneycombRush
{
/// <summary>
/// Represents a spritebatch where all drawing operations are scaled by a specific non-uniform factor. If a draw
/// operation specifies a specific scale factor, it will be multiplied by the default one.
/// </summary>
public class ScaledSpriteBatch : SpriteBatch
{
#region Properties
/// <summary>
/// Determines the scale factor for all drawing operations
/// </summary>
public Vector2 ScaleVector { get; set; }
#endregion
#region Initialization
public ScaledSpriteBatch(GraphicsDevice graphicsDevice, Vector2 initialScale) : base(graphicsDevice)
{
ScaleVector = initialScale;
}
#endregion
#region Draw overrides
/// <summary>
/// Adds a sprite to a batch of sprites for rendering using the specified texture,
/// position and color. Reference page contains links to related code samples.
/// </summary>
/// <param name="texture">A texture.</param>
/// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
/// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
/// <remarks>The drawing operation will be scaled according to the <see cref="ScaleVector"/>
/// property.</remarks>
public new void Draw(Texture2D texture, Vector2 position, Color color)
{
base.Draw(texture, position, null, color, 0, Vector2.Zero, ScaleVector, SpriteEffects.None, 0);
}
/// <summary>
/// Adds a sprite to a batch of sprites for rendering using the specified texture,
/// position, source rectangle, and color.
/// </summary>
/// <param name="texture">A texture.</param>
/// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
/// <param name="sourceRectangle">A rectangle that specifies (in texels) the source texels from a texture.
/// Use null to draw the entire texture.</param>
/// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
/// <remarks>The drawing operation will be scaled according to the <see cref="ScaleVector"/>
/// property.</remarks>
public new void Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color)
{
base.Draw(texture, position, sourceRectangle, color, 0, Vector2.Zero, ScaleVector, SpriteEffects.None, 0);
}
/// <summary>
/// Adds a sprite to a batch of sprites for rendering using the specified texture,
/// position, source rectangle, color, rotation, origin, scale, effects, and
/// layer. Reference page contains links to related code samples.
/// </summary>
/// <param name="texture">A texture.</param>
/// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
/// <param name="sourceRectangle">A rectangle that specifies (in texels) the source texels from a texture.
/// Use null to draw the entire texture.</param>
/// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
/// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
/// <param name="origin">The sprite origin; the default is (0,0) which represents the
/// upper-left corner.</param>
/// <param name="scale">Scale factor.</param>
/// <param name="effects">Effects to apply.</param>
/// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents
/// a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
/// <remarks>The drawing operation will be scaled according to the <see cref="ScaleVector"/>
/// property.</remarks>
public new void Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color,
float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth)
{
base.Draw(texture, position, sourceRectangle, color, rotation, origin, scale * ScaleVector, effects,
layerDepth);
}
/// <summary>
/// Adds a sprite to a batch of sprites for rendering using the specified texture,
/// position, source rectangle, color, rotation, origin, scale, effects and layer.
/// Reference page contains links to related code samples.
/// </summary>
/// <param name="texture">A texture.</param>
/// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
/// <param name="sourceRectangle">A rectangle that specifies (in texels) the source texels from a texture.
/// Use null to draw the entire texture.</param>
/// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
/// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
/// <param name="origin">The sprite origin; the default is (0,0) which represents the
/// upper-left corner.</param>
/// <param name="scale">Scale factor.</param>
/// <param name="effects">Effects to apply.</param>
/// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents
/// a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
/// <remarks>The drawing operation will be scaled according to the <see cref="ScaleVector"/>
/// property.</remarks>
public new void Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color,
float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth)
{
base.Draw(texture, position, sourceRectangle, color, rotation, origin, scale * ScaleVector, effects,
layerDepth);
}
/// <summary>
/// Adds a string to a batch of sprites for rendering using the specified font,
/// text, position, and color.
/// </summary>
/// <param name="spriteFont">A font for diplaying text</param>
/// <param name="text">A text string.</param>
/// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
/// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
/// <remarks>The drawing operation will be scaled according to the <see cref="ScaleVector"/>
/// property.</remarks>
public new void DrawString(SpriteFont spriteFont, string text, Vector2 position, Color color)
{
base.DrawString(spriteFont, text, position, color, 0, Vector2.Zero, ScaleVector, SpriteEffects.None, 0);
}
/// <summary>
/// Adds a string to a batch of sprites for rendering using the specified font,
/// text, position, and color.
/// </summary>
/// <param name="spriteFont">A font for diplaying text.</param>
/// <param name="text">A text string.</param>
/// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
/// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
/// <remarks>The drawing operation will be scaled according to the <see cref="ScaleVector"/>
/// property.</remarks>
public new void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2 position, Color color)
{
base.DrawString(spriteFont, text, position, color, 0, Vector2.Zero, ScaleVector, SpriteEffects.None, 0);
}
/// <summary>
/// Adds a string to a batch of sprites for rendering using the specified font,
/// text, position, color, rotation, origin, scale, effects and layer.
/// </summary>
/// <param name="spriteFont">A font for diplaying text.</param>
/// <param name="text">A text string.</param>
/// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
/// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
/// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
/// <param name="origin">The sprite origin; the default is (0,0) which represents the
/// upper-left corner.</param>
/// <param name="scale">Scale factor.</param>
/// <param name="effects">Effects to apply.</param>
/// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents
/// a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
/// <remarks>The drawing operation will be scaled according to the <see cref="ScaleVector"/>
/// property.</remarks>
public new void DrawString(SpriteFont spriteFont, string text, Vector2 position, Color color, float rotation,
Vector2 origin, float scale, SpriteEffects effects, float layerDepth)
{
base.DrawString(spriteFont, text, position, color, rotation, origin, scale * ScaleVector, effects,
layerDepth);
}
/// <summary>
/// Adds a string to a batch of sprites for rendering using the specified font,
/// text, position, color, rotation, origin, scale, effects and layer.
/// </summary>
/// <param name="spriteFont">A font for diplaying text.</param>
/// <param name="text">A text string.</param>
/// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
/// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
/// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
/// <param name="origin">The sprite origin; the default is (0,0) which represents the upper-left
/// corner.</param>
/// <param name="scale">Scale factor.</param>
/// <param name="effects">Effects to apply.</param>
/// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents
/// a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
/// <remarks>The drawing operation will be scaled according to the <see cref="ScaleVector"/>
/// property.</remarks>
public new void DrawString(SpriteFont spriteFont, string text, Vector2 position, Color color, float rotation,
Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth)
{
DrawString(spriteFont, text, position, color, rotation, origin, scale * ScaleVector, effects, layerDepth);
}
/// <summary>
/// Adds a string to a batch of sprites for rendering using the specified font,
/// text, position, color, rotation, origin, scale, effects and layer.
/// </summary>
/// <param name="spriteFont">A font for diplaying text.</param>
/// <param name="text">Text string.</param>
/// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
/// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
/// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
/// <param name="origin">The sprite origin; the default is (0,0) which represents the upper-left
/// corner.</param>
/// <param name="scale">Scale factor.</param>
/// <param name="effects">Effects to apply.</param>
/// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents
/// a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
/// <remarks>The drawing operation will be scaled according to the <see cref="ScaleVector"/>
/// property.</remarks>
public new void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2 position, Color color,
float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth)
{
base.DrawString(spriteFont, text, position, color, rotation, origin, scale * ScaleVector, effects,
layerDepth);
}
/// <summary>
/// Adds a string to a batch of sprites for rendering using the specified font,
/// text, position, color, rotation, origin, scale, effects and layer.
/// </summary>
/// <param name="spriteFont">A font for diplaying text.</param>
/// <param name="text">Text string.</param>
/// <param name="position">The location (in screen coordinates) to draw the sprite.</param>
/// <param name="color">The color to tint a sprite. Use Color.White for full color with no tinting.</param>
/// <param name="rotation">Specifies the angle (in radians) to rotate the sprite about its center.</param>
/// <param name="origin">The sprite origin; the default is (0,0) which represents the upper-left
/// corner.</param>
/// <param name="scale">Scale factor.</param>
/// <param name="effects">Effects to apply.</param>
/// <param name="layerDepth">The depth of a layer. By default, 0 represents the front layer and 1 represents
/// a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.</param>
/// <remarks>The drawing operation will be scaled according to the <see cref="ScaleVector"/>
/// property.</remarks>
public new void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2 position, Color color,
float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth)
{
base.DrawString(spriteFont, text, position, color, rotation, origin, scale * ScaleVector,
effects, layerDepth);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Collections.ObjectModel
{
public abstract partial class KeyedCollection<TKey, TItem> : System.Collections.ObjectModel.Collection<TItem>
{
protected KeyedCollection() { }
protected KeyedCollection(System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
protected KeyedCollection(System.Collections.Generic.IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold) { }
public System.Collections.Generic.IEqualityComparer<TKey> Comparer { get { throw null; } }
protected System.Collections.Generic.IDictionary<TKey, TItem> Dictionary { get { throw null; } }
public TItem this[TKey key] { get { throw null; } }
protected void ChangeItemKey(TItem item, TKey newKey) { }
protected override void ClearItems() { }
public bool Contains(TKey key) { throw null; }
protected abstract TKey GetKeyForItem(TItem item);
protected override void InsertItem(int index, TItem item) { }
public bool Remove(TKey key) { throw null; }
protected override void RemoveItem(int index) { }
protected override void SetItem(int index, TItem item) { }
public bool TryGetValue(TKey key, out TItem item) { throw null; }
}
public partial class ObservableCollection<T> : System.Collections.ObjectModel.Collection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged
{
public ObservableCollection() { }
public ObservableCollection(System.Collections.Generic.IEnumerable<T> collection) { }
public ObservableCollection(System.Collections.Generic.List<T> list) { }
public virtual event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged { add { } remove { } }
protected virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged { add { } remove { } }
event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } }
protected System.IDisposable BlockReentrancy() { throw null; }
protected void CheckReentrancy() { }
protected override void ClearItems() { }
protected override void InsertItem(int index, T item) { }
public void Move(int oldIndex, int newIndex) { }
protected virtual void MoveItem(int oldIndex, int newIndex) { }
protected virtual void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { }
protected virtual void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e) { }
protected override void RemoveItem(int index) { }
protected override void SetItem(int index, T item) { }
}
public partial class ReadOnlyDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public ReadOnlyDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { }
public int Count { get { throw null; } }
protected System.Collections.Generic.IDictionary<TKey, TValue> Dictionary { get { throw null; } }
public TValue this[TKey key] { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.KeyCollection Keys { get { throw null; } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.IsReadOnly { get { throw null; } }
TValue System.Collections.Generic.IDictionary<TKey,TValue>.this[TKey key] { get { throw null; } set { } }
System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey,TValue>.Keys { get { throw null; } }
System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey,TValue>.Values { get { throw null; } }
System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Keys { get { throw null; } }
System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Values { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
bool System.Collections.IDictionary.IsFixedSize { get { throw null; } }
bool System.Collections.IDictionary.IsReadOnly { get { throw null; } }
object System.Collections.IDictionary.this[object key] { get { throw null; } set { } }
System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } }
System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.ValueCollection Values { get { throw null; } }
public bool ContainsKey(TKey key) { throw null; }
public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Clear() { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int arrayIndex) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { throw null; }
void System.Collections.Generic.IDictionary<TKey,TValue>.Add(TKey key, TValue value) { }
bool System.Collections.Generic.IDictionary<TKey,TValue>.Remove(TKey key) { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
void System.Collections.IDictionary.Add(object key, object value) { }
void System.Collections.IDictionary.Clear() { }
bool System.Collections.IDictionary.Contains(object key) { throw null; }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; }
void System.Collections.IDictionary.Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public bool TryGetValue(TKey key, out TValue value) { throw null; }
public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable
{
internal KeyCollection() { }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void CopyTo(TKey[] array, int arrayIndex) { }
public System.Collections.Generic.IEnumerator<TKey> GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { }
void System.Collections.Generic.ICollection<TKey>.Clear() { }
bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { throw null; }
bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable
{
internal ValueCollection() { }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void CopyTo(TValue[] array, int arrayIndex) { }
public System.Collections.Generic.IEnumerator<TValue> GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { }
void System.Collections.Generic.ICollection<TValue>.Clear() { }
bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { throw null; }
bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
}
public partial class ReadOnlyObservableCollection<T> : System.Collections.ObjectModel.ReadOnlyCollection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged
{
public ReadOnlyObservableCollection(System.Collections.ObjectModel.ObservableCollection<T> list) : base (default(System.Collections.Generic.IList<T>)) { }
protected virtual event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged { add { } remove { } }
protected virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged { add { } remove { } }
event System.Collections.Specialized.NotifyCollectionChangedEventHandler System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged { add { } remove { } }
event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } }
protected virtual void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs args) { }
protected virtual void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args) { }
}
}
namespace System.Collections.Specialized
{
public partial interface INotifyCollectionChanged
{
event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged;
}
public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}
public partial class NotifyCollectionChangedEventArgs : System.EventArgs
{
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems, int startingIndex) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems, int startingIndex) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems, int index, int oldIndex) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem, int index) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object newItem, object oldItem) { }
public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object newItem, object oldItem, int index) { }
public System.Collections.Specialized.NotifyCollectionChangedAction Action { get { throw null; } }
public System.Collections.IList NewItems { get { throw null; } }
public int NewStartingIndex { get { throw null; } }
public System.Collections.IList OldItems { get { throw null; } }
public int OldStartingIndex { get { throw null; } }
}
public delegate void NotifyCollectionChangedEventHandler(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e);
}
namespace System.ComponentModel
{
public partial class DataErrorsChangedEventArgs : System.EventArgs
{
public DataErrorsChangedEventArgs(string propertyName) { }
public virtual string PropertyName { get { throw null; } }
}
public partial interface INotifyDataErrorInfo
{
bool HasErrors { get; }
event System.EventHandler<System.ComponentModel.DataErrorsChangedEventArgs> ErrorsChanged;
System.Collections.IEnumerable GetErrors(string propertyName);
}
public partial interface INotifyPropertyChanged
{
event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
}
public partial interface INotifyPropertyChanging
{
event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
}
public partial class PropertyChangedEventArgs : System.EventArgs
{
public PropertyChangedEventArgs(string propertyName) { }
public virtual string PropertyName { get { throw null; } }
}
public delegate void PropertyChangedEventHandler(object sender, System.ComponentModel.PropertyChangedEventArgs e);
public partial class PropertyChangingEventArgs : System.EventArgs
{
public PropertyChangingEventArgs(string propertyName) { }
public virtual string PropertyName { get { throw null; } }
}
public delegate void PropertyChangingEventHandler(object sender, System.ComponentModel.PropertyChangingEventArgs e);
[System.AttributeUsageAttribute(System.AttributeTargets.All)]
public sealed partial class TypeConverterAttribute : System.Attribute
{
public static readonly System.ComponentModel.TypeConverterAttribute Default;
public TypeConverterAttribute() { }
public TypeConverterAttribute(string typeName) { }
public TypeConverterAttribute(System.Type type) { }
public string ConverterTypeName { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class, Inherited=true)]
public sealed partial class TypeDescriptionProviderAttribute : System.Attribute
{
public TypeDescriptionProviderAttribute(string typeName) { }
public TypeDescriptionProviderAttribute(System.Type type) { }
public string TypeName { get { throw null; } }
}
}
namespace System.Reflection
{
public partial interface ICustomTypeProvider
{
System.Type GetCustomType();
}
}
namespace System.Windows.Input
{
[System.ComponentModel.TypeConverterAttribute("System.Windows.Input.CommandConverter, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")]
[System.Windows.Markup.ValueSerializerAttribute("System.Windows.Input.CommandValueSerializer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")]
public partial interface ICommand
{
event System.EventHandler CanExecuteChanged;
bool CanExecute(object parameter);
void Execute(object parameter);
}
}
namespace System.Windows.Markup
{
[System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=true)]
public sealed partial class ValueSerializerAttribute : System.Attribute
{
public ValueSerializerAttribute(string valueSerializerTypeName) { }
public ValueSerializerAttribute(System.Type valueSerializerType) { }
public System.Type ValueSerializerType { get { throw null; } }
public string ValueSerializerTypeName { get { throw null; } }
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
{
public class AsynchronousOperationListenerTests
{
private static readonly int s_testTimeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;
private class Listener : AsynchronousOperationListener
{
}
private class SleepHelper : IDisposable
{
private readonly CancellationTokenSource _tokenSource;
private readonly List<Task> _tasks = new List<Task>();
public SleepHelper()
{
_tokenSource = new CancellationTokenSource();
}
~SleepHelper()
{
if (!Environment.HasShutdownStarted)
{
Contract.Fail("Should have been disposed");
}
}
public void Dispose()
{
_tokenSource.Cancel();
try
{
Task.WaitAll(_tasks.ToArray());
}
catch (AggregateException e)
{
foreach (var inner in e.InnerExceptions)
{
Assert.IsType<TaskCanceledException>(inner);
}
}
GC.SuppressFinalize(this);
}
public void Sleep(TimeSpan timeToSleep)
{
var task = Task.Factory.SafeStartNew(() =>
{
while (true)
{
_tokenSource.Token.ThrowIfCancellationRequested();
Thread.Sleep(TimeSpan.FromMilliseconds(10));
}
}, _tokenSource.Token, TaskScheduler.Default);
_tasks.Add(task);
task.Wait((int)timeToSleep.TotalMilliseconds);
}
}
[Fact]
public void Operation()
{
using (var sleepHelper = new SleepHelper())
{
var signal = new ManualResetEventSlim();
var listener = new Listener();
var done = false;
var asyncToken = listener.BeginAsyncOperation("Test");
var task = new Task(() =>
{
signal.Set();
sleepHelper.Sleep(TimeSpan.FromSeconds(1));
done = true;
});
task.CompletesAsyncOperation(asyncToken);
task.Start();
Wait(listener, signal);
Assert.True(done, "The operation should have completed");
}
}
[Fact]
public void QueuedOperation()
{
using (var sleepHelper = new SleepHelper())
{
var signal = new ManualResetEventSlim();
var listener = new Listener();
var done = false;
var asyncToken1 = listener.BeginAsyncOperation("Test");
var task = new Task(() =>
{
signal.Set();
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
var asyncToken2 = listener.BeginAsyncOperation("Test");
var queuedTask = new Task(() =>
{
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
done = true;
});
queuedTask.CompletesAsyncOperation(asyncToken2);
queuedTask.Start();
});
task.CompletesAsyncOperation(asyncToken1);
task.Start();
Wait(listener, signal);
Assert.True(done, "Should have waited for the queued operation to finish!");
}
}
[Fact(/*Skip = "Throwing ContractFailure on a TPL thread?"*/)]
public void Cancel()
{
using (var sleepHelper = new SleepHelper())
{
var signal = new ManualResetEventSlim();
var listener = new Listener();
var done = false;
var continued = false;
var asyncToken1 = listener.BeginAsyncOperation("Test");
var task = new Task(() =>
{
signal.Set();
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
var asyncToken2 = listener.BeginAsyncOperation("Test");
var queuedTask = new Task(() =>
{
sleepHelper.Sleep(TimeSpan.FromSeconds(5));
continued = true;
});
asyncToken2.Dispose();
queuedTask.Start();
done = true;
});
task.CompletesAsyncOperation(asyncToken1);
task.Start();
Wait(listener, signal);
Assert.True(done, "Cancelling should have completed the current task.");
Assert.False(continued, "Continued Task when it shouldn't have.");
}
}
[Fact]
public void Nested()
{
using (var sleepHelper = new SleepHelper())
{
var signal = new ManualResetEventSlim();
var listener = new Listener();
var outerDone = false;
var innerDone = false;
var asyncToken1 = listener.BeginAsyncOperation("Test");
var task = new Task(() =>
{
signal.Set();
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
using (listener.BeginAsyncOperation("Test"))
{
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
innerDone = true;
}
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
outerDone = true;
});
task.CompletesAsyncOperation(asyncToken1);
task.Start();
Wait(listener, signal);
Assert.True(innerDone, "Should have completed the inner task");
Assert.True(outerDone, "Should have completed the outer task");
}
}
[Fact]
public void MultipleEnqueues()
{
using (var sleepHelper = new SleepHelper())
{
var signal = new ManualResetEventSlim();
var listener = new Listener();
var outerDone = false;
var firstQueuedDone = false;
var secondQueuedDone = false;
var asyncToken1 = listener.BeginAsyncOperation("Test");
var task = new Task(() =>
{
signal.Set();
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
var asyncToken2 = listener.BeginAsyncOperation("Test");
var firstQueueTask = new Task(() =>
{
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
var asyncToken3 = listener.BeginAsyncOperation("Test");
var secondQueueTask = new Task(() =>
{
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
secondQueuedDone = true;
});
secondQueueTask.CompletesAsyncOperation(asyncToken3);
secondQueueTask.Start();
firstQueuedDone = true;
});
firstQueueTask.CompletesAsyncOperation(asyncToken2);
firstQueueTask.Start();
outerDone = true;
});
task.CompletesAsyncOperation(asyncToken1);
task.Start();
Wait(listener, signal);
Assert.True(outerDone, "The outer task should have finished!");
Assert.True(firstQueuedDone, "The first queued task should have finished");
Assert.True(secondQueuedDone, "The second queued task should have finished");
}
}
[Fact]
public void IgnoredCancel()
{
using (var sleepHelper = new SleepHelper())
{
var signal = new ManualResetEventSlim();
var listener = new Listener();
var done = false;
var queuedFinished = false;
var cancelledFinished = false;
var asyncToken1 = listener.BeginAsyncOperation("Test");
var task = new Task(() =>
{
using (listener.BeginAsyncOperation("Test"))
{
var cancelledTask = new Task(() =>
{
sleepHelper.Sleep(TimeSpan.FromSeconds(10));
cancelledFinished = true;
});
signal.Set();
cancelledTask.Start();
}
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
// Now that we've cancelled the first request, queue another one to make sure we wait for it.
var asyncToken2 = listener.BeginAsyncOperation("Test");
var queuedTask = new Task(() =>
{
sleepHelper.Sleep(TimeSpan.FromSeconds(1));
queuedFinished = true;
});
queuedTask.CompletesAsyncOperation(asyncToken2);
queuedTask.Start();
done = true;
});
task.CompletesAsyncOperation(asyncToken1);
task.Start();
Wait(listener, signal);
Assert.True(done, "Cancelling should have completed the current task.");
Assert.True(queuedFinished, "Continued didn't run, but it was supposed to ignore the cancel.");
Assert.False(cancelledFinished, "We waited for the cancelled task to finish.");
}
}
[Fact]
public void SecondCompletion()
{
using (var sleepHelper = new SleepHelper())
{
var signal1 = new ManualResetEventSlim();
var signal2 = new ManualResetEventSlim();
var listener = new Listener();
var firstDone = false;
var secondDone = false;
var asyncToken1 = listener.BeginAsyncOperation("Test");
var firstTask = Task.Factory.StartNew(() =>
{
signal1.Set();
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
firstDone = true;
});
firstTask.CompletesAsyncOperation(asyncToken1);
firstTask.Wait();
var asyncToken2 = listener.BeginAsyncOperation("Test");
var secondTask = Task.Factory.StartNew(() =>
{
signal2.Set();
sleepHelper.Sleep(TimeSpan.FromMilliseconds(500));
secondDone = true;
});
secondTask.CompletesAsyncOperation(asyncToken2);
// give it two signals since second one might not have started when WaitTask.Wait is called - race condition
Wait(listener, signal1, signal2);
Assert.True(firstDone, "First didn't finish");
Assert.True(secondDone, "Should have waited for the second task");
}
}
private static void Wait(Listener listener, ManualResetEventSlim signal)
{
// Note: WaitTask will return immediately if there is no outstanding work. Due to
// threadpool scheduling, we may get here before that other thread has started to run.
// That's why each task set's a signal to say that it has begun and we first wait for
// that, and then start waiting.
Assert.True(signal.Wait(s_testTimeout), "Shouldn't have hit timeout waiting for task to begin");
var waitTask = listener.CreateWaitTask();
Assert.True(waitTask.Wait(s_testTimeout), "Wait shouldn't have needed to timeout");
}
private static void Wait(Listener listener, ManualResetEventSlim signal1, ManualResetEventSlim signal2)
{
// Note: WaitTask will return immediately if there is no outstanding work. Due to
// threadpool scheduling, we may get here before that other thread has started to run.
// That's why each task set's a signal to say that it has begun and we first wait for
// that, and then start waiting.
Assert.True(signal1.Wait(s_testTimeout), "Shouldn't have hit timeout waiting for task to begin");
Assert.True(signal2.Wait(s_testTimeout), "Shouldn't have hit timeout waiting for task to begin");
var waitTask = listener.CreateWaitTask();
Assert.True(waitTask.Wait(s_testTimeout), "Wait shouldn't have needed to timeout");
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.WindowsAzure.Commands.Tools.Vhd.Model;
using Microsoft.WindowsAzure.Commands.Tools.Vhd.Model.Persistence;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.WindowsAzure.Commands.Sync.Upload
{
public static class CloudPageBlobExtensions
{
public static IEnumerable<IListBlobItem> ListContainerBlobs(
this CloudBlobContainer container,
bool useFlatBlobListing,
BlobListingDetails details,
BlobRequestOptions options)
{
BlobContinuationToken continuationToken = null;
string prefix = null;
int maxBlobsPerRequest = 10;
List<IListBlobItem> blobs = new List<IListBlobItem>();
do
{
var listingResult = container.ListBlobsSegmentedAsync(
prefix, useFlatBlobListing, details, maxBlobsPerRequest, continuationToken, options, null)
.ConfigureAwait(false)
.GetAwaiter().GetResult();
continuationToken = listingResult.ContinuationToken;
blobs.AddRange(listingResult.Results);
}
while (continuationToken != null);
return blobs;
}
public static void SetUploadMetaData(this CloudPageBlob blob, LocalMetaData metaData)
{
if (metaData == null)
{
throw new ArgumentNullException("metaData");
}
blob.Metadata[LocalMetaData.MetaDataKey] = SerializationUtil.GetSerializedString(metaData);
}
public static void CleanUpUploadMetaData(this CloudPageBlob blob)
{
blob.Metadata.Remove(LocalMetaData.MetaDataKey);
}
public static LocalMetaData GetUploadMetaData(this CloudPageBlob blob)
{
if (blob.Metadata.Keys.Contains(LocalMetaData.MetaDataKey))
{
return SerializationUtil.GetObjectFromSerializedString<LocalMetaData>(blob.Metadata[LocalMetaData.MetaDataKey]);
}
return null;
}
public static byte[] GetBlobMd5Hash(this CloudPageBlob blob)
{
blob.FetchAttributesAsync().ConfigureAwait(false).GetAwaiter().GetResult();
if (String.IsNullOrEmpty(blob.Properties.ContentMD5))
{
return null;
}
return Convert.FromBase64String(blob.Properties.ContentMD5);
}
public static byte[] GetBlobMd5Hash(this CloudPageBlob blob, BlobRequestOptions requestOptions)
{
blob.FetchAttributesAsync(new AccessCondition(), requestOptions, operationContext: null)
.ConfigureAwait(false).GetAwaiter().GetResult();
if (String.IsNullOrEmpty(blob.Properties.ContentMD5))
{
return null;
}
return Convert.FromBase64String(blob.Properties.ContentMD5);
}
public static void SetBlobMd5Hash(this CloudPageBlob blob, byte[] md5Hash)
{
var base64String = Convert.ToBase64String(md5Hash);
blob.Properties.ContentMD5 = base64String;
}
public static void RemoveBlobMd5Hash(this CloudPageBlob blob)
{
blob.Properties.ContentMD5 = null;
}
public static VhdFooter GetVhdFooter(this CloudPageBlob basePageBlob)
{
var vhdFileFactory = new VhdFileFactory();
using (var file = vhdFileFactory.Create(basePageBlob.OpenReadAsync().ConfigureAwait(false).GetAwaiter().GetResult()))
{
return file.Footer;
}
}
public static bool Exists(this CloudPageBlob blob)
{
var listBlobItems = blob.Container.ListContainerBlobs(false, BlobListingDetails.None, null);
var blobToUpload = listBlobItems.FirstOrDefault(b => b.Uri == blob.Uri);
if (blobToUpload is CloudBlockBlob)
{
var message = String.Format(" CsUpload is expecting a page blob, however a block blob was found: '{0}'.", blob.Uri);
throw new InvalidOperationException(message);
}
return blobToUpload != null;
}
public static bool Exists(this CloudPageBlob blob, BlobRequestOptions options)
{
var listBlobItems = blob.Container.ListContainerBlobs(false, BlobListingDetails.UncommittedBlobs, options);
var blobToUpload = listBlobItems.FirstOrDefault(b => b.Uri == blob.Uri);
if (blobToUpload is CloudBlockBlob)
{
var message = String.Format(" CsUpload is expecting a page blob, however a block blob was found: '{0}'.", blob.Uri);
throw new InvalidOperationException(message);
}
return blobToUpload != null;
}
}
internal static class StringExtensions
{
public static string ToString<T>(this IEnumerable<T> source, string separator)
{
return "[" + string.Join(",", source.Select(s => s.ToString()).ToArray()) + "]";
}
}
public class VhdFilePath
{
public VhdFilePath(string absolutePath, string relativePath)
{
AbsolutePath = absolutePath;
RelativePath = relativePath;
}
public string AbsolutePath { get; private set; }
public string RelativePath { get; private set; }
}
internal static class VhdFileExtensions
{
public static IEnumerable<Guid> GetChildrenIds(this VhdFile vhdFile, Guid uniqueId)
{
var identityChain = vhdFile.GetIdentityChain();
if (!identityChain.Contains(uniqueId))
{
yield break;
}
foreach (var id in identityChain.TakeWhile(id => id != uniqueId))
{
yield return id;
}
}
public static VhdFilePath GetFilePathBy(this VhdFile vhdFile, Guid uniqueId)
{
VhdFilePath result = null;
string baseVhdPath = String.Empty;
var newBlocksOwners = new List<Guid> { Guid.Empty };
var current = vhdFile;
while (current != null && current.Footer.UniqueId != uniqueId)
{
newBlocksOwners.Add(current.Footer.UniqueId);
if (current.Parent != null)
{
result = new VhdFilePath(current.Header.GetAbsoluteParentPath(),
current.Header.GetRelativeParentPath());
}
current = current.Parent;
}
if (result == null)
{
string message = String.Format("There is no parent VHD file with with the id '{0}'", uniqueId);
throw new InvalidOperationException(message);
}
return result;
}
}
public static class UriExtensions
{
/// <summary>
/// Normalizes a URI for use as a blob URI.
/// </summary>
/// <remarks>
/// Ensures that the container name is lower-case.
/// </remarks>
public static Uri NormalizeBlobUri(this Uri uri)
{
var ub = new UriBuilder(uri);
var parts = ub.Path
.Split(new char[] { '/' }, StringSplitOptions.None)
.Select((p, i) => i == 1 ? p.ToLowerInvariant() : p)
.ToArray();
ub.Path = string.Join("/", parts);
return ub.Uri;
}
}
public static class ExceptionUtil
{
public static string DumpStorageExceptionErrorDetails(StorageException storageException)
{
if (storageException == null)
{
return string.Empty;
}
var message = new StringBuilder();
message.AppendLine("StorageException details");
#if NETSTANDARD
message.Append("Error.Code:").AppendLine(storageException.RequestInformation.ErrorCode);
#else
message.Append("Error.Code:").AppendLine(storageException.RequestInformation.ExtendedErrorInformation.ErrorCode);
#endif
message.Append("ErrorMessage:").AppendLine(storageException.RequestInformation.ExtendedErrorInformation.ErrorMessage);
foreach (var key in storageException.RequestInformation.ExtendedErrorInformation.AdditionalDetails.Keys)
{
message.Append(key).Append(":").Append(storageException.RequestInformation.ExtendedErrorInformation.AdditionalDetails[key]);
}
return message.ToString();
}
}
}
| |
using System;
using Csla;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// InvoiceEdit (editable root object).<br/>
/// This is a generated base class of <see cref="InvoiceEdit"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="InvoiceLines"/> of type <see cref="InvoiceLineCollection"/> (1:M relation to <see cref="InvoiceLineItem"/>)
/// </remarks>
[Serializable]
public partial class InvoiceEdit : BusinessBase<InvoiceEdit>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="InvoiceId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<Guid> InvoiceIdProperty = RegisterProperty<Guid>(p => p.InvoiceId, "Invoice Id");
/// <summary>
/// The invoice internal identification
/// </summary>
/// <value>The Invoice Id.</value>
public Guid InvoiceId
{
get { return GetProperty(InvoiceIdProperty); }
set { SetProperty(InvoiceIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="InvoiceNumber"/> property.
/// </summary>
public static readonly PropertyInfo<string> InvoiceNumberProperty = RegisterProperty<string>(p => p.InvoiceNumber, "Invoice Number");
/// <summary>
/// The public invoice number
/// </summary>
/// <value>The Invoice Number.</value>
public string InvoiceNumber
{
get { return GetProperty(InvoiceNumberProperty); }
set { SetProperty(InvoiceNumberProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CustomerId"/> property.
/// </summary>
public static readonly PropertyInfo<string> CustomerIdProperty = RegisterProperty<string>(p => p.CustomerId, "Customer Id");
/// <summary>
/// Gets or sets the Customer Id.
/// </summary>
/// <value>The Customer Id.</value>
public string CustomerId
{
get { return GetProperty(CustomerIdProperty); }
set { SetProperty(CustomerIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="InvoiceDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> InvoiceDateProperty = RegisterProperty<SmartDate>(p => p.InvoiceDate, "Invoice Date");
/// <summary>
/// Gets or sets the Invoice Date.
/// </summary>
/// <value>The Invoice Date.</value>
public string InvoiceDate
{
get { return GetPropertyConvert<SmartDate, string>(InvoiceDateProperty); }
set { SetPropertyConvert<SmartDate, string>(InvoiceDateProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="TotalAmount"/> property.
/// </summary>
public static readonly PropertyInfo<decimal> TotalAmountProperty = RegisterProperty<decimal>(p => p.TotalAmount, "Total Amount");
/// <summary>
/// Computed invoice total amount
/// </summary>
/// <value>The Total Amount.</value>
public decimal TotalAmount
{
get { return GetProperty(TotalAmountProperty); }
set { SetProperty(TotalAmountProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Gets the Create Date.
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUser"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> CreateUserProperty = RegisterProperty<int>(p => p.CreateUser, "Create User");
/// <summary>
/// Gets the Create User.
/// </summary>
/// <value>The Create User.</value>
public int CreateUser
{
get { return GetProperty(CreateUserProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Gets the Change Date.
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUser"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> ChangeUserProperty = RegisterProperty<int>(p => p.ChangeUser, "Change User");
/// <summary>
/// Gets the Change User.
/// </summary>
/// <value>The Change User.</value>
public int ChangeUser
{
get { return GetProperty(ChangeUserProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Gets the Row Version.
/// </summary>
/// <value>The Row Version.</value>
public byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
/// <summary>
/// Maintains metadata about child <see cref="InvoiceLines"/> property.
/// </summary>
public static readonly PropertyInfo<InvoiceLineCollection> InvoiceLinesProperty = RegisterProperty<InvoiceLineCollection>(p => p.InvoiceLines, "Invoice Lines", RelationshipTypes.Child);
/// <summary>
/// Gets the Invoice Lines ("parent load" child property).
/// </summary>
/// <value>The Invoice Lines.</value>
public InvoiceLineCollection InvoiceLines
{
get { return GetProperty(InvoiceLinesProperty); }
private set { LoadProperty(InvoiceLinesProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="InvoiceEdit"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="InvoiceEdit"/> object.</returns>
public static InvoiceEdit NewInvoiceEdit()
{
return DataPortal.Create<InvoiceEdit>();
}
/// <summary>
/// Factory method. Loads a <see cref="InvoiceEdit"/> object, based on given parameters.
/// </summary>
/// <param name="invoiceId">The InvoiceId parameter of the InvoiceEdit to fetch.</param>
/// <returns>A reference to the fetched <see cref="InvoiceEdit"/> object.</returns>
public static InvoiceEdit GetInvoiceEdit(Guid invoiceId)
{
return DataPortal.Fetch<InvoiceEdit>(invoiceId);
}
/// <summary>
/// Factory method. Deletes a <see cref="InvoiceEdit"/> object, based on given parameters.
/// </summary>
/// <param name="invoiceId">The InvoiceId of the InvoiceEdit to delete.</param>
public static void DeleteInvoiceEdit(Guid invoiceId)
{
DataPortal.Delete<InvoiceEdit>(invoiceId);
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="InvoiceEdit"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewInvoiceEdit(EventHandler<DataPortalResult<InvoiceEdit>> callback)
{
DataPortal.BeginCreate<InvoiceEdit>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="InvoiceEdit"/> object, based on given parameters.
/// </summary>
/// <param name="invoiceId">The InvoiceId parameter of the InvoiceEdit to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetInvoiceEdit(Guid invoiceId, EventHandler<DataPortalResult<InvoiceEdit>> callback)
{
DataPortal.BeginFetch<InvoiceEdit>(invoiceId, callback);
}
/// <summary>
/// Factory method. Asynchronously deletes a <see cref="InvoiceEdit"/> object, based on given parameters.
/// </summary>
/// <param name="invoiceId">The InvoiceId of the InvoiceEdit to delete.</param>
/// <param name="callback">The completion callback method.</param>
public static void DeleteInvoiceEdit(Guid invoiceId, EventHandler<DataPortalResult<InvoiceEdit>> callback)
{
DataPortal.BeginDelete<InvoiceEdit>(invoiceId, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="InvoiceEdit"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public InvoiceEdit()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="InvoiceEdit"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(InvoiceIdProperty, Guid.NewGuid());
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CreateUserProperty, Security.UserInformation.UserId);
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
LoadProperty(ChangeUserProperty, ReadProperty(CreateUserProperty));
LoadProperty(InvoiceLinesProperty, DataPortal.CreateChild<InvoiceLineCollection>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="InvoiceEdit"/> object from the database, based on given criteria.
/// </summary>
/// <param name="invoiceId">The Invoice Id.</param>
protected void DataPortal_Fetch(Guid invoiceId)
{
var args = new DataPortalHookArgs(invoiceId);
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<IInvoiceEditDal>();
var data = dal.Fetch(invoiceId);
Fetch(data);
FetchChildren(dal);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Loads a <see cref="InvoiceEdit"/> object from the given <see cref="InvoiceEditDto"/>.
/// </summary>
/// <param name="data">The InvoiceEditDto to use.</param>
private void Fetch(InvoiceEditDto data)
{
// Value properties
LoadProperty(InvoiceIdProperty, data.InvoiceId);
LoadProperty(InvoiceNumberProperty, data.InvoiceNumber);
LoadProperty(CustomerIdProperty, data.CustomerId);
LoadProperty(InvoiceDateProperty, data.InvoiceDate);
LoadProperty(CreateDateProperty, data.CreateDate);
LoadProperty(CreateUserProperty, data.CreateUser);
LoadProperty(ChangeDateProperty, data.ChangeDate);
LoadProperty(ChangeUserProperty, data.ChangeUser);
LoadProperty(RowVersionProperty, data.RowVersion);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects from the given DAL provider.
/// </summary>
/// <param name="dal">The DAL provider to use.</param>
private void FetchChildren(IInvoiceEditDal dal)
{
LoadProperty(InvoiceLinesProperty, DataPortal.FetchChild<InvoiceLineCollection>(dal.InvoiceLineCollection));
}
/// <summary>
/// Inserts a new <see cref="InvoiceEdit"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
SimpleAuditTrail();
var dto = new InvoiceEditDto();
dto.InvoiceId = InvoiceId;
dto.InvoiceNumber = InvoiceNumber;
dto.CustomerId = CustomerId;
dto.InvoiceDate = ReadProperty(InvoiceDateProperty);
dto.CreateDate = CreateDate;
dto.CreateUser = CreateUser;
dto.ChangeDate = ChangeDate;
dto.ChangeUser = ChangeUser;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IInvoiceEditDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(RowVersionProperty, resultDto.RowVersion);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="InvoiceEdit"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
SimpleAuditTrail();
var dto = new InvoiceEditDto();
dto.InvoiceId = InvoiceId;
dto.InvoiceNumber = InvoiceNumber;
dto.CustomerId = CustomerId;
dto.InvoiceDate = ReadProperty(InvoiceDateProperty);
dto.ChangeDate = ChangeDate;
dto.ChangeUser = ChangeUser;
dto.RowVersion = RowVersion;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IInvoiceEditDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
LoadProperty(RowVersionProperty, resultDto.RowVersion);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
LoadProperty(ChangeUserProperty, Security.UserInformation.UserId);
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
LoadProperty(CreateUserProperty, ReadProperty(ChangeUserProperty));
}
}
/// <summary>
/// Self deletes the <see cref="InvoiceEdit"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(InvoiceId);
}
/// <summary>
/// Deletes the <see cref="InvoiceEdit"/> object from database.
/// </summary>
/// <param name="invoiceId">The delete criteria.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(Guid invoiceId)
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IInvoiceEditDal>();
using (BypassPropertyChecks)
{
dal.Delete(invoiceId);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
/// <summary>
/// CA1716: Identifiers should not match keywords
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class IdentifiersShouldNotMatchKeywordsAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1716";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotMatchKeywordsTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMemberParameter = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotMatchKeywordsMessageMemberParameter), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMember = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotMatchKeywordsMessageMember), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageType = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotMatchKeywordsMessageType), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNamespace = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotMatchKeywordsMessageNamespace), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotMatchKeywordsDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
internal static DiagnosticDescriptor MemberParameterRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageMemberParameter,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor MemberRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageMember,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor TypeRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageType,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor NamespaceRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageNamespace,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
// Define the format in which this rule displays namespace names. The format is chosen to be
// consistent with FxCop's display format for this rule.
private static readonly SymbolDisplayFormat s_namespaceDisplayFormat =
SymbolDisplayFormat.CSharpErrorMessageFormat
// Turn off the EscapeKeywordIdentifiers flag (which is on by default), so that
// a method named "@for" is displayed as "for"
.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.None);
private static readonly ImmutableHashSet<SymbolKind> s_defaultAnalyzedSymbolKinds =
ImmutableHashSet.Create(
SymbolKind.Namespace,
SymbolKind.NamedType,
SymbolKind.Method,
SymbolKind.Property,
SymbolKind.Event,
SymbolKind.Parameter
);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(MemberParameterRule, MemberRule, TypeRule, NamespaceRule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(compilationStartAnalysisContext =>
{
var namespaceRuleAnalyzer = new NamespaceRuleAnalyzer();
compilationStartAnalysisContext.RegisterSymbolAction(
symbolAnalysisContext => namespaceRuleAnalyzer.Analyze(symbolAnalysisContext),
SymbolKind.NamedType);
compilationStartAnalysisContext.RegisterSymbolAction(AnalyzeTypeRule, SymbolKind.NamedType);
compilationStartAnalysisContext.RegisterSymbolAction(AnalyzeMemberRule, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property);
compilationStartAnalysisContext.RegisterSymbolAction(AnalyzeMemberParameterRule, SymbolKind.Method);
});
}
private static bool ShouldAnalyze(SymbolAnalysisContext context, DiagnosticDescriptor rule)
{
if (!context.Options.MatchesConfiguredVisibility(rule, context.Symbol, context.Compilation, context.CancellationToken))
{
return false;
}
return GetSymbolKindsToAnalyze(context, rule).Contains(context.Symbol.Kind);
}
private static ImmutableHashSet<SymbolKind> GetSymbolKindsToAnalyze(SymbolAnalysisContext context, DiagnosticDescriptor rule)
=> context.Options.GetAnalyzedSymbolKindsOption(rule, context.Symbol, context.Compilation, s_defaultAnalyzedSymbolKinds, context.CancellationToken);
private sealed class NamespaceRuleAnalyzer
{
private readonly ISet<string> _namespaceWithKeywordSet = new HashSet<string>();
private readonly object _lockGuard = new();
public void Analyze(SymbolAnalysisContext context)
{
INamedTypeSymbol type = (INamedTypeSymbol)context.Symbol;
if (!GetSymbolKindsToAnalyze(context, NamespaceRule).Contains(SymbolKind.Namespace))
{
return;
}
// Don't complain about a namespace unless it contains at least one public type.
if (!context.Options.MatchesConfiguredVisibility(NamespaceRule, type, context.Compilation, context.CancellationToken))
{
return;
}
INamespaceSymbol containingNamespace = type.ContainingNamespace;
if (containingNamespace.IsGlobalNamespace)
{
return;
}
string namespaceDisplayString = containingNamespace.ToDisplayString(s_namespaceDisplayFormat);
IEnumerable<string> namespaceNameComponents = containingNamespace.ToDisplayParts(s_namespaceDisplayFormat)
.Where(dp => dp.Kind == SymbolDisplayPartKind.NamespaceName)
.Select(dp => dp.ToString());
foreach (string component in namespaceNameComponents)
{
if (IsKeyword(component, out string matchingKeyword))
{
bool doReportDiagnostic;
lock (_lockGuard)
{
string namespaceWithKeyword = namespaceDisplayString + "*" + matchingKeyword;
doReportDiagnostic = _namespaceWithKeywordSet.Add(namespaceWithKeyword);
}
if (doReportDiagnostic)
{
var diagnostic = containingNamespace.CreateDiagnostic(NamespaceRule, namespaceDisplayString, matchingKeyword);
context.ReportDiagnostic(diagnostic);
}
}
}
}
}
private static void AnalyzeTypeRule(SymbolAnalysisContext context)
{
INamedTypeSymbol type = (INamedTypeSymbol)context.Symbol;
if (!ShouldAnalyze(context, TypeRule))
{
return;
}
if (IsKeyword(type.Name, out string matchingKeyword))
{
context.ReportDiagnostic(
type.CreateDiagnostic(
TypeRule,
type.FormatMemberName(),
matchingKeyword));
}
}
private static void AnalyzeMemberRule(SymbolAnalysisContext context)
{
ISymbol symbol = context.Symbol;
if (!ShouldAnalyze(context, MemberRule))
{
return;
}
if (!IsKeyword(symbol.Name, out string matchingKeyword))
{
return;
}
// IsAbstract returns true for both abstract class members and interface members.
if (symbol.IsVirtual || symbol.IsAbstract)
{
context.ReportDiagnostic(
symbol.CreateDiagnostic(
MemberRule,
symbol.FormatMemberName(),
matchingKeyword));
}
}
private static void AnalyzeMemberParameterRule(SymbolAnalysisContext context)
{
var method = (IMethodSymbol)context.Symbol;
if (!GetSymbolKindsToAnalyze(context, MemberParameterRule).Contains(SymbolKind.Parameter) ||
!context.Options.MatchesConfiguredVisibility(MemberParameterRule, method, context.Compilation, context.CancellationToken))
{
return;
}
// IsAbstract returns true for both abstract class members and interface members.
if (!method.IsVirtual && !method.IsAbstract)
{
return;
}
foreach (IParameterSymbol parameter in method.Parameters)
{
if (IsKeyword(parameter.Name, out string matchingKeyword))
{
context.ReportDiagnostic(
parameter.CreateDiagnostic(
MemberParameterRule,
method.FormatMemberName(),
parameter.Name,
matchingKeyword));
}
}
}
private static bool IsKeyword(string name, out string keyword)
{
if (s_caseSensitiveKeywords.TryGetValue(name, out keyword))
{
return true;
}
return s_caseInsensitiveKeywords.TryGetKey(name, out keyword);
}
private static readonly ImmutableHashSet<string> s_caseSensitiveKeywords = new[]
{
// C#
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate",
"do",
"double",
"else",
"enum",
"event",
"explicit",
"extern",
"false",
"finally",
"fixed",
"float",
"for",
"foreach",
"goto",
"if",
"implicit",
"in",
"int",
"interface",
"internal",
"is",
"lock",
"long",
"namespace",
"new",
"null",
"object",
"operator",
"out",
"override",
"params",
"private",
"protected",
"public",
"readonly",
"ref",
"return",
"sbyte",
"sealed",
"short",
"sizeof",
"static",
"string",
"struct",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"uint",
"ulong",
"unchecked",
"unsafe",
"ushort",
"using",
"virtual",
"void",
"volatile",
"while",
// Listed as a keywords in Microsoft.CodeAnalysis.CSharp.SyntaxKind, but
// omitted, at least for now, for compatibility with FxCop:
//"__arglist",
//"__makeref",
//"__reftype",
//"__refvalue",
//"stackalloc",
// C++
"__abstract",
"__alignof",
"__asm",
"__assume",
"__based",
"__box",
"__builtin_alignof",
"__cdecl",
"__clrcall",
"__compileBreak",
"__CURSOR__",
"__declspec",
"__delegate",
"__event",
"__except",
"__fastcall",
"__feacp_av",
"__feacpBreak",
"__finally",
"__forceinline",
"__gc",
"__has_assign",
"__has_copy",
"__has_finalizer",
"__has_nothrow_assign",
"__has_nothrow_copy",
"__has_trivial_assign",
"__has_trivial_constructor",
"__has_trivial_copy",
"__has_trivial_destructor",
"__has_user_destructor",
"__has_virtual_destructor",
"__hook",
"__identifier",
"__if_exists",
"__if_not_exists",
"__inline",
"__int128",
"__int16",
"__int32",
"__int64",
"__int8",
"__interface",
"__is_abstract",
"__is_base_of",
"__is_class",
"__is_convertible_to",
"__is_delegate",
"__is_empty",
"__is_enum",
"__is_interface_class",
"__is_pod",
"__is_polymorphic",
"__is_ref_array",
"__is_ref_class",
"__is_sealed",
"__is_simple_value_class",
"__is_union",
"__is_value_class",
"__leave",
"__multiple_inheritance",
"__newslot",
"__nogc",
"__nounwind",
"__nvtordisp",
"__offsetof",
"__pin",
"__pragma",
"__property",
"__ptr32",
"__ptr64",
"__raise",
"__restrict",
"__resume",
"__sealed",
"__single_inheritance",
"__stdcall",
"__super",
"__thiscall",
"__try",
"__try_cast",
"__typeof",
"__unaligned",
"__unhook",
"__uuidof",
"__value",
"__virtual_inheritance",
"__w64",
"__wchar_t",
"and",
"and_eq",
"asm",
"auto",
"bitand",
"bitor",
//"bool",
//"break",
//"case",
//"catch",
"cdecl",
//"char",
//"class",
"compl",
//"const",
"const_cast",
//"continue",
//"default",
"delete",
//"do",
//"double",
"dynamic_cast",
//"else",
//"enum",
//"explicit",
"export",
//"extern",
//"false,
//"float",
//"for",
"friend",
"gcnew",
"generic",
//"goto",
//"if",
"inline",
//"int",
//"long",
"mutable",
//"namespace",
//"new",
"not",
"not_eq",
"nullptr",
//"operator",
"or",
"or_eq",
//"private",
//"protected",
//"public",
"register",
"reinterpret_cast",
//"return",
//"short",
"signed",
//"sizeof",
//"static",
"static_cast",
//"struct",
//"switch",
"template",
//"this",
//"throw",
//"true",
//"try",
"typedef",
"typeid",
"typename",
"union",
"unsigned",
//"using",
//"virtual",
//"void",
//"volatile",
"wchar_t",
//"while",
"xor",
"xor_eq"
}.ToImmutableHashSet(StringComparer.Ordinal);
private static readonly ImmutableDictionary<string, string> s_caseInsensitiveKeywords = new[]
{
"AddHandler",
"AddressOf",
"Alias",
"And",
"AndAlso",
"As",
"Boolean",
"ByRef",
"Byte",
"ByVal",
"Call",
"Case",
"Catch",
"CBool",
"CByte",
"CChar",
"CDate",
"CDbl",
"CDec",
"Char",
"CInt",
"Class",
"CLng",
"CObj",
"Const",
"Continue",
"CSByte",
"CShort",
"CSng",
"CStr",
"CType",
"CUInt",
"CULng",
"CUShort",
"Date",
"Decimal",
"Declare",
"Default",
"Delegate",
"Dim",
"DirectCast",
"Do",
"Double",
"Each",
"Else",
"ElseIf",
"End",
"Enum",
"Erase",
"Error",
"Event",
"Exit",
"False",
"Finally",
"For",
"Friend",
"Function",
"Get",
"GetType",
"Global",
"GoTo",
"Handles",
"If",
"Implements",
"Imports",
"In",
"Inherits",
"Integer",
"Interface",
"Is",
"IsNot",
"Lib",
"Like",
"Long",
"Loop",
"Me",
"Mod",
"Module",
"MustInherit",
"MustOverride",
"MyBase",
"MyClass",
"Namespace",
"Narrowing",
"New",
"Next",
"Not",
"Nothing",
"NotInheritable",
"NotOverridable",
"Object",
"Of",
"On",
"Operator",
"Option",
"Optional",
"Or",
"OrElse",
"Overloads",
"Overridable",
"Overrides",
"ParamArray",
"Partial",
"Private",
"Property",
"Protected",
"Public",
"RaiseEvent",
"ReadOnly",
"ReDim",
"REM",
"RemoveHandler",
"Resume",
"Return",
"SByte",
"Select",
"Set",
"Shadows",
"Shared",
"Short",
"Single",
"Static",
"Step",
"Stop",
"String",
"Structure",
"Sub",
"SyncLock",
"Then",
"Throw",
"To",
"True",
"Try",
"TryCast",
"TypeOf",
"UInteger",
"ULong",
"UShort",
"Using",
"When",
"While",
"Widening",
"With",
"WithEvents",
"WriteOnly",
"Xor"
// Listed as a keywords in Microsoft.CodeAnalysis.VisualBasic.SyntaxKind, but
// omitted, at least for now, for compatibility with FxCop:
//"Aggregate",
//"All",
//"Ansi",
//"Ascending",
//"Assembly",
//"Async",
//"Await",
//"Auto",
//"Binary",
//"By",
//"Compare",
//"Custom",
//"Descending",
//"Disable",
//"Distinct",
//"Enable",
//"EndIf",
//"Equals",
//"Explicit",
//"ExternalChecksum",
//"ExternalSource",
//"From",
//"GetXmlNamespace",
//"Gosub",
//"Group",
//"Infer",
//"Into",
//"IsFalse",
//"IsTrue",
//"Iterator",
//"Yield",
//"Join",
//"Key",
//"Let",
//"Mid",
//"Off",
//"Order",
//"Out",
//"Preserve",
//"Reference",
//"Region",
//"Strict",
//"Take",
//"Text",
//"Type",
//"Unicode",
//"Until",
//"Warning",
//"Variant",
//"Wend",
//"Where",
//"Xml"
}.ToImmutableDictionary(key => key, StringComparer.OrdinalIgnoreCase);
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using OrchardCore.DisplayManagement.Descriptors;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.DisplayManagement.Implementation;
using OrchardCore.DisplayManagement.Shapes;
using OrchardCore.DisplayManagement.Zones;
using OrchardCore.Environment.Cache;
namespace OrchardCore.DisplayManagement.Views
{
public class ShapeResult : IDisplayResult
{
private string _defaultLocation;
private Dictionary<string, string> _otherLocations;
private string _differentiator;
private string _prefix;
private string _cacheId;
private readonly string _shapeType;
private readonly Func<IBuildShapeContext, ValueTask<IShape>> _shapeBuilder;
private readonly Func<IShape, Task> _processing;
private Action<CacheContext> _cache;
private string _groupId;
private Action<ShapeDisplayContext> _displaying;
public ShapeResult(string shapeType, Func<IBuildShapeContext, ValueTask<IShape>> shapeBuilder)
: this(shapeType, shapeBuilder, null)
{
}
public ShapeResult(string shapeType, Func<IBuildShapeContext, ValueTask<IShape>> shapeBuilder, Func<IShape, Task> processing)
{
// The shape type is necessary before the shape is created as it will drive the placement
// resolution which itself can prevent the shape from being created.
_shapeType = shapeType;
_shapeBuilder = shapeBuilder;
_processing = processing;
}
public Task ApplyAsync(BuildDisplayContext context)
{
return ApplyImplementationAsync(context, context.DisplayType);
}
public Task ApplyAsync(BuildEditorContext context)
{
return ApplyImplementationAsync(context, "Edit");
}
private async Task ApplyImplementationAsync(BuildShapeContext context, string displayType)
{
// If no location is set from the driver, use the one from the context
if (String.IsNullOrEmpty(_defaultLocation))
{
_defaultLocation = context.DefaultZone;
}
// Look into specific implementations of placements (like placement.json files)
var placement = context.FindPlacement(_shapeType, _differentiator, displayType, context);
// Look for mapped display type locations
if (_otherLocations != null)
{
string displayTypePlacement;
if (_otherLocations.TryGetValue(displayType, out displayTypePlacement))
{
_defaultLocation = displayTypePlacement;
}
}
// If no placement is found, use the default location
if (placement == null)
{
placement = new PlacementInfo() { Location = _defaultLocation };
}
if (placement.Location == null)
{
// If a placement was found without actual location, use the default.
// It can happen when just setting alternates or wrappers for instance.
placement.Location = _defaultLocation;
}
if (placement.DefaultPosition == null)
{
placement.DefaultPosition = context.DefaultPosition;
}
// If there are no placement or it's explicitly noop then stop rendering execution
if (String.IsNullOrEmpty(placement.Location) || placement.Location == "-")
{
return;
}
// Parse group placement.
_groupId = placement.GetGroup() ?? _groupId;
// If the shape's group doesn't match the currently rendered one, return
if (!String.Equals(context.GroupId ?? "", _groupId ?? "", StringComparison.OrdinalIgnoreCase))
{
return;
}
var newShape = Shape = await _shapeBuilder(context);
// Ignore it if the driver returned a null shape.
if (newShape == null)
{
return;
}
ShapeMetadata newShapeMetadata = newShape.Metadata;
newShapeMetadata.Prefix = _prefix;
newShapeMetadata.Name = _differentiator ?? _shapeType;
newShapeMetadata.DisplayType = displayType;
newShapeMetadata.PlacementSource = placement.Source;
newShapeMetadata.Tab = placement.GetTab();
newShapeMetadata.Type = _shapeType;
if (_displaying != null)
{
newShapeMetadata.OnDisplaying(_displaying);
}
// The _processing callback is used to delay execution of costly initialization
// that can be prevented by caching
if (_processing != null)
{
newShapeMetadata.OnProcessing(_processing);
}
// Apply cache settings
if (!String.IsNullOrEmpty(_cacheId) && _cache != null)
{
_cache(newShapeMetadata.Cache(_cacheId));
}
// If a specific shape is provided, remove all previous alternates and wrappers.
if (!String.IsNullOrEmpty(placement.ShapeType))
{
newShapeMetadata.Type = placement.ShapeType;
newShapeMetadata.Alternates.Clear();
newShapeMetadata.Wrappers.Clear();
}
if (placement != null)
{
if (placement.Alternates != null)
{
newShapeMetadata.Alternates.AddRange(placement.Alternates);
}
if (placement.Wrappers != null)
{
newShapeMetadata.Wrappers.AddRange(placement.Wrappers);
}
}
dynamic parentShape = context.Shape;
if (placement.IsLayoutZone())
{
parentShape = context.Layout;
}
var position = placement.GetPosition();
var zones = placement.GetZones();
foreach (var zone in zones)
{
if (parentShape == null)
{
break;
}
var zoneProperty = parentShape.Zones;
if (zoneProperty != null)
{
// parentShape is a ZoneHolding
parentShape = zoneProperty[zone];
}
else
{
// try to access it as a member
parentShape = parentShape[zone];
}
}
position = !String.IsNullOrEmpty(position) ? position : null;
if (parentShape is ZoneOnDemand zoneOnDemand)
{
await zoneOnDemand.AddAsync(newShape, position);
}
else if (parentShape is Shape shape)
{
shape.Add(newShape, position);
}
}
/// <summary>
/// Sets the prefix of the form elements rendered in the shape.
/// </summary>
/// <remarks>
/// The goal is to isolate each shape when edited together.
/// </remarks>
public ShapeResult Prefix(string prefix)
{
_prefix = prefix;
return this;
}
/// <summary>
/// Sets the default location of the shape when no specific placement applies.
/// </summary>
public ShapeResult Location(string location)
{
_defaultLocation = location;
return this;
}
/// <summary>
/// Sets the location to use for a matching display type.
/// </summary>
public ShapeResult Location(string displayType, string location)
{
if (_otherLocations == null)
{
_otherLocations = new Dictionary<string, string>(2);
}
_otherLocations[displayType] = location;
return this;
}
/// <summary>
/// Sets the location to use for a matching display type.
/// </summary>
public ShapeResult Displaying(Action<ShapeDisplayContext> displaying)
{
_displaying = displaying;
return this;
}
/// <summary>
/// Sets a discriminator that is used to find the location of the shape when two shapes of the same type are displayed.
/// </summary>
public ShapeResult Differentiator(string differentiator)
{
_differentiator = differentiator;
return this;
}
/// <summary>
/// Sets the group identifier the shape will be rendered in.
/// </summary>
/// <param name="groupId"></param>
/// <returns></returns>
public ShapeResult OnGroup(string groupId)
{
_groupId = groupId;
return this;
}
/// <summary>
/// Sets the caching properties of the shape to render.
/// </summary>
public ShapeResult Cache(string cacheId, Action<CacheContext> cache = null)
{
_cacheId = cacheId;
_cache = cache;
return this;
}
public IShape Shape { get; private set; }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
#if FEATURE_HOST_ASSEMBLY_RESOLVER
namespace System.Runtime.Loader
{
[System.Security.SecuritySafeCritical]
public abstract class AssemblyLoadContext
{
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool OverrideDefaultAssemblyLoadContextForCurrentDomain(IntPtr ptrNativeAssemblyLoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool CanUseAppPathAssemblyLoadContextInCurrentDomain();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly);
#if FEATURE_MULTICOREJIT
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalSetProfileRoot(string directoryPath);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext);
#endif // FEATURE_MULTICOREJIT
[System.Security.SecuritySafeCritical]
protected AssemblyLoadContext()
{
// Initialize the VM side of AssemblyLoadContext if not already done.
GCHandle gchALC = GCHandle.Alloc(this);
IntPtr ptrALC = GCHandle.ToIntPtr(gchALC);
m_pNativeAssemblyLoadContext = InitializeAssemblyLoadContext(ptrALC);
}
internal AssemblyLoadContext(bool fDummy)
{
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly);
// These are helpers that can be used by AssemblyLoadContext derivations.
// They are used to load assemblies in DefaultContext.
protected Assembly LoadFromAssemblyPath(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException("assemblyPath");
}
if (Path.IsRelative(assemblyPath))
{
throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath");
}
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, null, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
protected Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath)
{
if (nativeImagePath == null)
{
throw new ArgumentNullException("nativeImagePath");
}
if (Path.IsRelative(nativeImagePath))
{
throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "nativeImagePath");
}
// Check if the nativeImagePath has ".ni.dll" or ".ni.exe" extension
if (!(nativeImagePath.EndsWith(".ni.dll", StringComparison.InvariantCultureIgnoreCase) ||
nativeImagePath.EndsWith(".ni.exe", StringComparison.InvariantCultureIgnoreCase)))
{
throw new ArgumentException("nativeImagePath");
}
if (assemblyPath != null && Path.IsRelative(assemblyPath))
{
throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath");
}
// Basic validation has succeeded - lets try to load the NI image.
// Ask LoadFile to load the specified assembly in the DefaultContext
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
protected Assembly LoadFromStream(Stream assembly)
{
return LoadFromStream(assembly, null);
}
protected Assembly LoadFromStream(Stream assembly, Stream assemblySymbols)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
int iAssemblyStreamLength = (int)assembly.Length;
int iSymbolLength = 0;
// Allocate the byte[] to hold the assembly
byte[] arrAssembly = new byte[iAssemblyStreamLength];
// Copy the assembly to the byte array
assembly.Read(arrAssembly, 0, iAssemblyStreamLength);
// Get the symbol stream in byte[] if provided
byte[] arrSymbols = null;
if (assemblySymbols != null)
{
iSymbolLength = (int)assemblySymbols.Length;
arrSymbols = new byte[iSymbolLength];
assemblySymbols.Read(arrSymbols, 0, iSymbolLength);
}
RuntimeAssembly loadedAssembly = null;
unsafe
{
fixed(byte *ptrAssembly = arrAssembly, ptrSymbols = arrSymbols)
{
LoadFromStream(m_pNativeAssemblyLoadContext, new IntPtr(ptrAssembly), iAssemblyStreamLength, new IntPtr(ptrSymbols), iSymbolLength, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
}
}
return loadedAssembly;
}
// Custom AssemblyLoadContext implementations can override this
// method to perform custom processing and use one of the protected
// helpers above to load the assembly.
protected abstract Assembly Load(AssemblyName assemblyName);
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.LoadFromAssemblyName(assemblyName);
}
public Assembly LoadFromAssemblyName(AssemblyName assemblyName)
{
// AssemblyName is mutable. Cache the expected name before anybody gets a chance to modify it.
string requestedSimpleName = assemblyName.Name;
Assembly assembly = Load(assemblyName);
if (assembly == null)
{
throw new FileLoadException(Environment.GetResourceString("IO.FileLoad"), requestedSimpleName);
}
// Get the name of the loaded assembly
string loadedSimpleName = null;
// Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly
// which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder),
// we need to check for RuntimeAssembly.
RuntimeAssembly rtLoadedAssembly = assembly as RuntimeAssembly;
if (rtLoadedAssembly != null)
{
loadedSimpleName = rtLoadedAssembly.GetSimpleName();
}
// The simple names should match at the very least
if (String.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase)))
throw new InvalidOperationException(Environment.GetResourceString("Argument_CustomAssemblyLoadContextRequestedNameMismatch"));
return assembly;
}
// Custom AssemblyLoadContext implementations can override this
// method to perform the load of unmanaged native dll
// This function needs to return the HMODULE of the dll it loads
protected virtual IntPtr LoadUnmanagedDll(String unmanagedDllName)
{
//defer to default coreclr poilcy of loading unmanaged dll
return IntPtr.Zero;
}
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static IntPtr ResolveUnmanagedDll(String unmanagedDllName, IntPtr gchManagedAssemblyLoadContext)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.LoadUnmanagedDll(unmanagedDllName);
}
public static AssemblyLoadContext Default
{
get
{
while (m_DefaultAssemblyLoadContext == null)
{
// Try to initialize the default assembly load context with apppath one if we are allowed to
if (AssemblyLoadContext.CanUseAppPathAssemblyLoadContextInCurrentDomain())
{
#pragma warning disable 0420
Interlocked.CompareExchange(ref m_DefaultAssemblyLoadContext, new AppPathAssemblyLoadContext(), null);
break;
#pragma warning restore 0420
}
// Otherwise, need to yield to other thread to finish the initialization
Thread.Yield();
}
return m_DefaultAssemblyLoadContext;
}
}
// This will be used to set the AssemblyLoadContext for DefaultContext, for the AppDomain,
// by a host. Once set, the runtime will invoke the LoadFromAssemblyName method against it to perform
// assembly loads for the DefaultContext.
//
// This method will throw if the Default AssemblyLoadContext is already set or the Binding model is already locked.
public static void InitializeDefaultContext(AssemblyLoadContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
// Try to override the default assembly load context
if (!AssemblyLoadContext.OverrideDefaultAssemblyLoadContextForCurrentDomain(context.m_pNativeAssemblyLoadContext))
{
throw new InvalidOperationException(Environment.GetResourceString("AppDomain_BindingModelIsLocked"));
}
// Update the managed side as well.
m_DefaultAssemblyLoadContext = context;
}
// This call opens and closes the file, but does not add the
// assembly to the domain.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern AssemblyName nGetFileInformation(String s);
// Helper to return AssemblyName corresponding to the path of an IL assembly
public static AssemblyName GetAssemblyName(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException("assemblyPath");
}
String fullPath = Path.GetFullPathInternal(assemblyPath);
return nGetFileInformation(fullPath);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly);
// Returns the load context in which the specified assembly has been loaded
public static AssemblyLoadContext GetLoadContext(Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
AssemblyLoadContext loadContextForAssembly = null;
IntPtr ptrAssemblyLoadContext = GetLoadContextForAssembly((RuntimeAssembly)assembly);
if (ptrAssemblyLoadContext == IntPtr.Zero)
{
// If the load context is returned null, then the assembly was bound using the TPA binder
// and we shall return reference to the active "Default" binder - which could be the TPA binder
// or an overridden CLRPrivBinderAssemblyLoadContext instance.
loadContextForAssembly = AssemblyLoadContext.Default;
}
else
{
loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target);
}
return loadContextForAssembly;
}
// Set the root directory path for profile optimization.
public void SetProfileOptimizationRoot(string directoryPath)
{
#if FEATURE_MULTICOREJIT
InternalSetProfileRoot(directoryPath);
#endif // FEATURE_MULTICOREJIT
}
// Start profile optimization for the specified profile name.
public void StartProfileOptimization(string profile)
{
#if FEATURE_MULTICOREJIT
InternalStartProfile(profile, m_pNativeAssemblyLoadContext);
#endif // FEATURE_MULTICOREJI
}
// Contains the reference to VM's representation of the AssemblyLoadContext
private IntPtr m_pNativeAssemblyLoadContext;
// Each AppDomain contains the reference to its AssemblyLoadContext instance, if one is
// specified by the host. By having the field as a static, we are
// making it an AppDomain-wide field.
private static volatile AssemblyLoadContext m_DefaultAssemblyLoadContext;
}
[System.Security.SecuritySafeCritical]
class AppPathAssemblyLoadContext : AssemblyLoadContext
{
internal AppPathAssemblyLoadContext() : base(false)
{
}
[System.Security.SecuritySafeCritical]
protected override Assembly Load(AssemblyName assemblyName)
{
return Assembly.Load(assemblyName);
}
}
}
#endif // FEATURE_HOST_ASSEMBLY_RESOLVER
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig
{
using System;
using System.Collections;
using System.Collections.Generic;
public class GrowOnlyList< T >
{
class Cluster
{
internal const int DefaultCapacity = 4;
internal const int MaxCapacity = 256;
//
// State
//
internal Cluster m_next;
internal readonly T[] m_elements;
internal int m_pos;
//
// Costructor Methods
//
internal Cluster( int capacity )
{
m_elements = new T[capacity];
m_pos = 0;
}
//
// Helper Methods
//
internal Cluster Add( T obj )
{
int capacity = m_elements.Length;
if(m_pos == capacity)
{
m_next = new Cluster( Math.Min( capacity * 2, MaxCapacity ) );
return m_next.Add( obj );
}
m_elements[m_pos++] = obj;
return this;
}
}
//
// State
//
private Cluster m_first;
private Cluster m_last;
private int m_count;
//
// Costructor Methods
//
public GrowOnlyList()
{
Clear();
}
//
// Helper Methods
//
public void Clear()
{
m_first = new Cluster( Cluster.DefaultCapacity );
m_last = m_first;
m_count = 0;
}
public void Add( T obj )
{
m_last = m_last.Add( obj );
m_count++;
}
//--//
public Enumerator GetEnumerator()
{
return new Enumerator( this );
}
//
// Access Methods
//
public int Count
{
get
{
return m_count;
}
}
public T this[int index]
{
get
{
if(index >= 0 && index < m_count)
{
for(Cluster cluster = m_first; cluster != null; cluster = cluster.m_next)
{
if(index < cluster.m_pos)
{
return cluster.m_elements[index];
}
index -= cluster.m_pos;
}
}
throw new ArgumentOutOfRangeException();
}
set
{
if(index >= 0 && index < m_count)
{
for(Cluster cluster = m_first; cluster != null; cluster = cluster.m_next)
{
if(index < cluster.m_pos)
{
cluster.m_elements[index] = value;
return;
}
index -= cluster.m_pos;
}
}
throw new ArgumentOutOfRangeException();
}
}
//--//--//--//--//--//--//--//--//
public struct Enumerator
{
//
// State
//
private Cluster m_first;
private Cluster m_current;
private int m_index;
//
// Constructor Methods
//
internal Enumerator( GrowOnlyList< T > list )
{
m_first = list.m_first;
m_current = m_first;
m_index = 0;
}
public void Dispose()
{
}
public bool MoveNext()
{
while(m_current != null)
{
if(m_index < m_current.m_pos)
{
m_index++;
return true;
}
m_current = m_current.m_next;
m_index = 0;
}
return false;
}
public T Current
{
get
{
return m_current.m_elements[m_index-1];
}
}
void Reset()
{
m_current = m_first;
m_index = 0;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
public static partial class SecurityRulesOperationsExtensions
{
/// <summary>
/// The delete network security rule operation deletes the specified network
/// security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
public static void Delete(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName)
{
Task.Factory.StartNew(s => ((ISecurityRulesOperations)s).DeleteAsync(resourceGroupName, networkSecurityGroupName, securityRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete network security rule operation deletes the specified network
/// security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync( this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The delete network security rule operation deletes the specified network
/// security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
public static void BeginDelete(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName)
{
Task.Factory.StartNew(s => ((ISecurityRulesOperations)s).BeginDeleteAsync(resourceGroupName, networkSecurityGroupName, securityRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete network security rule operation deletes the specified network
/// security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync( this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Get NetworkSecurityRule operation retreives information about the
/// specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
public static SecurityRule Get(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName)
{
return Task.Factory.StartNew(s => ((ISecurityRulesOperations)s).GetAsync(resourceGroupName, networkSecurityGroupName, securityRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get NetworkSecurityRule operation retreives information about the
/// specified network security rule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityRule> GetAsync( this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<SecurityRule> result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The Put network security rule operation creates/updates a security rule in
/// the specified network security group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create/update network security rule operation
/// </param>
public static SecurityRule CreateOrUpdate(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters)
{
return Task.Factory.StartNew(s => ((ISecurityRulesOperations)s).CreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put network security rule operation creates/updates a security rule in
/// the specified network security group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create/update network security rule operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityRule> CreateOrUpdateAsync( this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<SecurityRule> result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The Put network security rule operation creates/updates a security rule in
/// the specified network security group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create/update network security rule operation
/// </param>
public static SecurityRule BeginCreateOrUpdate(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters)
{
return Task.Factory.StartNew(s => ((ISecurityRulesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put network security rule operation creates/updates a security rule in
/// the specified network security group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create/update network security rule operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityRule> BeginCreateOrUpdateAsync( this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<SecurityRule> result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The List network security rule opertion retrieves all the security rules
/// in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
public static IPage<SecurityRule> List(this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName)
{
return Task.Factory.StartNew(s => ((ISecurityRulesOperations)s).ListAsync(resourceGroupName, networkSecurityGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List network security rule opertion retrieves all the security rules
/// in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SecurityRule>> ListAsync( this ISecurityRulesOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<IPage<SecurityRule>> result = await operations.ListWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// The List network security rule opertion retrieves all the security rules
/// in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SecurityRule> ListNext(this ISecurityRulesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((ISecurityRulesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List network security rule opertion retrieves all the security rules
/// in a network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SecurityRule>> ListNextAsync( this ISecurityRulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
AzureOperationResponse<IPage<SecurityRule>> result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.UnitTests;
using Xunit;
namespace Desktop.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingInApiDesignAnalyzerTests : DiagnosticAnalyzerTestBase
{
private static readonly string s_CA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodMessage = DesktopAnalyzersResources.XmlTextReaderDerivedClassSetInsecureSettingsInMethodMessage;
private DiagnosticResult GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(int line, int column, string name)
{
return GetCSharpResultAt(line, column, CA3077RuleId, string.Format(s_CA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodMessage, name));
}
private DiagnosticResult GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(int line, int column, string name)
{
return GetBasicResultAt(line, column, CA3077RuleId, string.Format(s_CA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodMessage, name));
}
[Fact]
public void XmlTextReaderDerivedTypeNoCtorSetUrlResolverToXmlResolverMethodShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public void method()
{
XmlResolver = new XmlUrlResolver();
}
}
}",
GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(11, 13, "method")
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub method()
XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(8, 13, "method")
);
}
[Fact]
public void XmlTextReaderDerivedTypeSetUrlResolverToXmlResolverMethodShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method()
{
XmlResolver = new XmlUrlResolver();
}
}
}",
GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(17, 13, "method")
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method()
XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(13, 13, "method")
);
}
[Fact]
public void XmlTextReaderDerivedTypeSetDtdProcessingToParseMethodShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method()
{
DtdProcessing = DtdProcessing.Parse;
}
}
}",
GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(17, 13, "method")
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method()
DtdProcessing = DtdProcessing.Parse
End Sub
End Class
End Namespace",
GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(13, 13, "method")
);
}
[Fact]
public void XmlTextReaderDerivedTypeSetUrlResolverToThisXmlResolverMethodShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method()
{
this.XmlResolver = new XmlUrlResolver();
}
}
}",
GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(17, 13, "method")
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method()
Me.XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(13, 13, "method")
);
}
[Fact]
public void XmlTextReaderDerivedTypeSetUrlResolverToBaseXmlResolverMethodShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method()
{
base.XmlResolver = new XmlUrlResolver();
}
}
}",
GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(17, 13, "method")
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method()
MyBase.XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(13, 13, "method")
);
}
[Fact]
public void XmlTextReaderDerivedTypeSetXmlResolverToNullMethodShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method()
{
XmlResolver = null;
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method()
XmlResolver = Nothing
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderDerivedTypeSetDtdProcessingToProhibitMethodShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method()
{
DtdProcessing = DtdProcessing.Prohibit;
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method()
DtdProcessing = DtdProcessing.Prohibit
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderDerivedTypeSetDtdProcessingToTypoMethodShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method()
{
DtdProcessing = DtdProcessing.prohibit;
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method()
DtdProcessing = DtdProcessing.prohibit
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderDerivedTypeParseAndNullResolverMethodShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method()
{
DtdProcessing = DtdProcessing.Parse;
XmlResolver = null;
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method()
DtdProcessing = DtdProcessing.Parse
XmlResolver = Nothing
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderDerivedTypeIgnoreAndUrlResolverMethodShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method()
{
DtdProcessing = DtdProcessing.Ignore;
XmlResolver = new XmlUrlResolver();
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method()
DtdProcessing = DtdProcessing.Ignore
XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderDerivedTypeParseAndUrlResolverMethodShouldGenerateDiagnostic()
{
DiagnosticResult diagWith2Locations = GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodCSharpResultAt(17, 13, "method");
diagWith2Locations.Locations = new DiagnosticResultLocation[]
{
diagWith2Locations.Locations[0],
new DiagnosticResultLocation(diagWith2Locations.Locations[0].Path, 18, 13)
};
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method()
{
DtdProcessing = DtdProcessing.Parse;
XmlResolver = new XmlUrlResolver();
}
}
}",
diagWith2Locations
);
diagWith2Locations = GetCA3077XmlTextReaderDerivedClassSetInsecureSettingsInMethodBasicResultAt(13, 13, "method");
diagWith2Locations.Locations = new DiagnosticResultLocation[]
{
diagWith2Locations.Locations[0],
new DiagnosticResultLocation(diagWith2Locations.Locations[0].Path, 14, 13)
};
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method()
DtdProcessing = DtdProcessing.Parse
XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
diagWith2Locations
);
}
[Fact]
public void XmlTextReaderDerivedTypeSecureResolverInOnePathMethodShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method(bool flag)
{
DtdProcessing = DtdProcessing.Parse;
if (flag)
{
XmlResolver = null;
}
else
{
XmlResolver = new XmlUrlResolver(); // intended false negative, due to the lack of flow analysis
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method(flag As Boolean)
DtdProcessing = DtdProcessing.Parse
If flag Then
XmlResolver = Nothing
Else
' intended false negative, due to the lack of flow analysis
XmlResolver = New XmlUrlResolver()
End If
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderDerivedTypeSetInsecureSettingsInSeperatePathsMethodShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
public void method(bool flag)
{
if (flag)
{
// secure
DtdProcessing = DtdProcessing.Ignore;
XmlResolver = null;
}
else
{
// insecure
DtdProcessing = DtdProcessing.Parse;
XmlResolver = new XmlUrlResolver(); // intended false negative, due to the lack of flow analysis
}
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
Public Sub method(flag As Boolean)
If flag Then
' secure
DtdProcessing = DtdProcessing.Ignore
XmlResolver = Nothing
Else
' insecure
DtdProcessing = DtdProcessing.Parse
' intended false negative, due to the lack of flow analysis
XmlResolver = New XmlUrlResolver()
End If
End Sub
End Class
End Namespace");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//permutations for (((s.a+s.b)+s.c)+s.d)
//(((s.a+s.b)+s.c)+s.d)
//(s.d+((s.a+s.b)+s.c))
//((s.a+s.b)+s.c)
//(s.c+(s.a+s.b))
//(s.a+s.b)
//(s.b+s.a)
//(s.a+s.b)
//(s.b+s.a)
//(s.a+(s.b+s.c))
//(s.b+(s.a+s.c))
//(s.b+s.c)
//(s.a+s.c)
//((s.a+s.b)+s.c)
//(s.c+(s.a+s.b))
//((s.a+s.b)+(s.c+s.d))
//(s.c+((s.a+s.b)+s.d))
//(s.c+s.d)
//((s.a+s.b)+s.d)
//(s.a+(s.b+s.d))
//(s.b+(s.a+s.d))
//(s.b+s.d)
//(s.a+s.d)
//(((s.a+s.b)+s.c)+s.d)
//(s.d+((s.a+s.b)+s.c))
namespace CseTest
{
using System;
public class Test_Main
{
static int Main()
{
int ret = 100;
class_s s = new class_s();
s.a = return_int(false, -51);
s.b = return_int(false, 86);
s.c = return_int(false, 89);
s.d = return_int(false, 56);
int v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24;
v1 = v2 = v3 = v4 = v5 = v6 = v7 = v8 = v9 = v10 = v11 = v12 = v13 = v14 = v15 = v16 = v17 = v18 = v19 = v20 = v21 = v22 = v23 = v24 = 0;
#if LOOP
do {
#endif
#if TRY
try {
#endif
#if LOOP
do {
for (int i = 0; i < 10; i++) {
#endif
int stage = 0;
start_try:
try
{
checked
{
stage++;
switch (stage)
{
case 1:
v1 = (((s.a + s.b) + s.c) + s.d) + System.Int32.MaxValue;
break;
case 2:
v2 = (s.d + ((s.a + s.b) + s.c)) + System.Int32.MaxValue; ;
break;
case 3:
v3 = ((s.a + s.b) + s.c) + System.Int32.MaxValue; ;
break;
case 4:
v4 = (s.c + (s.a + s.b)) + System.Int32.MaxValue; ;
break;
case 5:
v5 = (s.a + s.b) + System.Int32.MaxValue;
break;
case 6:
v6 = (s.b + s.a) + System.Int32.MaxValue; ;
break;
case 7:
v7 = (s.a + s.b) + System.Int32.MaxValue; ;
break;
case 8:
v8 = (s.b + s.a) + System.Int32.MaxValue; ;
break;
case 9:
v9 = (s.a + (s.b + s.c)) + System.Int32.MaxValue;
break;
case 10:
v10 = (s.b + (s.a + s.c)) + System.Int32.MaxValue;
break;
case 11:
v11 = (s.b + s.c) + System.Int32.MaxValue;
break;
case 12:
v12 = (s.a + s.c) + System.Int32.MaxValue;
break;
case 13:
v13 = ((s.a + s.b) + s.c) + System.Int32.MaxValue;
break;
case 14:
v14 = (s.c + (s.a + s.b)) + System.Int32.MaxValue;
break;
case 15:
v15 = ((s.a + s.b) + (s.c + s.d)) + System.Int32.MaxValue;
break;
case 16:
v16 = (s.c + ((s.a + s.b) + s.d)) + System.Int32.MaxValue;
break;
case 17:
v17 = (s.c + s.d) + System.Int32.MaxValue;
break;
case 18:
v18 = ((s.a + s.b) + s.d) + System.Int32.MaxValue;
break;
case 19:
v19 = (s.a + (s.b + s.d)) + System.Int32.MaxValue;
break;
case 20:
v20 = (s.b + (s.a + s.d)) + System.Int32.MaxValue;
break;
case 21:
v21 = (s.b + s.d) + System.Int32.MaxValue;
break;
case 22:
v22 = (s.a + s.d) + System.Int32.MaxValue;
break;
case 23:
v23 = (((s.a + s.b) + s.c) + s.d) + System.Int32.MaxValue;
break;
case 24:
v24 = (s.d + ((s.a + s.b) + s.c)) + System.Int32.MaxValue;
break;
}
}
}
catch (System.OverflowException)
{
switch (stage)
{
case 1:
v1 = (((s.a + s.b) + s.c) + s.d);
break;
case 2:
v2 = (s.d + ((s.a + s.b) + s.c));
break;
case 3:
v3 = ((s.a + s.b) + s.c);
break;
case 4:
v4 = (s.c + (s.a + s.b));
break;
case 5:
v5 = (s.a + s.b);
break;
case 6:
v6 = (s.b + s.a);
break;
case 7:
v7 = (s.a + s.b);
break;
case 8:
v8 = (s.b + s.a);
break;
case 9:
v9 = (s.a + (s.b + s.c));
break;
case 10:
v10 = (s.b + (s.a + s.c));
break;
case 11:
v11 = (s.b + s.c);
break;
case 12:
v12 = (s.a + s.c);
break;
case 13:
v13 = ((s.a + s.b) + s.c);
break;
case 14:
v14 = (s.c + (s.a + s.b));
break;
case 15:
v15 = ((s.a + s.b) + (s.c + s.d));
break;
case 16:
v16 = (s.c + ((s.a + s.b) + s.d));
break;
case 17:
v17 = (s.c + s.d);
break;
case 18:
v18 = ((s.a + s.b) + s.d);
break;
case 19:
v19 = (s.a + (s.b + s.d));
break;
case 20:
v20 = (s.b + (s.a + s.d));
break;
case 21:
v21 = (s.b + s.d);
break;
case 22:
v22 = (s.a + s.d);
break;
case 23:
v23 = (((s.a + s.b) + s.c) + s.d);
break;
case 24:
v24 = (s.d + ((s.a + s.b) + s.c));
break;
}
goto start_try;
}
if (stage != 25)
{
Console.WriteLine("test for stage failed actual value {0} ", stage);
ret = ret + 1;
}
if (v1 != 180)
{
Console.WriteLine("test0: for (((s.a+s.b)+s.c)+s.d) failed actual value {0} ", v1);
ret = ret + 1;
}
if (v2 != 180)
{
Console.WriteLine("test1: for (s.d+((s.a+s.b)+s.c)) failed actual value {0} ", v2);
ret = ret + 1;
}
if (v3 != 124)
{
Console.WriteLine("test2: for ((s.a+s.b)+s.c) failed actual value {0} ", v3);
ret = ret + 1;
}
if (v4 != 124)
{
Console.WriteLine("test3: for (s.c+(s.a+s.b)) failed actual value {0} ", v4);
ret = ret + 1;
}
if (v5 != 35)
{
Console.WriteLine("test4: for (s.a+s.b) failed actual value {0} ", v5);
ret = ret + 1;
}
if (v6 != 35)
{
Console.WriteLine("test5: for (s.b+s.a) failed actual value {0} ", v6);
ret = ret + 1;
}
if (v7 != 35)
{
Console.WriteLine("test6: for (s.a+s.b) failed actual value {0} ", v7);
ret = ret + 1;
}
if (v8 != 35)
{
Console.WriteLine("test7: for (s.b+s.a) failed actual value {0} ", v8);
ret = ret + 1;
}
if (v9 != 124)
{
Console.WriteLine("test8: for (s.a+(s.b+s.c)) failed actual value {0} ", v9);
ret = ret + 1;
}
if (v10 != 124)
{
Console.WriteLine("test9: for (s.b+(s.a+s.c)) failed actual value {0} ", v10);
ret = ret + 1;
}
if (v11 != 175)
{
Console.WriteLine("test10: for (s.b+s.c) failed actual value {0} ", v11);
ret = ret + 1;
}
if (v12 != 38)
{
Console.WriteLine("test11: for (s.a+s.c) failed actual value {0} ", v12);
ret = ret + 1;
}
if (v13 != 124)
{
Console.WriteLine("test12: for ((s.a+s.b)+s.c) failed actual value {0} ", v13);
ret = ret + 1;
}
if (v14 != 124)
{
Console.WriteLine("test13: for (s.c+(s.a+s.b)) failed actual value {0} ", v14);
ret = ret + 1;
}
if (v15 != 180)
{
Console.WriteLine("test14: for ((s.a+s.b)+(s.c+s.d)) failed actual value {0} ", v15);
ret = ret + 1;
}
if (v16 != 180)
{
Console.WriteLine("test15: for (s.c+((s.a+s.b)+s.d)) failed actual value {0} ", v16);
ret = ret + 1;
}
if (v17 != 145)
{
Console.WriteLine("test16: for (s.c+s.d) failed actual value {0} ", v17);
ret = ret + 1;
}
if (v18 != 91)
{
Console.WriteLine("test17: for ((s.a+s.b)+s.d) failed actual value {0} ", v18);
ret = ret + 1;
}
if (v19 != 91)
{
Console.WriteLine("test18: for (s.a+(s.b+s.d)) failed actual value {0} ", v19);
ret = ret + 1;
}
if (v20 != 91)
{
Console.WriteLine("test19: for (s.b+(s.a+s.d)) failed actual value {0} ", v20);
ret = ret + 1;
}
if (v21 != 142)
{
Console.WriteLine("test20: for (s.b+s.d) failed actual value {0} ", v21);
ret = ret + 1;
}
if (v22 != 5)
{
Console.WriteLine("test21: for (s.a+s.d) failed actual value {0} ", v22);
ret = ret + 1;
}
if (v23 != 180)
{
Console.WriteLine("test22: for (((s.a+s.b)+s.c)+s.d) failed actual value {0} ", v23);
ret = ret + 1;
}
if (v24 != 180)
{
Console.WriteLine("test23: for (s.d+((s.a+s.b)+s.c)) failed actual value {0} ", v24);
ret = ret + 1;
}
#if LOOP
s.d = return_int(false, 56);
}
} while (v24 == 0);
#endif
#if TRY
} finally {
}
#endif
#if LOOP
} while (ret== 1000);
#endif
Console.WriteLine(ret);
return ret;
}
private static int return_int(bool verbose, int input)
{
int ans;
try
{
ans = input;
}
finally
{
if (verbose)
{
Console.WriteLine("returning : ans");
}
}
return ans;
}
}
public class class_s
{
public int a;
public int b;
public int c;
public int d;
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Markdig.Extensions.Footnotes;
using Markdig.Renderers.Html;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using NUnit.Framework;
namespace Markdig.Tests
{
/// <summary>
/// Test the precise source location of all Markdown elements, including extensions
/// </summary>
[TestFixture]
public class TestSourcePosition
{
[Test]
public void TestParagraph()
{
Check("0123456789", @"
paragraph ( 0, 0) 0-9
literal ( 0, 0) 0-9
");
}
[Test]
public void TestParagraphAndNewLine()
{
Check("0123456789\n0123456789", @"
paragraph ( 0, 0) 0-20
literal ( 0, 0) 0-9
linebreak ( 0,10) 10-10
literal ( 1, 0) 11-20
");
Check("0123456789\r\n0123456789", @"
paragraph ( 0, 0) 0-21
literal ( 0, 0) 0-9
linebreak ( 0,10) 10-10
literal ( 1, 0) 12-21
");
}
[Test]
public void TestParagraphNewLineAndSpaces()
{
// 0123 45678
Check("012\n 345", @"
paragraph ( 0, 0) 0-8
literal ( 0, 0) 0-2
linebreak ( 0, 3) 3-3
literal ( 1, 2) 6-8
");
}
[Test]
public void TestParagraph2()
{
Check("0123456789\n\n0123456789", @"
paragraph ( 0, 0) 0-9
literal ( 0, 0) 0-9
paragraph ( 2, 0) 12-21
literal ( 2, 0) 12-21
");
}
[Test]
public void TestEmphasis()
{
Check("012**3456789**", @"
paragraph ( 0, 0) 0-13
literal ( 0, 0) 0-2
emphasis ( 0, 3) 3-13
literal ( 0, 5) 5-11
");
}
[Test]
public void TestEmphasis2()
{
// 01234567
Check("01*2**3*", @"
paragraph ( 0, 0) 0-7
literal ( 0, 0) 0-1
emphasis ( 0, 2) 2-7
literal ( 0, 3) 3-3
literal ( 0, 4) 4-5
literal ( 0, 6) 6-6
");
}
[Test]
public void TestEmphasis3()
{
// 0123456789
Check("01**2***3*", @"
paragraph ( 0, 0) 0-9
literal ( 0, 0) 0-1
emphasis ( 0, 2) 2-6
literal ( 0, 4) 4-4
emphasis ( 0, 7) 7-9
literal ( 0, 8) 8-8
");
}
[Test]
public void TestEmphasisFalse()
{
Check("0123456789**0123", @"
paragraph ( 0, 0) 0-15
literal ( 0, 0) 0-9
literal ( 0,10) 10-11
literal ( 0,12) 12-15
");
}
[Test]
public void TestHeading()
{
// 012345
Check("# 2345", @"
heading ( 0, 0) 0-5
literal ( 0, 2) 2-5
");
}
[Test]
public void TestHeadingWithEmphasis()
{
// 0123456789
Check("# 23**45**", @"
heading ( 0, 0) 0-9
literal ( 0, 2) 2-3
emphasis ( 0, 4) 4-9
literal ( 0, 6) 6-7
");
}
[Test]
public void TestFootnoteLinkReferenceDefinition()
{
// 01 2 345678
var footnote = Markdown.Parse("0\n\n [^1]:", new MarkdownPipelineBuilder().UsePreciseSourceLocation().UseFootnotes().Build()).Descendants<FootnoteLinkReferenceDefinition>().FirstOrDefault();
Assert.NotNull(footnote);
Assert.AreEqual(2, footnote.Line);
Assert.AreEqual(new SourceSpan(4, 7), footnote.Span);
Assert.AreEqual(new SourceSpan(5, 6), footnote.LabelSpan);
}
[Test]
public void TestLinkReferenceDefinition1()
{
// 0 1
// 0123456789012345
var link = Markdown.Parse("[234]: /56 'yo' ", new MarkdownPipelineBuilder().UsePreciseSourceLocation().Build()).Descendants<LinkReferenceDefinition>().FirstOrDefault();
Assert.NotNull(link);
Assert.AreEqual(0, link.Line);
Assert.AreEqual(new SourceSpan(0, 14), link.Span);
Assert.AreEqual(new SourceSpan(1, 3), link.LabelSpan);
Assert.AreEqual(new SourceSpan(7, 9), link.UrlSpan);
Assert.AreEqual(new SourceSpan(11, 14), link.TitleSpan);
}
[Test]
public void TestLinkReferenceDefinition2()
{
// 0 1
// 01 2 34567890123456789
var link = Markdown.Parse("0\n\n [234]: /56 'yo' ", new MarkdownPipelineBuilder().UsePreciseSourceLocation().Build()).Descendants<LinkReferenceDefinition>().FirstOrDefault();
Assert.NotNull(link);
Assert.AreEqual(2, link.Line);
Assert.AreEqual(new SourceSpan(4, 18), link.Span);
Assert.AreEqual(new SourceSpan(5, 7), link.LabelSpan);
Assert.AreEqual(new SourceSpan(11, 13), link.UrlSpan);
Assert.AreEqual(new SourceSpan(15, 18), link.TitleSpan);
}
[Test]
public void TestCodeSpan()
{
// 012345678
Check("0123`456`", @"
paragraph ( 0, 0) 0-8
literal ( 0, 0) 0-3
code ( 0, 4) 4-8
");
}
[Test]
public void TestLink()
{
// 0123456789
Check("012[45](#)", @"
paragraph ( 0, 0) 0-9
literal ( 0, 0) 0-2
link ( 0, 3) 3-9
literal ( 0, 4) 4-5
");
}
[Test]
public void TestLinkParts1()
{
// 0 1
// 01 2 3456789012345
var link = Markdown.Parse("0\n\n01 [234](/56)", new MarkdownPipelineBuilder().UsePreciseSourceLocation().Build()).Descendants<LinkInline>().FirstOrDefault();
Assert.NotNull(link);
Assert.AreEqual(new SourceSpan(7, 9), link.LabelSpan);
Assert.AreEqual(new SourceSpan(12, 14), link.UrlSpan);
Assert.AreEqual(SourceSpan.Empty, link.TitleSpan);
}
[Test]
public void TestLinkParts2()
{
// 0 1
// 01 2 34567890123456789
var link = Markdown.Parse("0\n\n01 [234](/56 'yo')", new MarkdownPipelineBuilder().UsePreciseSourceLocation().Build()).Descendants<LinkInline>().FirstOrDefault();
Assert.NotNull(link);
Assert.AreEqual(new SourceSpan(7, 9), link.LabelSpan);
Assert.AreEqual(new SourceSpan(12, 14), link.UrlSpan);
Assert.AreEqual(new SourceSpan(16, 19), link.TitleSpan);
}
[Test]
public void TestLinkParts3()
{
// 0 1
// 01 2 3456789012345
var link = Markdown.Parse("0\n\n01", new MarkdownPipelineBuilder().UsePreciseSourceLocation().Build()).Descendants<LinkInline>().FirstOrDefault();
Assert.NotNull(link);
Assert.AreEqual(new SourceSpan(5, 15), link.Span);
Assert.AreEqual(new SourceSpan(7, 9), link.LabelSpan);
Assert.AreEqual(new SourceSpan(12, 14), link.UrlSpan);
Assert.AreEqual(SourceSpan.Empty, link.TitleSpan);
}
[Test]
public void TestAutolinkInline()
{
// 0123456789ABCD
Check("01<http://yes>", @"
paragraph ( 0, 0) 0-13
literal ( 0, 0) 0-1
autolink ( 0, 2) 2-13
");
}
[Test]
public void TestFencedCodeBlock()
{
// 012 3456 78 9ABC
Check("01\n```\n3\n```\n", @"
paragraph ( 0, 0) 0-1
literal ( 0, 0) 0-1
fencedcode ( 1, 0) 3-11
");
}
[Test]
public void TestHtmlBlock()
{
// 012345 67 89ABCDE F 0
Check("<div>\n0\n</div>\n\n1", @"
html ( 0, 0) 0-13
paragraph ( 4, 0) 16-16
literal ( 4, 0) 16-16
");
}
[Test]
public void TestHtmlBlock1()
{
// 0 1
// 01 2 345678901 23
Check("0\n\n<!--A-->\n1\n", @"
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
html ( 2, 0) 3-10
paragraph ( 3, 0) 12-12
literal ( 3, 0) 12-12
");
}
[Test]
public void TestHtmlComment()
{
// 0 1 2
// 012345678901 234567890 1234
Check("# 012345678\n<!--0-->\n123\n", @"
heading ( 0, 0) 0-10
literal ( 0, 2) 2-10
html ( 1, 0) 12-19
paragraph ( 2, 0) 21-23
literal ( 2, 0) 21-23
");
}
[Test]
public void TestHtmlInline()
{
// 0123456789
Check("01<b>4</b>", @"
paragraph ( 0, 0) 0-9
literal ( 0, 0) 0-1
html ( 0, 2) 2-4
literal ( 0, 5) 5-5
html ( 0, 6) 6-9
");
}
[Test]
public void TestHtmlInline1()
{
// 0
// 0123456789
Check("0<!--A-->1", @"
paragraph ( 0, 0) 0-9
literal ( 0, 0) 0-0
html ( 0, 1) 1-8
literal ( 0, 9) 9-9
");
}
[Test]
public void TestThematicBreak()
{
// 0123 4567
Check("---\n---\n", @"
thematicbreak ( 0, 0) 0-2
thematicbreak ( 1, 0) 4-6
");
}
[Test]
public void TestQuoteBlock()
{
// 0123456
Check("> 2345\n", @"
quote ( 0, 0) 0-5
paragraph ( 0, 2) 2-5
literal ( 0, 2) 2-5
");
}
[Test]
public void TestQuoteBlockWithLines()
{
// 01234 56789A
Check("> 01\n> 23\n", @"
quote ( 0, 0) 0-9
paragraph ( 0, 2) 2-9
literal ( 0, 2) 2-3
linebreak ( 0, 4) 4-4
literal ( 1, 3) 8-9
");
}
[Test]
public void TestQuoteBlockWithLazyContinuation()
{
// 01234 56
Check("> 01\n23\n", @"
quote ( 0, 0) 0-6
paragraph ( 0, 2) 2-6
literal ( 0, 2) 2-3
linebreak ( 0, 4) 4-4
literal ( 1, 0) 5-6
");
}
[Test]
public void TestListBlock()
{
// 0123 4567
Check("- 0\n- 1\n", @"
list ( 0, 0) 0-6
listitem ( 0, 0) 0-2
paragraph ( 0, 2) 2-2
literal ( 0, 2) 2-2
listitem ( 1, 0) 4-6
paragraph ( 1, 2) 6-6
literal ( 1, 2) 6-6
");
}
[Test]
public void TestListBlock2()
{
string test = @"
1. Foo
9. Bar
5. Foo
6. Bar
987123. FooBar";
test = test.Replace("\r\n", "\n");
var list = Markdown.Parse(test, new MarkdownPipelineBuilder().UsePreciseSourceLocation().Build()).Descendants<ListBlock>().FirstOrDefault();
Assert.NotNull(list);
Assert.AreEqual(1, list.Line);
Assert.True(list.IsOrdered);
List<ListItemBlock> items = list.Cast<ListItemBlock>().ToList();
Assert.AreEqual(5, items.Count);
// Test orders
Assert.AreEqual(1, items[0].Order);
Assert.AreEqual(9, items[1].Order);
Assert.AreEqual(5, items[2].Order);
Assert.AreEqual(6, items[3].Order);
Assert.AreEqual(987123, items[4].Order);
// Test positions
for (int i = 0; i < 4; i++)
{
Assert.AreEqual(i + 1, items[i].Line);
Assert.AreEqual(1 + (i * 7), items[i].Span.Start);
Assert.AreEqual(6, items[i].Span.Length);
}
Assert.AreEqual(5, items[4].Line);
Assert.AreEqual(new SourceSpan(29, 42), items[4].Span);
}
[Test]
public void TestEscapeInline()
{
// 0123
Check(@"\-\)", @"
paragraph ( 0, 0) 0-3
literal ( 0, 0) 0-1
literal ( 0, 2) 2-3
");
}
[Test]
public void TestHtmlEntityInline()
{
// 01 23456789
Check("0\n 1", @"
paragraph ( 0, 0) 0-9
literal ( 0, 0) 0-0
linebreak ( 0, 1) 1-1
htmlentity ( 1, 0) 2-7
literal ( 1, 6) 8-9
");
}
[Test]
public void TestAbbreviations()
{
Check("*[HTML]: Hypertext Markup Language\r\n\r\nLater in a text we are using HTML and it becomes an abbr tag HTML", @"
paragraph ( 2, 0) 38-102
container ( 2, 0) 38-102
literal ( 2, 0) 38-66
abbreviation ( 2,29) 67-70
literal ( 2,33) 71-98
abbreviation ( 2,61) 99-102
", "abbreviations");
}
[Test]
public void TestCitation()
{
// 0123 4 567 8
Check("01 \"\"23\"\"", @"
paragraph ( 0, 0) 0-8
literal ( 0, 0) 0-2
emphasis ( 0, 3) 3-8
literal ( 0, 5) 5-6
", "citations");
}
[Test]
public void TestCustomContainer()
{
// 01 2345 678 9ABC DEF
Check("0\n:::\n23\n:::\n45\n", @"
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
customcontainer ( 1, 0) 2-11
paragraph ( 2, 0) 6-7
literal ( 2, 0) 6-7
paragraph ( 4, 0) 13-14
literal ( 4, 0) 13-14
", "customcontainers");
}
[Test]
public void TestDefinitionList()
{
// 012 3456789A
Check("a0\n: 1234", @"
definitionlist ( 0, 0) 0-10
definitionitem ( 1, 0) 3-10
definitionterm ( 0, 0) 0-1
literal ( 0, 0) 0-1
paragraph ( 1, 4) 7-10
literal ( 1, 4) 7-10
", "definitionlists");
}
[Test]
public void TestDefinitionList2()
{
// 012 3456789AB CDEF01234
Check("a0\n: 1234\n: 5678", @"
definitionlist ( 0, 0) 0-20
definitionitem ( 1, 0) 3-10
definitionterm ( 0, 0) 0-1
literal ( 0, 0) 0-1
paragraph ( 1, 4) 7-10
literal ( 1, 4) 7-10
definitionitem ( 2, 4) 12-20
paragraph ( 2, 5) 17-20
literal ( 2, 5) 17-20
", "definitionlists");
}
[Test]
public void TestEmoji()
{
// 01 2345
Check("0\n :)\n", @"
paragraph ( 0, 0) 0-4
literal ( 0, 0) 0-0
linebreak ( 0, 1) 1-1
emoji ( 1, 1) 3-4
", "emojis");
}
[Test]
public void TestEmphasisExtra()
{
// 0123456
Check("0 ~~1~~", @"
paragraph ( 0, 0) 0-6
literal ( 0, 0) 0-1
emphasis ( 0, 2) 2-6
literal ( 0, 4) 4-4
", "emphasisextras");
}
[Test]
public void TestFigures()
{
// 01 2345 67 89AB
Check("0\n^^^\n0\n^^^\n", @"
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
figure ( 1, 0) 2-10
paragraph ( 2, 0) 6-6
literal ( 2, 0) 6-6
", "figures");
}
[Test]
public void TestFiguresCaption1()
{
// 01 234567 89 ABCD
Check("0\n^^^ab\n0\n^^^\n", @"
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
figure ( 1, 0) 2-12
figurecaption ( 1, 3) 5-6
literal ( 1, 3) 5-6
paragraph ( 2, 0) 8-8
literal ( 2, 0) 8-8
", "figures");
}
[Test]
public void TestFiguresCaption2()
{
// 01 2345 67 89ABCD
Check("0\n^^^\n0\n^^^ab\n", @"
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
figure ( 1, 0) 2-12
paragraph ( 2, 0) 6-6
literal ( 2, 0) 6-6
figurecaption ( 3, 3) 11-12
literal ( 3, 3) 11-12
", "figures");
}
[Test]
public void TestFooters()
{
// 01 234567 89ABCD
Check("0\n^^ 12\n^^ 34\n", @"
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
footer ( 1, 0) 2-12
paragraph ( 1, 3) 5-12
literal ( 1, 3) 5-6
linebreak ( 1, 5) 7-7
literal ( 2, 3) 11-12
", "footers");
}
[Test]
public void TestAttributes()
{
// 0123456789
Check("0123{#456}", @"
paragraph ( 0, 0) 0-9
attributes ( 0, 4) 4-9
literal ( 0, 0) 0-3
", "attributes");
}
[Test]
public void TestAttributesForHeading()
{
// 0123456789ABC
Check("# 01 {#456}", @"
heading ( 0, 0) 0-4
attributes ( 0, 5) 5-10
literal ( 0, 2) 2-3
", "attributes");
}
[Test]
public void TestMathematicsInline()
{
// 01 23456789AB
Check("0\n012 $abcd$", @"
paragraph ( 0, 0) 0-11
literal ( 0, 0) 0-0
linebreak ( 0, 1) 1-1
literal ( 1, 0) 2-5
math ( 1, 4) 6-11
attributes ( 0, 0) 0--1
", "mathematics");
}
[Test]
public void TestSmartyPants()
{
// 01234567
// 01 23456789
Check("0\n2 <<45>>", @"
paragraph ( 0, 0) 0-9
literal ( 0, 0) 0-0
linebreak ( 0, 1) 1-1
literal ( 1, 0) 2-3
smartypant ( 1, 2) 4-5
literal ( 1, 4) 6-7
smartypant ( 1, 6) 8-9
", "smartypants");
}
[Test]
public void TestSmartyPantsUnbalanced()
{
// 012345
// 01 234567
Check("0\n2 <<45", @"
paragraph ( 0, 0) 0-7
literal ( 0, 0) 0-0
linebreak ( 0, 1) 1-1
literal ( 1, 0) 2-3
literal ( 1, 2) 4-5
literal ( 1, 4) 6-7
", "smartypants");
}
[Test]
public void TestPipeTable()
{
// 0123 4567 89AB
Check("a|b\n-|-\n0|1\n", @"
table ( 0, 0) 0-10
tablerow ( 0, 0) 0-2
tablecell ( 0, 0) 0-0
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
tablecell ( 0, 2) 2-2
paragraph ( 0, 2) 2-2
literal ( 0, 2) 2-2
tablerow ( 2, 0) 8-10
tablecell ( 2, 0) 8-8
paragraph ( 2, 0) 8-8
literal ( 2, 0) 8-8
tablecell ( 2, 2) 10-10
paragraph ( 2, 2) 10-10
literal ( 2, 2) 10-10
", "pipetables");
}
[Test]
public void TestPipeTable2()
{
// 01 2 3456 789A BCD
Check("0\n\na|b\n-|-\n0|1\n", @"
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
table ( 2, 0) 3-13
tablerow ( 2, 0) 3-5
tablecell ( 2, 0) 3-3
paragraph ( 2, 0) 3-3
literal ( 2, 0) 3-3
tablecell ( 2, 2) 5-5
paragraph ( 2, 2) 5-5
literal ( 2, 2) 5-5
tablerow ( 4, 0) 11-13
tablecell ( 4, 0) 11-11
paragraph ( 4, 0) 11-11
literal ( 4, 0) 11-11
tablecell ( 4, 2) 13-13
paragraph ( 4, 2) 13-13
literal ( 4, 2) 13-13
", "pipetables");
}
[Test]
public void TestIndentedCode()
{
// 01 2 345678 9ABCDE
Check("0\n\n 0\n 1\n", @"
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
code ( 2, 0) 3-13
");
}
[Test]
public void TestIndentedCodeAfterList()
{
// 0 1 2 3 4 5
// 012345678901234567 8 901234567890123456 789012345678901234 56789
Check("1) Some list item\n\n some code\n more code\n", @"
list ( 0, 0) 0-53
listitem ( 0, 0) 0-53
paragraph ( 0, 3) 3-16
literal ( 0, 3) 3-16
code ( 2, 0) 19-53
");
}
[Test]
public void TestIndentedCodeWithTabs()
{
// 01 2 3 45 6 78
Check("0\n\n\t0\n\t1\n", @"
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
code ( 2, 0) 3-7
");
}
[Test]
public void TestIndentedCodeWithMixedTabs()
{
// 01 2 34 56 78 9
Check("0\n\n \t0\n \t1\n", @"
paragraph ( 0, 0) 0-0
literal ( 0, 0) 0-0
code ( 2, 0) 3-9
");
}
[Test]
public void TestTabsInList()
{
// 012 34 567 89
Check("- \t0\n- \t1\n", @"
list ( 0, 0) 0-8
listitem ( 0, 0) 0-3
paragraph ( 0, 4) 3-3
literal ( 0, 4) 3-3
listitem ( 1, 0) 5-8
paragraph ( 1, 4) 8-8
literal ( 1, 4) 8-8
");
}
[Test]
public void TestDocument()
{
// L0 L0 L1L2 L3 L4 L5L6 L7L8
// 0 10 20 30 40 50 60 70 80 90
// 012345678901234567890 1 2345678901 2345678901 2345678901 2 345678901234567890123 4 5678901234567890123
Check("# This is a document\n\n1) item 1\n2) item 2\n3) item 4\n\nWith an **emphasis**\n\n> and a blockquote\n", @"
heading ( 0, 0) 0-19
literal ( 0, 2) 2-19
list ( 2, 0) 22-51
listitem ( 2, 0) 22-30
paragraph ( 2, 3) 25-30
literal ( 2, 3) 25-30
listitem ( 3, 0) 32-40
paragraph ( 3, 3) 35-40
literal ( 3, 3) 35-40
listitem ( 4, 0) 42-51
paragraph ( 4, 3) 45-50
literal ( 4, 3) 45-50
paragraph ( 6, 0) 53-72
literal ( 6, 0) 53-60
emphasis ( 6, 8) 61-72
literal ( 6,10) 63-70
quote ( 8, 0) 75-92
paragraph ( 8, 2) 77-92
literal ( 8, 2) 77-92
");
}
private static void Check(string text, string expectedResult, string extensions = null)
{
var pipelineBuilder = new MarkdownPipelineBuilder().UsePreciseSourceLocation();
if (extensions != null)
{
pipelineBuilder.Configure(extensions);
}
var pipeline = pipelineBuilder.Build();
var document = Markdown.Parse(text, pipeline);
var build = new StringBuilder();
foreach (var val in document.Descendants())
{
var name = GetTypeName(val.GetType());
build.Append($"{name,-12} ({val.Line,2},{val.Column,2}) {val.Span.Start,2}-{val.Span.End}\n");
var attributes = val.TryGetAttributes();
if (attributes != null)
{
build.Append($"{"attributes",-12} ({attributes.Line,2},{attributes.Column,2}) {attributes.Span.Start,2}-{attributes.Span.End}\n");
}
}
var result = build.ToString().Trim();
expectedResult = expectedResult.Trim();
expectedResult = expectedResult.Replace("\r\n", "\n").Replace("\r", "\n");
if (expectedResult != result)
{
Console.WriteLine("```````````````````Source");
Console.WriteLine(TestParser.DisplaySpaceAndTabs(text));
Console.WriteLine("```````````````````Result");
Console.WriteLine(result);
Console.WriteLine("```````````````````Expected");
Console.WriteLine(expectedResult);
Console.WriteLine("```````````````````");
Console.WriteLine();
}
TextAssert.AreEqual(expectedResult, result);
}
private static string GetTypeName(Type type)
{
return type.Name.ToLowerInvariant()
.Replace("block", string.Empty)
.Replace("inline", string.Empty);
}
}
}
| |
// $Id$
//
// 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 Org.Apache.Etch.Bindings.Csharp.Msg;
using Org.Apache.Etch.Bindings.Csharp.Support;
namespace Org.Apache.Etch.Bindings.Csharp.Transport.Fmt
{
/// <summary>
/// Common interface for various types of tagged data input and output.
/// </summary>
abstract public class TaggedData
{
public TaggedData()
{
}
/// <summary>
/// Constructs the TaggedData.
/// </summary>
/// <param name="vf"></param>
public TaggedData( ValueFactory vf )
{
this.vf = vf;
}
/// <summary>
/// The value factory to use for tagged input and output.
/// </summary>
protected readonly ValueFactory vf;
/// <summary>
///
/// </summary>
/// <returns>the value factory to use for tagged input and output.</returns>
public ValueFactory GetValueFactory()
{
return vf;
}
protected ArrayValue ToArrayValue( Object value, Validator v )
{
Type c = value.GetType();
int dim = 0;
while ( c.IsArray )
{
dim++;
c = c.GetElementType();
}
// now we want the type code for c, and if the type code is custom,
// we'll also want the struct type code.
sbyte typeCode = GetNativeTypeCode( c );
XType customStructType;
if (typeCode == TypeCode.CUSTOM || typeCode == TypeCode.STRUCT)
{
customStructType = GetCustomStructType(c);
if (customStructType == null && c == typeof(StructValue))
{
Validator_StructValue x = FindStructValueValidator( v );
if (x != null)
customStructType = x.GetXType();
}
if (customStructType == null )
throw new ArgumentException(" In tagged Data" );
}
else
customStructType = null;
return new ArrayValue( value, typeCode, customStructType, dim );
}
private Validator_StructValue FindStructValueValidator( Validator v )
{
if (v is Validator_StructValue)
return (Validator_StructValue) v;
if (v is ComboValidator)
{
ComboValidator x = (ComboValidator) v;
Validator_StructValue y = FindStructValueValidator( x.A() );
if (y != null)
return y;
return FindStructValueValidator( x.B() );
}
return null;
}
protected Object FromArrayValue( ArrayValue av )
{
return av.GetArray();
}
protected Object AllocateArrayValue( sbyte typeCode, XType customStructType,
int dim, int length )
{
Type clss = GetComponentType( typeCode, customStructType, dim );
if ( clss == null )
throw new ArgumentException(String.Format(
"could not get array for {0}, {1}, {2}",
typeCode, customStructType, dim));
return Array.CreateInstance( clss, length );
}
private Type GetComponentType( sbyte typeCode, XType customStructType, int dim )
{
Type c;
if (typeCode == TypeCode.CUSTOM || typeCode == TypeCode.STRUCT)
{
// c = GetCustomType( customStructType );
c = customStructType.GetComponentType();
if (c == null)
c = typeof (StructValue);
}
else
c = GetNativeType(typeCode);
//Console.WriteLine( "c = " + c );
if ( c == null )
return null;
if ( dim == 0 )
return c;
int[] dims;
while ( dim > 0 )
{
dims = new int[ dim ];
if ( dim > 1 )
c = c.MakeArrayType();
dim--;
}
//Object o = Array.CreateInstance( c, 1 );
//c = ( ( Array ) o ).GetType();
//Console.WriteLine( "type= "+c );
return c;
}
/// <summary>
/// Returns the type code for the specified class. This
/// is needed when we have an array and we have determine
/// the base type and now we're fixing to serialize it.
/// We use the base type code to reconstitute it on the
/// other side. So we don't return a perfect code the way
/// checkValue does, but rather just something that let's
/// us recreate the appropriate array type on import.
/// </summary>
/// <param name="c"></param>
/// <returns>a type code for the specified class.</returns>
abstract public sbyte GetNativeTypeCode( Type c );
/// <summary>
///
/// </summary>
/// <param name="c"></param>
/// <returns>a struct type for the specified custom class.</returns>
abstract public XType GetCustomStructType( Type c );
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns>the class for a specified (native) type code.</returns>
abstract public Type GetNativeType( sbyte type );
abstract public sbyte CheckValue( Object value );
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ALang
{
/// <summary>
/// Represents a file containing list of lexemes and additional information
/// </summary>
public sealed class LexemeModule
{
public List<Lexeme> Lexemes;
public string FileName;
}
/// <summary>
/// Stores part of input source code
/// </summary>
public sealed class Lexeme
{
public string Source;
public enum CodeType
{
Reserved,
Number,
Name,
Delimiter,
String
};
public CodeType Code;
public int Line;
};
public sealed class Lexer
{
public Lexer()
{
m_delimiters = m_delimiters.OrderByDescending(delim => delim.Length).ToList();
}
public void Convert(List<SourceFileInfo> sources)
{
int pos;
foreach (var source in sources)
{
pos = 0;
m_lexemes = new List<Lexeme>();
while (pos < source.SourceCode.Length)
{
pos = FindLexerPart(source.SourceCode, pos);
}
m_output.Add(new LexemeModule {FileName = source.FileName, Lexemes = m_lexemes});
}
}
public List<LexemeModule> GetOutput()
{
return m_output;
}
private int FindLexerPart(string source, int pos)
{
if (source[pos] == '/' && source[pos + 1] == '/')
{
return RemoveComment(source, pos);
}
else if (Char.IsLetter(source[pos]))
{
return ReadWord(source, pos);
}
else if (m_delimiters.Exists(delim => delim[0] == source[pos]))
{
return ReadDelimiter(source, pos);
}
else if (Char.IsDigit(source[pos]))
{
return ReadNumber(source, pos);
}
else if (source[pos] == '\"')
{
return ReadString(source, pos);
}
else if (Char.IsWhiteSpace(source[pos]))
{
if (source[pos] == '\n')
{
m_currentLine++;
}
return pos + 1;
}
else
{
throw new Exception("Unknown lexeme: " + source[pos]);
}
}
private int RemoveComment(string source, int pos)
{
pos += 2; //skip '//'
while (source[pos] != '\n')
++pos;
return ++pos;
}
private int ReadWord(string source, int pos)
{
StringBuilder builder = new StringBuilder();
while (Char.IsLetterOrDigit(source[pos]) || source[pos] == '_')
{
builder.Append(source[pos]);
++pos;
}
string result = builder.ToString();
m_lexemes.Add(new Lexeme {Source = result, Code = GetIsReserved(result), Line = m_currentLine});
return pos;
}
private int ReadDelimiter(string source, int pos)
{
int index = m_delimiters.FindIndex(delim => (pos + delim.Length) > source.Length
? false
: delim == source.Substring(pos, delim.Length));
if (index == -1)
{
//WTF?
throw new System.Exception("WTF with delimiters");
}
m_lexemes.Add(new Lexeme
{
Source = m_delimiters[index],
Code = Lexeme.CodeType.Delimiter,
Line = m_currentLine
});
pos += m_delimiters[index].Length;
return pos;
}
private int ReadNumber(string source, int pos)
{
StringBuilder builder = new StringBuilder();
int pointCount = 0;
while (Char.IsDigit(source[pos]) || (source[pos] == '.' && pointCount++ == 0))
{
builder.Append(source[pos]);
++pos;
}
string result = builder.ToString();
m_lexemes.Add(new Lexeme {Source = result, Code = Lexeme.CodeType.Number, Line = m_currentLine});
return pos;
}
private int ReadString(string source, int pos)
{
StringBuilder builder = new StringBuilder();
++pos; //Skip "
while (source[pos] != '\"')
{
if (source[pos] == '\\')
continue;
builder.Append(source[pos]);
++pos;
}
++pos; //Skip "
string result = builder.ToString();
m_lexemes.Add(new Lexeme {Source = result, Code = Lexeme.CodeType.String, Line = m_currentLine});
return pos;
}
Lexeme.CodeType GetIsReserved(string source)
{
if (m_reserved.Contains(source))
return Lexeme.CodeType.Reserved;
else
return Lexeme.CodeType.Name;
}
List<LexemeModule> m_output = new List<LexemeModule>();
List<Lexeme> m_lexemes;
int m_currentLine = 0;
List<string> m_reserved = new List<string>
{
"if",
"else",
"for",
"while",
"function",
"class",
"constexpr",
"using",
"component",
"default",
"Int8",
"Int16",
"Int32",
"Int64",
"Bool",
"Single",
"Double",
"String"
};
List<string> m_delimiters = new List<string>
{
"+",
"-",
"*",
"/",
",",
".",
"<",
">",
"<=",
">=",
"=",
"!=",
";",
":",
"%",
"^",
"(",
")",
"[",
"]",
"{",
"}",
"->"
};
}
}
| |
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Util;
using NUnit.Framework;
using System;
using System.IO;
using System.Security.Principal;
using System.Threading;
namespace newtelligence.DasBlog.Runtime.Test
{
[TestFixture]
public class BlogDataServiceTest : BlogServiceContainer
{
[Test]
public void VerifySaveEntry()
{
Guid entryId = Guid.NewGuid();
Entry entry = new Entry();
entry.Initialize();
entry.CreatedUtc = new DateTime(2004, 1, 1);
entry.Title = "Happy New ear";
entry.Content = "The beginning of a new year.";
entry.Categories = "Test";
entry.EntryId = entryId.ToString();
entry.Description = "The description of the entry.";
entry.Author = "Inigo Montoya";
// TODO: Update so private entries will work as well.
entry.IsPublic = true;
entry.Language = "C#";
entry.Link = "http://mark.michaelis.net/blog";
entry.ModifiedUtc = entry.CreatedUtc;
entry.ShowOnFrontPage = false;
BlogDataService.SaveEntry( entry );
entry = BlogDataService.GetEntry(entryId.ToString());
Assert.IsNotNull(entry, "Unable to retrieve the specified entry.");
Assert.AreEqual(entryId.ToString(), entry.EntryId);
Assert.AreEqual(new DateTime(2004, 1, 1), entry.CreatedUtc);
Assert.AreEqual("Happy New ear", entry.Title);
Assert.AreEqual("The beginning of a new year.", entry.Content);
Assert.AreEqual("Test", entry.Categories);
Assert.AreEqual("The description of the entry.", entry.Description);
Assert.AreEqual("Inigo Montoya", entry.Author);
Assert.AreEqual(true, entry.IsPublic);
Assert.AreEqual("C#", entry.Language);
Assert.AreEqual("http://mark.michaelis.net/blog", entry.Link);
Assert.AreEqual(entry.CreatedUtc, entry.ModifiedUtc);
Assert.AreEqual(false, entry.ShowOnFrontPage);
}
[Test]
public void GetDayEntry()
{
IDayEntry dayEntry;
// Note that non public items are ignored.
dayEntry = BlogDataService.GetDayEntry(new DateTime(2003, 7, 31));
Assert.AreEqual(6, dayEntry.GetEntries().Count);
// Note that non public items are ignored.
dayEntry = BlogDataService.GetDayEntry(new DateTime(2003, 8, 1));
Assert.AreEqual(4, dayEntry.GetEntries().Count);
}
[Test]
public void VerifyGetEntriesFormMonth()
{
EntryCollection entries;
TimeZone timeZone = TimeZone.CurrentTimeZone;
DateTime dateTime;
// Since TimeZone does not have a constructor for a particular
// time zone we only run this test for the Pacific Time Zone.
if(timeZone.StandardName == "Pacific Standard Time")
{
dateTime = new DateTime(2004, 3, 4).ToUniversalTime();
entries = BlogDataService.GetEntriesForMonth(dateTime,
timeZone, null);
Assert.AreEqual(3, entries.Count);
// Note that non-public items are not returned.
dateTime = new DateTime(2003, 7, 31).ToUniversalTime();
entries = BlogDataService.GetEntriesForMonth(dateTime,
timeZone, null);
Assert.AreEqual(8, entries.Count);
dateTime = new DateTime(2003, 1, 4).ToUniversalTime();
entries = BlogDataService.GetEntriesForMonth(dateTime,
timeZone, null);
Assert.AreEqual(0, entries.Count);
}
}
[Test]
public void VerifyGetEntriesForCategory()
{
EntryCollection entries;
// Note that non-public entries are not returned by default.
entries = BlogDataService.GetEntriesForCategory(
"G. K. Chesterton Quotes", null);
Assert.AreEqual(10, entries.Count);
entries = BlogDataService.GetEntriesForCategory(
"G. K. Chesterton Quotes|More By Chesterton", null);
Assert.AreEqual(2, entries.Count);
// Note that non-public entries are not returned by default.
entries = BlogDataService.GetEntriesForCategory(
"G. K. Chesterton Quotes|Private Entry", null);
Assert.AreEqual(0, entries.Count);
}
[Test]
public void VerifyGetEntry()
{
Entry entry;
IPrincipal originalPrincipal;
entry = BlogDataService.GetEntry(
"0c805dc8-e389-4d05-9bd8-9a99a28d78f4");
Assert.AreEqual("Interesting but not necessarily true.", entry.Title);
// Don't return private entries by default.
entry = BlogDataService.GetEntry(
"40f5dbc6-3a50-4bea-833b-8be993886258");
Assert.IsNull(entry, "Unexpectedly we retrieved a private entry.");
originalPrincipal = Thread.CurrentPrincipal;
// Return private entries if requested explicitly.
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity("junk", "junk"), new string[]{"admin"});
entry = BlogDataService.GetEntry(
"40f5dbc6-3a50-4bea-833b-8be993886258");
Assert.AreEqual("Compatible Transitional Capability (CTC)", entry.Title);
Thread.CurrentPrincipal = originalPrincipal;
// Don't return private entries by default.
entry = BlogDataService.GetEntry(
"40f5dbc6-3a50-4bea-833b-8be993886258");
Assert.IsNull(entry, "Unexpectedly we retrieved a private entry.");
}
[Test]
public void VerifyGetDaysWithEntries()
{
TimeZone timeZone = TimeZone.CurrentTimeZone;
DateTime[] daysWithEntries;
// Since TimeZone does not have a constructor for a particular
// time zone we only run this test for the Pacific Time Zone.
if(timeZone.StandardName == "Pacific Standard Time")
{
daysWithEntries = BlogDataService.GetDaysWithEntries(
timeZone);
Array.Sort(daysWithEntries);
// Rather than checking the count we look for
// particular items so that it does not cause
// problems when adding more test data.
Assert.IsTrue(Array.BinarySearch(daysWithEntries, new DateTime(2004, 3, 26)) >= 0);
Assert.IsTrue(Array.BinarySearch(daysWithEntries, new DateTime(2004, 3, 14)) >= 0);
Assert.IsTrue(Array.BinarySearch(daysWithEntries, new DateTime(2004, 3, 2)) >= 0);
Assert.IsTrue(Array.BinarySearch(daysWithEntries, new DateTime(2004, 2, 29)) >= 0);
Assert.IsTrue(Array.BinarySearch(daysWithEntries, new DateTime(2004, 2, 18)) >= 0);
Assert.IsTrue(Array.BinarySearch(daysWithEntries, new DateTime(2004, 1, 25)) >= 0);
Assert.IsTrue(Array.BinarySearch(daysWithEntries, new DateTime(2004, 1, 12)) >= 0);
Assert.IsTrue(Array.BinarySearch(daysWithEntries, new DateTime(2003, 8, 1)) >= 0);
Assert.IsTrue(Array.BinarySearch(daysWithEntries, new DateTime(2003, 7, 31)) >= 0);
Assert.IsTrue(Array.BinarySearch(daysWithEntries, new DateTime(2003, 7, 30)) >= 0);
}
}
[Test]
public void VerifyGetCategories()
{
string[] categories;
bool GKChestertonQuotes = false;
bool MoreByChesterton = false;
bool ARandomMathematicalQuotation = false;
bool Miscellaneous = false;
bool PrivateEntry = false;
categories = new string[BlogDataService.GetCategories().Count];
for(int count=0; count<categories.Length; count++)
{
if(BlogDataService.GetCategories()[count].DisplayName == "G. K. Chesterton Quotes")
{
GKChestertonQuotes = true;
}
else if(BlogDataService.GetCategories()[count].DisplayName == "More By Chesterton")
{
MoreByChesterton = true;
}
else if(BlogDataService.GetCategories()[count].DisplayName == "A Random Mathematical Quotation")
{
ARandomMathematicalQuotation = true;
}
else if(BlogDataService.GetCategories()[count].DisplayName == "Miscellaneous")
{
Miscellaneous = true;
}
else if(BlogDataService.GetCategories()[count].DisplayName == "Private Entry")
{
PrivateEntry = true;
}
}
Assert.IsTrue(GKChestertonQuotes);
Assert.IsTrue(MoreByChesterton);
Assert.IsTrue(ARandomMathematicalQuotation);
Assert.IsTrue(Miscellaneous);
Assert.IsFalse(PrivateEntry);
}
[Test]
public void VerifyPublicAreNotRetrievedByDefault()
{
IDayEntry dayEntry;
dayEntry = BlogDataService.GetDayEntry(new DateTime(2003, 7, 31));
Assert.AreEqual(6, dayEntry.GetEntries().Count,
"The correct item count was not returned considering some items were private.");
dayEntry = BlogDataService.GetDayEntry(new DateTime(2003, 8, 1));
Assert.AreEqual(4, dayEntry.GetEntries().Count,
"The correct item count was not returned considering some items were private.");
}
// [Test]
public void CreateTestEntries()
{
Entry entry;
DateTime dateTime = new DateTime(2004, 01, 1);
dateTime = dateTime.AddDays(12.33);
entry = new Entry();
entry.Initialize();
entry.Title="Naivete of the Mathematician ";
entry.Content="Mathematics is not yet capable of coping with the naivete of the mathematician himself. (Sociology Learns the Language of Mathematics.)";
entry.EntryId = Guid.NewGuid().ToString();
entry.Author = "Abraham Kaplan";
entry.CreatedUtc = dateTime;
entry.ModifiedUtc = dateTime;
entry.Categories = "A Random Mathematical Quotation";
BlogDataService.SaveEntry(entry);
}
}
}
| |
// Copyright 2015, 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.
// Author: Anash P. Oommen
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.Util.v201505;
using Google.Api.Ads.Dfp.v201505;
using System;
namespace Google.Api.Ads.Dfp.Examples.CSharp.v201505 {
/// <summary>
/// This code example creates new line items. To determine which line items
/// exist, run GetAllLineItems.cs. To determine which orders exist, run
/// GetAllOrders.cs. To determine which placements exist, run
/// GetAllPlacements.cs. To determine the IDs for locations, run
/// GetGeoTargets.cs
///
/// Tags: LineItemService.createLineItems
/// </summary>
class CreateLineItems : SampleBase {
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description {
get {
return "This code example creates new line items. To determine which line items " +
"exist, run GetAllLineItems.cs. To determine which orders exist, run GetAllOrders.cs" +
". To determine which placements exist, run GetAllPlacements.cs. To determine the " +
"IDs for locations, run GetGeoTargets.cs.";
}
}
/// <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) {
SampleBase codeExample = new CreateLineItems();
Console.WriteLine(codeExample.Description);
codeExample.Run(new DfpUser());
}
/// <summary>
/// Run the code examples.
/// </summary>
/// <param name="user">The DFP user object running the code examples.</param>
public override void Run(DfpUser user) {
// Get the LineItemService.
LineItemService lineItemService =
(LineItemService) user.GetService(DfpService.v201505.LineItemService);
// Set the order that all created line items will belong to and the
// placement ID to target.
long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));
long[] targetPlacementIds = new long[] {long.Parse(_T("INSERT_PLACEMENT_ID_HERE"))};
// Create inventory targeting.
InventoryTargeting inventoryTargeting = new InventoryTargeting();
inventoryTargeting.targetedPlacementIds = targetPlacementIds;
// Create geographical targeting.
GeoTargeting geoTargeting = new GeoTargeting();
// Include the US and Quebec, Canada.
Location countryLocation = new Location();
countryLocation.id = 2840L;
Location regionLocation = new Location();
regionLocation.id = 20123L;
geoTargeting.targetedLocations = new Location[] {countryLocation, regionLocation};
Location postalCodeLocation = new Location();
postalCodeLocation.id = 9000093;
// Exclude Chicago and the New York metro area.
Location cityLocation = new Location();
cityLocation.id = 1016367L;
Location metroLocation = new Location();
metroLocation.id = 200501L;
geoTargeting.excludedLocations = new Location[] {cityLocation, metroLocation};
// Exclude domains that are not under the network's control.
UserDomainTargeting userDomainTargeting = new UserDomainTargeting();
userDomainTargeting.domains = new String[] {"usa.gov"};
userDomainTargeting.targeted = false;
// Create day-part targeting.
DayPartTargeting dayPartTargeting = new DayPartTargeting();
dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;
// Target only the weekend in the browser's timezone.
DayPart saturdayDayPart = new DayPart();
saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201505.DayOfWeek.SATURDAY;
saturdayDayPart.startTime = new TimeOfDay();
saturdayDayPart.startTime.hour = 0;
saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;
saturdayDayPart.endTime = new TimeOfDay();
saturdayDayPart.endTime.hour = 24;
saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;
DayPart sundayDayPart = new DayPart();
sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201505.DayOfWeek.SUNDAY;
sundayDayPart.startTime = new TimeOfDay();
sundayDayPart.startTime.hour = 0;
sundayDayPart.startTime.minute = MinuteOfHour.ZERO;
sundayDayPart.endTime = new TimeOfDay();
sundayDayPart.endTime.hour = 24;
sundayDayPart.endTime.minute = MinuteOfHour.ZERO;
dayPartTargeting.dayParts = new DayPart[] {saturdayDayPart, sundayDayPart};
// Create technology targeting.
TechnologyTargeting technologyTargeting = new TechnologyTargeting();
// Create browser targeting.
BrowserTargeting browserTargeting = new BrowserTargeting();
browserTargeting.isTargeted = true;
// Target just the Chrome browser.
Technology browserTechnology = new Technology();
browserTechnology.id = 500072L;
browserTargeting.browsers = new Technology[] {browserTechnology};
technologyTargeting.browserTargeting = browserTargeting;
// Create an array to store local line item objects.
LineItem[] lineItems = new LineItem[5];
for (int i = 0; i < 5; i++) {
LineItem lineItem = new LineItem();
lineItem.name = "Line item #" + i;
lineItem.orderId = orderId;
lineItem.targeting = new Targeting();
lineItem.targeting.inventoryTargeting = inventoryTargeting;
lineItem.targeting.geoTargeting = geoTargeting;
lineItem.targeting.userDomainTargeting = userDomainTargeting;
lineItem.targeting.dayPartTargeting = dayPartTargeting;
lineItem.targeting.technologyTargeting = technologyTargeting;
lineItem.lineItemType = LineItemType.STANDARD;
lineItem.allowOverbook = true;
// Set the creative rotation type to even.
lineItem.creativeRotationType = CreativeRotationType.EVEN;
// Set the size of creatives that can be associated with this line item.
Size size = new Size();
size.width = 300;
size.height = 250;
size.isAspectRatio = false;
// Create the creative placeholder.
CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
creativePlaceholder.size = size;
lineItem.creativePlaceholders = new CreativePlaceholder[] {creativePlaceholder};
// Set the line item to run for one month.
lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.endDateTime =
DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1), "America/New_York");
// Set the cost per unit to $2.
lineItem.costType = CostType.CPM;
lineItem.costPerUnit = new Money();
lineItem.costPerUnit.currencyCode = "USD";
lineItem.costPerUnit.microAmount = 2000000L;
// Set the number of units bought to 500,000 so that the budget is
// $1,000.
Goal goal = new Goal();
goal.goalType = GoalType.LIFETIME;
goal.unitType = UnitType.IMPRESSIONS;
goal.units = 500000L;
lineItem.primaryGoal = goal;
lineItems[i] = lineItem;
}
try {
// Create the line items on the server.
lineItems = lineItemService.createLineItems(lineItems);
if (lineItems != null) {
foreach (LineItem lineItem in lineItems) {
Console.WriteLine("A line item with ID \"{0}\", belonging to order ID \"{1}\", and" +
" named \"{2}\" was created.", lineItem.id, lineItem.orderId, lineItem.name);
}
} else {
Console.WriteLine("No line items created.");
}
} catch (Exception ex) {
Console.WriteLine("Failed to create line items. Exception says \"{0}\"",
ex.Message);
}
}
}
}
| |
/*
| 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.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ESRI.ArcLogistics.Geometry
{
/// <summary>
/// Class that helps to convert compact geometry string to array of points.
/// </summary>
public class CompactGeometryConverter
{
#region public methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Converts compact geometry string to array of points.
/// </summary>
/// <param name="geometry">Compact geometry string.</param>
/// <param name="points">Output parameter that contains array of points if conversion succeeded.</param>
/// <returns>Returns <c>true</c> if conversion succeeded or <c>false</c> otherwise.</returns>
public static bool Convert(string geometry, out Point[] points)
{
Debug.Assert(geometry != null);
points = null;
List<Point> ptList = new List<Point>();
int? flags = 0;
int indexXY = 0;
double multBy_XY = 0;
var firstElement = CompactGeometryStringWorker.ReadInt(geometry, ref indexXY);
// If we couldn't read first element - return false.
if (firstElement == null)
return false;
// Check that string is in post 9.3 format.
if (firstElement == POST_93_FORMAT)
{
// Read version and check that it is current.
var version = CompactGeometryStringWorker.ReadInt(geometry, ref indexXY);
if(version != CURRENT_VERSION)
return false;
// Flags showing what additional info string contains.
flags = CompactGeometryStringWorker.ReadInt(geometry, ref indexXY);
// Read XY multiplier.
var succeeded = CompactGeometryStringWorker.ReadDouble(geometry, ref indexXY, ref multBy_XY);
if (!succeeded)
return false;
}
// If it isnt - first element is XY multiplier.
else
multBy_XY = (double)firstElement;
int nLength;
int index_M = 0;
int index_Z = 0;
double multBy_M = 0;
// If geometry has no additional info.
if (flags == 0)
nLength = geometry.Length;
// If it has - read info about Z and M coordinates.
else
{
nLength = geometry.IndexOf(CompactGeometryStringWorker.AdditionalPartsSeparator);
// Check that compressed geometry has Z coordinate.
if ((flags & FLAG_HAS_Z) == FLAG_HAS_Z)
{
index_Z = nLength + 1;
CompactGeometryStringWorker.ReadInt(geometry, ref index_Z);
}
// Check that it has M coordinate.
if ((flags & FLAG_HAS_M) == FLAG_HAS_M)
{
index_M = geometry.IndexOf(
CompactGeometryStringWorker.AdditionalPartsSeparator, index_Z) + 1;
// Read M multiplier.
var succeded = CompactGeometryStringWorker.ReadDouble(geometry, ref index_M, ref multBy_M);
if (!succeded)
return false;
}
}
// Create readers for coordinates.
var xReader = new CoordinateReader(geometry, multBy_XY);
var yReader = new CoordinateReader(geometry, multBy_XY);
var mReader = new CoordinateReader(geometry, multBy_M);
while (indexXY != nLength)
{
// Read X and Y coordinates.
double xCoordinate = 0;
double yCoordinate = 0;
if (!xReader.ReadNextCoordinate(ref indexXY, ref xCoordinate) ||
!yReader.ReadNextCoordinate(ref indexXY, ref yCoordinate))
return false;
// If it has M coordinate.
if ((flags & FLAG_HAS_M) == FLAG_HAS_M)
{
// Read M coordinate.
double mCoordinate = 0;
if(! mReader.ReadNextCoordinate(ref index_M, ref mCoordinate))
return false;
// Add point with M coordinate.
ptList.Add(new Point(xCoordinate, yCoordinate, mCoordinate));
}
// If point has no M coordinate - add default point.
else
ptList.Add(new Point(xCoordinate, yCoordinate));
}
points = ptList.ToArray();
return true;
}
/// <summary>
/// Converts the specified collection of points into compact geometry.
/// </summary>
/// <param name="points">Collection of points to be converted to a compact geometry.</param>
/// <returns>A string containing specified points in a compact geometry format.</returns>
public static string Convert(IEnumerable<Point> points)
{
// Compute XY multiplier.
var maxValue = points.Max(point => Math.Max(Math.Abs(point.X), Math.Abs(point.Y)));
var multByXY = maxValue == 0.0 ? 1 : (int)(Int32.MaxValue / maxValue);
var result = new StringBuilder();
// Append info about geometry format.
CompactGeometryStringWorker.AppendValue(POST_93_FORMAT, result);
CompactGeometryStringWorker.AppendValue(CURRENT_VERSION, result);
CompactGeometryStringWorker.AppendValue(FLAG_HAS_M, result);
// Append XY multiplier.
CompactGeometryStringWorker.AppendValue(multByXY, result);
var lastX = default(int);
var lastY = default(int);
var lastM = default(int);
foreach (var point in points)
{
lastX = CompactGeometryStringWorker.AppendValue(point.X, lastX, multByXY, result);
lastY = CompactGeometryStringWorker.AppendValue(point.Y, lastY, multByXY, result);
}
// Write separtor to string.
result.Append(CompactGeometryStringWorker.AdditionalPartsSeparator);
// Calculate M multiplier.
var multByM = (int)(1 / M_PRESICION);
// Write M multiplier.
CompactGeometryStringWorker.AppendValue(multByM, result);
foreach (var point in points)
lastM = CompactGeometryStringWorker.AppendValue(point.M, lastM, multByM, result);
return result.ToString();
}
#endregion public methods
#region private constants
/// <summary>
/// Value showing that compressed geom contains additional information.
/// </summary>
private const int POST_93_FORMAT = 0;
/// <summary>
/// Compressed geometry version.
/// </summary>
private const int CURRENT_VERSION = 1;
/// <summary>
/// Value showing that flag contains M.
/// </summary>
private const int FLAG_HAS_M = 2;
/// <summary>
/// Value showing that flag contains Z.
/// </summary>
private const int FLAG_HAS_Z = 1;
/// <summary>
/// Presicion for converting M values.
/// </summary>
private const double M_PRESICION = .00001;
#endregion
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Activities
{
using System.Activities;
using System.Activities.Debugger;
using System.Activities.DynamicUpdate;
using System.Activities.XamlIntegration;
using System.Activities.Statements;
using System.Activities.Validation;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Reflection;
using System.Runtime;
using System.Runtime.Collections;
using System.ServiceModel.Activities.Description;
using System.ServiceModel.Description;
using System.ServiceModel.XamlIntegration;
using System.Text;
using System.Windows.Markup;
using System.Xaml;
using System.Xml;
using System.Xml.Linq;
[ContentProperty("Body")]
public class WorkflowService : IDebuggableWorkflowTree
{
Collection<Endpoint> endpoints;
Collection<Type> implementedContracts;
NullableKeyDictionary<WorkflowIdentity, DynamicUpdateMap> updateMaps;
IDictionary<XName, ContractDescription> cachedInferredContracts;
IDictionary<XName, Collection<CorrelationQuery>> correlationQueryByContract;
IDictionary<ContractAndOperationNameTuple, OperationInfo> keyedByNameOperationInfo;
IList<Receive> knownServiceActivities;
HashSet<ReceiveAndReplyTuple> receiveAndReplyPairs;
ServiceDescription serviceDescription;
XName inferedServiceName;
public WorkflowService()
{
}
[DefaultValue(null)]
public Activity Body
{
get;
set;
}
[Fx.Tag.KnownXamlExternal]
[DefaultValue(null)]
[TypeConverter(typeof(ServiceXNameTypeConverter))]
public XName Name
{
get;
set;
}
[DefaultValue(null)]
public string ConfigurationName
{
get;
set;
}
[DefaultValue(false)]
public bool AllowBufferedReceive
{
get;
set;
}
public Collection<Endpoint> Endpoints
{
get
{
if (this.endpoints == null)
{
this.endpoints = new Collection<Endpoint>();
}
return this.endpoints;
}
}
[Fx.Tag.KnownXamlExternal]
[DefaultValue(null)]
public WorkflowIdentity DefinitionIdentity
{
get;
set;
}
public Collection<Type> ImplementedContracts
{
get
{
if (this.implementedContracts == null)
{
this.implementedContracts = new Collection<Type>();
}
return this.implementedContracts;
}
}
public IDictionary<WorkflowIdentity, DynamicUpdateMap> UpdateMaps
{
get
{
if (this.updateMaps == null)
{
this.updateMaps = new NullableKeyDictionary<WorkflowIdentity, DynamicUpdateMap>();
}
return this.updateMaps;
}
}
internal bool HasImplementedContracts
{
get
{
return this.implementedContracts != null && this.implementedContracts.Count > 0;
}
}
[DefaultValue(null)]
internal Dictionary<OperationIdentifier, OperationProperty> OperationProperties
{
get;
set;
}
IDictionary<ContractAndOperationNameTuple, OperationInfo> OperationsInfo
{
get
{
if (this.keyedByNameOperationInfo == null)
{
GetContractDescriptions();
}
return this.keyedByNameOperationInfo;
}
}
internal XName InternalName
{
get
{
if (this.Name != null)
{
return this.Name;
}
else
{
if (this.inferedServiceName == null)
{
Fx.Assert(this.Body != null, "Body cannot be null!");
if (this.Body.DisplayName.Length == 0)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.MissingDisplayNameInRootActivity));
}
this.inferedServiceName = XName.Get(XmlConvert.EncodeLocalName(this.Body.DisplayName));
}
return this.inferedServiceName;
}
}
}
internal IDictionary<XName, Collection<CorrelationQuery>> CorrelationQueries
{
get
{
Fx.Assert(this.cachedInferredContracts != null, "Must infer contract first!");
return this.correlationQueryByContract;
}
}
public Activity GetWorkflowRoot()
{
return this.Body;
}
internal ServiceDescription GetEmptyServiceDescription()
{
if (this.serviceDescription == null)
{
WalkActivityTree();
ServiceDescription result = new ServiceDescription
{
Name = this.InternalName.LocalName,
Namespace = string.IsNullOrEmpty(this.InternalName.NamespaceName) ? NamingHelper.DefaultNamespace : this.InternalName.NamespaceName,
ConfigurationName = this.ConfigurationName ?? this.InternalName.LocalName
};
this.serviceDescription = result;
}
return this.serviceDescription;
}
static void AddAdditionalConstraint(ValidationSettings workflowServiceSettings, Type constraintType, Constraint constraint)
{
IList<Constraint> constraintList;
if (workflowServiceSettings.AdditionalConstraints.TryGetValue(constraintType, out constraintList))
{
constraintList.Add(constraint);
}
else
{
constraintList = new List<Constraint>(1)
{
constraint,
};
workflowServiceSettings.AdditionalConstraints.Add(constraintType, constraintList);
}
}
public ValidationResults Validate(ValidationSettings settings)
{
Collection<ValidationError> errors = new Collection<ValidationError>();
ValidationSettings workflowServiceSettings = this.CopyValidationSettions(settings);
if (this.HasImplementedContracts)
{
this.OperationProperties = CreateOperationProperties(errors);
// Add additional constraints
AddAdditionalConstraint(workflowServiceSettings, typeof(Receive), GetContractFirstValidationReceiveConstraints());
AddAdditionalConstraint(workflowServiceSettings, typeof(SendReply), GetContractFirstValidationSendReplyConstraints());
}
ValidationResults results = null;
if (this.Body != null)
{
results = ActivityValidationServices.Validate(this.Body, workflowServiceSettings);
if (!this.HasImplementedContracts)
{
return results;
}
else
{
// If the user specified implemented contract, then we need to add the errors into the error collection
foreach (ValidationError validationError in results.Errors)
{
errors.Add(validationError);
}
foreach (ValidationError validationWarning in results.Warnings)
{
errors.Add(validationWarning);
}
}
}
if (this.HasImplementedContracts)
{
this.AfterValidation(errors);
}
return new ValidationResults(errors);
}
bool IsContractValid(ContractDescription contractDescription, Collection<ValidationError> validationError)
{
bool isValid = true;
if (contractDescription.IsDuplex())
{
validationError.Add(new ValidationError(SR.DuplexContractsNotSupported));
isValid = false;
}
return isValid;
}
ValidationSettings CopyValidationSettions(ValidationSettings source)
{
if ( source == null )
{
return new ValidationSettings();
}
ValidationSettings clonedSettings = new ValidationSettings
{
OnlyUseAdditionalConstraints = source.OnlyUseAdditionalConstraints,
SingleLevel = source.SingleLevel,
SkipValidatingRootConfiguration = source.SkipValidatingRootConfiguration,
PrepareForRuntime = source.PrepareForRuntime,
Environment = source.Environment,
};
foreach (KeyValuePair<Type, IList<Constraint>> constrants in source.AdditionalConstraints)
{
if (constrants.Key != null && constrants.Value != null)
{
clonedSettings.AdditionalConstraints.Add(constrants.Key, new List<Constraint>(constrants.Value));
}
}
return clonedSettings;
}
void AfterValidation(Collection<ValidationError> errors)
{
if (this.HasImplementedContracts)
{
Dictionary<OperationIdentifier, OperationProperty> operationProperties = this.OperationProperties;
if (operationProperties != null)
{
foreach (OperationProperty property in operationProperties.Values)
{
Fx.Assert(property.Operation != null, "OperationProperty.Operation should not be null!");
if (property.ImplementingReceives.Count < 1)
{
errors.Add(new ValidationError(SR.OperationIsNotImplemented(property.Operation.Name, property.Operation.DeclaringContract.Name), true));
}
else if (!property.Operation.IsOneWay)
{
foreach (Receive recv in property.ImplementingReceives)
{
if (!property.ImplementingSendRepliesRequests.Contains(recv))
{
// passing the receive activity without a matching SendReply as the SourceDetail
errors.Add(new ValidationError(SR.TwoWayIsImplementedAsOneWay(property.Operation.Name, property.Operation.DeclaringContract.Name), true, string.Empty, recv));
}
}
}
}
}
}
}
Dictionary<OperationIdentifier, OperationProperty> CreateOperationProperties(Collection<ValidationError> validationErrors)
{
Dictionary<OperationIdentifier, OperationProperty> operationProperties = null;
if (this.HasImplementedContracts)
{
operationProperties = new Dictionary<OperationIdentifier, OperationProperty>();
foreach (Type contractType in this.ImplementedContracts)
{
ContractDescription contract = null;
try
{
contract = ContractDescription.GetContract(contractType);
if (contract != null)
{
if (this.IsContractValid(contract, validationErrors))
{
foreach (OperationDescription operation in contract.Operations)
{
OperationIdentifier id = new OperationIdentifier(operation.DeclaringContract.Name, operation.DeclaringContract.Namespace, operation.Name);
if (operationProperties.ContainsKey(id))
{
validationErrors.Add(new ValidationError(SR.DuplicatedContract(operation.DeclaringContract.Name, operation.Name), true));
}
else
{
operationProperties.Add(id, new OperationProperty(operation));
}
}
}
}
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
validationErrors.Add(new ValidationError(exception.Message));
}
}
}
return operationProperties;
}
public virtual IDictionary<XName, ContractDescription> GetContractDescriptions()
{
if (this.cachedInferredContracts == null)
{
WalkActivityTree();
Fx.Assert(this.knownServiceActivities != null && this.receiveAndReplyPairs != null, "Failed to walk the activity tree!");
this.correlationQueryByContract = new Dictionary<XName, Collection<CorrelationQuery>>();
// Contract inference
IDictionary<XName, ContractDescription> inferredContracts = new Dictionary<XName, ContractDescription>();
this.keyedByNameOperationInfo = new Dictionary<ContractAndOperationNameTuple, OperationInfo>();
foreach (Receive receive in this.knownServiceActivities)
{
XName contractXName = FixServiceContractName(receive.ServiceContractName);
ContractAndOperationNameTuple tuple = new ContractAndOperationNameTuple(contractXName, receive.OperationName);
OperationInfo operationInfo;
if (this.keyedByNameOperationInfo.TryGetValue(tuple, out operationInfo))
{
// All Receives with same ServiceContractName and OperationName need to be validated
ContractValidationHelper.ValidateReceiveWithReceive(receive, operationInfo.Receive);
}
else
{
// Note that activities in keyedByNameOperationInfo are keyed by
// ServiceContractName and OperationName tuple. So we won't run into the case where
// two opertions have the same OperationName.
ContractDescription contract;
if (!inferredContracts.TryGetValue(contractXName, out contract))
{
// Infer Name, Namespace
contract = new ContractDescription(contractXName.LocalName, contractXName.NamespaceName);
// We use ServiceContractName.LocalName to bind contract with config
contract.ConfigurationName = contractXName.LocalName;
// We do NOT infer ContractDescription.ProtectionLevel
inferredContracts.Add(contractXName, contract);
}
OperationDescription operation = ContractInferenceHelper.CreateOperationDescription(receive, contract);
contract.Operations.Add(operation);
operationInfo = new OperationInfo(receive, operation);
this.keyedByNameOperationInfo.Add(tuple, operationInfo);
}
CorrectOutMessageForOperationWithFault(receive, operationInfo);
ContractInferenceHelper.UpdateIsOneWayFlag(receive, operationInfo.OperationDescription);
// FaultTypes and KnownTypes need to be collected from all Receive activities
ContractInferenceHelper.AddFaultDescription(receive, operationInfo.OperationDescription);
ContractInferenceHelper.AddKnownTypesToOperation(receive, operationInfo.OperationDescription);
// WorkflowFormatterBehavior should have reference to all the Receive activities
ContractInferenceHelper.AddReceiveToFormatterBehavior(receive, operationInfo.OperationDescription);
Collection<CorrelationQuery> correlationQueries = null;
// Collect CorrelationQuery from Receive
if (receive.HasCorrelatesOn || receive.HasCorrelationInitializers)
{
MessageQuerySet select = receive.HasCorrelatesOn ? receive.CorrelatesOn : null;
CorrelationQuery correlationQuery = ContractInferenceHelper.CreateServerCorrelationQuery(select,
receive.CorrelationInitializers, operationInfo.OperationDescription, false);
CollectCorrelationQuery(ref correlationQueries, contractXName, correlationQuery);
}
// Find all known Receive-Reply pair in the activity tree. Remove them from this.receiveAndReplyPairs
// Also collect CorrelationQuery from following replies
if (receive.HasReply)
{
foreach (SendReply reply in receive.FollowingReplies)
{
ReceiveAndReplyTuple pair = new ReceiveAndReplyTuple(receive, reply);
this.receiveAndReplyPairs.Remove(pair);
CollectCorrelationQueryFromReply(ref correlationQueries, contractXName,
reply, operationInfo.OperationDescription);
reply.SetContractName(contractXName);
}
}
if (receive.HasFault)
{
foreach (SendReply fault in receive.FollowingFaults)
{
ReceiveAndReplyTuple pair = new ReceiveAndReplyTuple(receive, fault);
this.receiveAndReplyPairs.Remove(pair);
CollectCorrelationQueryFromReply(ref correlationQueries, contractXName,
fault, operationInfo.OperationDescription);
}
}
// Have to do this here otherwise message/fault formatters
// non-WorkflowServiceHost case won't be set. Cannot do this
// during CacheMetadata time because activity order in which
// CacheMetadata calls are made doesn't yield the correct result.
// Not possible to do it at runtime either because the ToReply and
// ToRequest activities that use the formatters do not have access
// to related OperationDescription. Note: non-WorkflowServiceHosts will
// need to call GetContractDescriptions() to get these default formatters
// wired up.
receive.SetDefaultFormatters(operationInfo.OperationDescription);
}
// Check for Receive referenced by SendReply but no longer in the activity tree
if (this.receiveAndReplyPairs.Count != 0)
{
throw FxTrace.Exception.AsError(new ValidationException(SR.DanglingReceive));
}
// Print out tracing information
if (TD.InferredContractDescriptionIsEnabled())
{
foreach (ContractDescription contract in inferredContracts.Values)
{
TD.InferredContractDescription(contract.Name, contract.Namespace);
if (TD.InferredOperationDescriptionIsEnabled())
{
foreach (OperationDescription operation in contract.Operations)
{
TD.InferredOperationDescription(operation.Name, contract.Name, operation.IsOneWay.ToString());
}
}
}
}
this.cachedInferredContracts = inferredContracts;
}
return this.cachedInferredContracts;
}
internal void ValidateForVersioning(WorkflowService baseWorkflowService)
{
if (this.knownServiceActivities == null)
{
WalkActivityTree();
}
foreach (Receive receive in this.knownServiceActivities)
{
XName contractXName = FixServiceContractName(receive.ServiceContractName);
ContractAndOperationNameTuple tuple = new ContractAndOperationNameTuple(contractXName, receive.OperationName);
OperationInfo operationInfo;
if (baseWorkflowService.OperationsInfo.TryGetValue(tuple, out operationInfo))
{
// All Receives with same ServiceContractName and OperationName need to be validated
ContractValidationHelper.ValidateReceiveWithReceive(receive, operationInfo.Receive);
ContractInferenceHelper.AddReceiveToFormatterBehavior(receive, operationInfo.OperationDescription);
ContractInferenceHelper.UpdateIsOneWayFlag(receive, operationInfo.OperationDescription);
}
else
{
throw FxTrace.Exception.AsError(new ValidationException(SR.OperationNotFound(contractXName, receive.OperationName)));
}
}
}
internal void DetachFromVersioning(WorkflowService baseWorkflowService)
{
if (this.knownServiceActivities == null)
{
return;
}
foreach (Receive receive in this.knownServiceActivities)
{
XName contractXName = FixServiceContractName(receive.ServiceContractName);
ContractAndOperationNameTuple tuple = new ContractAndOperationNameTuple(contractXName, receive.OperationName);
OperationInfo operationInfo;
if (baseWorkflowService.OperationsInfo.TryGetValue(tuple, out operationInfo))
{
ContractInferenceHelper.RemoveReceiveFromFormatterBehavior(receive, operationInfo.OperationDescription);
}
}
}
void WalkActivityTree()
{
if (this.knownServiceActivities != null)
{
// We return if we have already walked the activity tree
return;
}
if (this.Body == null)
{
throw FxTrace.Exception.AsError(new ValidationException(SR.MissingBodyInWorkflowService));
}
// Validate the activity tree
ValidationResults validationResults = null;
StringBuilder exceptionMessage = new StringBuilder();
bool doesErrorExist = false;
try
{
if (this.HasImplementedContracts)
{
validationResults = this.Validate(new ValidationSettings() { PrepareForRuntime = true, });
}
else
{
WorkflowInspectionServices.CacheMetadata(this.Body);
}
}
catch (InvalidWorkflowException e)
{
doesErrorExist = true;
exceptionMessage.AppendLine(e.Message);
}
if (validationResults != null)
{
if (validationResults.Errors != null && validationResults.Errors.Count > 0)
{
doesErrorExist = true;
foreach (ValidationError error in validationResults.Errors)
{
exceptionMessage.AppendLine(error.Message);
}
}
}
if (doesErrorExist)
{
throw FxTrace.Exception.AsError(new InvalidWorkflowException(exceptionMessage.ToString()));
}
this.knownServiceActivities = new List<Receive>();
this.receiveAndReplyPairs = new HashSet<ReceiveAndReplyTuple>();
// Now let us walk the tree here
Queue<QueueItem> activities = new Queue<QueueItem>();
// The root activity is never "in" a TransactedReceiveScope
activities.Enqueue(new QueueItem(this.Body, null, null));
while (activities.Count > 0)
{
QueueItem queueItem = activities.Dequeue();
Fx.Assert(queueItem != null, "Queue item cannot be null");
Activity activity = queueItem.Activity;
Fx.Assert(queueItem.Activity != null, "Queue item's Activity cannot be null");
Activity parentReceiveScope = queueItem.ParentReceiveScope;
Activity rootTransactedReceiveScope = queueItem.RootTransactedReceiveScope;
if (activity is Receive) // First, let's see if this is a Receive activity
{
Receive receive = (Receive)activity;
if (rootTransactedReceiveScope != null)
{
receive.InternalReceive.AdditionalData.IsInsideTransactedReceiveScope = true;
Fx.Assert(parentReceiveScope != null, "Internal error.. TransactedReceiveScope should be valid here");
if (IsFirstTransactedReceive(receive, parentReceiveScope, rootTransactedReceiveScope))
{
receive.InternalReceive.AdditionalData.IsFirstReceiveOfTransactedReceiveScopeTree = true;
}
}
this.knownServiceActivities.Add(receive);
}
else if (activity is SendReply) // Let's see if this is a SendReply
{
SendReply sendReply = (SendReply)activity;
Receive pairedReceive = sendReply.Request;
Fx.Assert(pairedReceive != null, "SendReply must point to a Receive!");
if (sendReply.InternalContent.IsFault)
{
pairedReceive.FollowingFaults.Add(sendReply);
}
else
{
if (pairedReceive.HasReply)
{
SendReply followingReply = pairedReceive.FollowingReplies[0];
ContractValidationHelper.ValidateSendReplyWithSendReply(followingReply, sendReply);
}
pairedReceive.FollowingReplies.Add(sendReply);
}
ReceiveAndReplyTuple tuple = new ReceiveAndReplyTuple(pairedReceive, sendReply);
this.receiveAndReplyPairs.Add(tuple);
}
// Enqueue child activities and delegates
if (activity is TransactedReceiveScope)
{
parentReceiveScope = activity;
if (rootTransactedReceiveScope == null)
{
rootTransactedReceiveScope = parentReceiveScope;
}
}
foreach (Activity childActivity in WorkflowInspectionServices.GetActivities(activity))
{
QueueItem queueData = new QueueItem(childActivity, parentReceiveScope, rootTransactedReceiveScope);
activities.Enqueue(queueData);
}
}
}
XName FixServiceContractName(XName serviceContractName)
{
// By default, we use WorkflowService.Name as ServiceContractName
XName contractXName = serviceContractName ?? this.InternalName;
ContractInferenceHelper.ProvideDefaultNamespace(ref contractXName);
return contractXName;
}
static void CorrectOutMessageForOperationWithFault(Receive receive, OperationInfo operationInfo)
{
Fx.Assert(receive != null && operationInfo != null, "Argument cannot be null!");
Receive prevReceive = operationInfo.Receive;
if (receive != prevReceive && receive.HasReply &&
!prevReceive.HasReply && prevReceive.HasFault)
{
ContractInferenceHelper.CorrectOutMessageForOperation(receive, operationInfo.OperationDescription);
operationInfo.Receive = receive;
}
}
void CollectCorrelationQuery(ref Collection<CorrelationQuery> queries, XName serviceContractName, CorrelationQuery correlationQuery)
{
Fx.Assert(serviceContractName != null, "Argument cannot be null!");
if (correlationQuery == null)
{
return;
}
if (queries == null && !this.correlationQueryByContract.TryGetValue(serviceContractName, out queries))
{
queries = new Collection<CorrelationQuery>();
this.correlationQueryByContract.Add(serviceContractName, queries);
}
queries.Add(correlationQuery);
}
void CollectCorrelationQueryFromReply(ref Collection<CorrelationQuery> correlationQueries, XName serviceContractName,
Activity reply, OperationDescription operation)
{
SendReply sendReply = reply as SendReply;
if (sendReply != null)
{
CorrelationQuery correlationQuery = ContractInferenceHelper.CreateServerCorrelationQuery(
null, sendReply.CorrelationInitializers, operation, true);
CollectCorrelationQuery(ref correlationQueries, serviceContractName, correlationQuery);
}
}
internal void ResetServiceDescription()
{
this.serviceDescription = null;
this.cachedInferredContracts = null;
}
bool IsFirstTransactedReceive(Receive request, Activity parent, Activity root)
{
Receive receive = null;
if (parent != null && root != null)
{
TransactedReceiveScope rootTRS = root as TransactedReceiveScope;
if (rootTRS != null)
{
receive = rootTRS.Request;
}
}
return (parent == root && receive == request);
}
Constraint GetContractFirstValidationReceiveConstraints()
{
DelegateInArgument<Receive> element = new DelegateInArgument<Receive> { Name = "ReceiveElement" };
DelegateInArgument<ValidationContext> validationContext = new DelegateInArgument<ValidationContext> { Name = "validationContext" };
Variable<IEnumerable<Activity>> parentChainVar = new Variable<IEnumerable<Activity>>("parentChainVar");
return new Constraint<Receive>
{
Body = new ActivityAction<Receive, ValidationContext>
{
Argument1 = element,
Argument2 = validationContext,
Handler = new Sequence
{
Variables = { parentChainVar },
Activities =
{
new GetParentChain { ValidationContext = validationContext, Result = parentChainVar },
new ValidateReceiveContract()
{
DisplayName = "ValidateReceiveContract",
ReceiveActivity = element,
WorkflowService = new InArgument<WorkflowService>()
{
Expression = new GetWorkflowSerivce(this)
},
ParentChain = parentChainVar,
}
}
}
}
};
}
Constraint GetContractFirstValidationSendReplyConstraints()
{
DelegateInArgument<SendReply> element = new DelegateInArgument<SendReply> { Name = "ReceiveElement" };
DelegateInArgument<ValidationContext> validationContext = new DelegateInArgument<ValidationContext> { Name = "validationContext" };
return new Constraint<SendReply>
{
Body = new ActivityAction<SendReply, ValidationContext>
{
Argument1 = element,
Argument2 = validationContext,
Handler = new Sequence
{
Activities =
{
new ValidateSendReplyContract()
{
DisplayName = "ValidateReceiveContract",
ReceiveActivity = element,
WorkflowSerivce = new InArgument<WorkflowService>()
{
Expression = new GetWorkflowSerivce(this)
},
ValidationContext = validationContext
}
}
}
}
};
}
struct ContractAndOperationNameTuple : IEquatable<ContractAndOperationNameTuple>
{
XName serviceContractXName;
string operationName;
public ContractAndOperationNameTuple(XName serviceContractXName, string operationName)
{
this.serviceContractXName = serviceContractXName;
this.operationName = operationName;
}
public bool Equals(ContractAndOperationNameTuple other)
{
return this.serviceContractXName == other.serviceContractXName && this.operationName == other.operationName;
}
public override int GetHashCode()
{
int hashCode = 0;
if (this.serviceContractXName != null)
{
hashCode ^= this.serviceContractXName.GetHashCode();
}
hashCode ^= this.operationName.GetHashCode();
return hashCode;
}
}
struct ReceiveAndReplyTuple : IEquatable<ReceiveAndReplyTuple>
{
Receive receive;
Activity reply;
public ReceiveAndReplyTuple(Receive receive, SendReply reply)
{
this.receive = receive;
this.reply = reply;
}
public bool Equals(ReceiveAndReplyTuple other)
{
return this.receive == other.receive && this.reply == other.reply;
}
public override int GetHashCode()
{
int hash = 0;
if (this.receive != null)
{
hash ^= this.receive.GetHashCode();
}
if (this.reply != null)
{
hash ^= this.reply.GetHashCode();
}
return hash;
}
}
class OperationInfo
{
Receive receive;
OperationDescription operationDescription;
public OperationInfo(Receive receive, OperationDescription operationDescription)
{
this.receive = receive;
this.operationDescription = operationDescription;
}
public Receive Receive
{
get { return this.receive; }
set { this.receive = value; }
}
public OperationDescription OperationDescription
{
get { return this.operationDescription; }
}
}
class QueueItem
{
Activity activity;
Activity parent;
Activity rootTransactedReceiveScope;
public QueueItem(Activity element, Activity parent, Activity root)
{
this.activity = element;
this.parent = parent;
this.rootTransactedReceiveScope = root;
}
public Activity Activity
{
get { return this.activity; }
}
public Activity ParentReceiveScope
{
get { return this.parent; }
}
public Activity RootTransactedReceiveScope
{
get { return this.rootTransactedReceiveScope; }
}
}
class GetWorkflowSerivce : CodeActivity<WorkflowService>
{
WorkflowService workflowService;
public GetWorkflowSerivce(WorkflowService serviceReference)
{
workflowService = serviceReference;
}
protected override void CacheMetadata(CodeActivityMetadata metadata)
{
RuntimeArgument resultArgument = new RuntimeArgument("Result", typeof(WorkflowService), ArgumentDirection.Out);
metadata.Bind(this.Result, resultArgument);
metadata.SetArgumentsCollection(
new Collection<RuntimeArgument>
{
resultArgument
});
}
protected override WorkflowService Execute(CodeActivityContext context)
{
return workflowService;
}
}
class ValidateReceiveContract : NativeActivity
{
public InArgument<Receive> ReceiveActivity
{
get;
set;
}
public InArgument<IEnumerable<Activity>> ParentChain
{
get;
set;
}
public InArgument<WorkflowService> WorkflowService
{
get;
set;
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
RuntimeArgument receiveActivity = new RuntimeArgument("ReceiveActivity", typeof(Receive), ArgumentDirection.In);
RuntimeArgument parentChain = new RuntimeArgument("ParentChain", typeof(IEnumerable<Activity>), ArgumentDirection.In);
RuntimeArgument operationProperties = new RuntimeArgument("OperationProperties", typeof(WorkflowService), ArgumentDirection.In);
if (this.ReceiveActivity == null)
{
this.ReceiveActivity = new InArgument<Receive>();
}
metadata.Bind(this.ReceiveActivity, receiveActivity);
if (this.ParentChain == null)
{
this.ParentChain = new InArgument<IEnumerable<Activity>>();
}
metadata.Bind(this.ParentChain, parentChain);
if (this.WorkflowService == null)
{
this.WorkflowService = new InArgument<WorkflowService>();
}
metadata.Bind(this.WorkflowService, operationProperties);
Collection<RuntimeArgument> arguments = new Collection<RuntimeArgument>
{
receiveActivity,
parentChain,
operationProperties,
};
metadata.SetArgumentsCollection(arguments);
}
protected override void Execute(NativeActivityContext context)
{
Receive receiveActivity = this.ReceiveActivity.Get(context);
Dictionary<OperationIdentifier, OperationProperty> operationProperties;
Fx.Assert(receiveActivity != null, "ValidateReceiveContract needs the receive activity to be present");
if (string.IsNullOrEmpty(receiveActivity.OperationName))
{
Constraint.AddValidationError(context, new ValidationError(SR.MissingOperationName(this.DisplayName)));
}
else
{
WorkflowService workflowService = this.WorkflowService.Get(context);
operationProperties = workflowService.OperationProperties;
XName serviceName = workflowService.FixServiceContractName(receiveActivity.ServiceContractName);
// We only do contract first validation if there are contract specified
if (operationProperties != null)
{
string contractName = serviceName.LocalName;
string contractNamespace = string.IsNullOrEmpty(serviceName.NamespaceName) ?
NamingHelper.DefaultNamespace : serviceName.NamespaceName;
string operationXmlName = NamingHelper.XmlName(receiveActivity.OperationName);
OperationProperty property;
OperationIdentifier operationId = new OperationIdentifier(contractName, contractNamespace, operationXmlName);
if (operationProperties.TryGetValue(operationId, out property))
{
property.ImplementingReceives.Add(receiveActivity);
Fx.Assert(property.Operation != null, "OperationProperty.Operation should not be null!");
ValidateContract(context, receiveActivity, property.Operation);
}
else
{
// It is OK to add a new contract, but we do not allow adding a new operation to a specified contract.
foreach (OperationIdentifier id in operationProperties.Keys)
{
if (contractName == id.ContractName && contractNamespace == id.ContractNamespace)
{
Constraint.AddValidationError(context, new ValidationError(SR.OperationDoesNotExistInContract(receiveActivity.OperationName, contractName, contractNamespace)));
break;
}
}
}
}
}
}
void ValidateTransactionBehavior(NativeActivityContext context, Receive receiveActivity, OperationDescription targetOperation)
{
TransactionFlowAttribute transactionFlowAttribute = targetOperation.Behaviors.Find<TransactionFlowAttribute>();
Activity parent = null;
// we know it's IList<Activity>
IList<Activity> parentChain = (IList<Activity>)this.ParentChain.Get(context);
if (parentChain.Count > 0)
{
parent = parentChain[0];
}
bool isInTransactedReceiveScope = false;
TransactedReceiveScope trs = parent as TransactedReceiveScope;
if (trs != null && trs.Request == receiveActivity)
{
isInTransactedReceiveScope = true;
}
if (transactionFlowAttribute != null)
{
if (transactionFlowAttribute.Transactions == TransactionFlowOption.Mandatory)
{
if (targetOperation.IsOneWay)
{
Constraint.AddValidationError(context, new ValidationError(SR.TargetContractCannotBeOneWayWithTransactionFlow(targetOperation.Name, targetOperation.DeclaringContract.Name)));
}
// Receive has to be in a transacted receive scope
if (!isInTransactedReceiveScope)
{
Constraint.AddValidationError(context, new ValidationError(SR.ReceiveIsNotInTRS(targetOperation.Name, targetOperation.DeclaringContract.Name)));
}
}
else if (transactionFlowAttribute.Transactions == TransactionFlowOption.NotAllowed)
{
if (isInTransactedReceiveScope)
{
Constraint.AddValidationError(context, new ValidationError(SR.ReceiveIsInTRSWhenTransactionFlowNotAllowed(targetOperation.Name, targetOperation.DeclaringContract.Name), true));
}
}
}
}
void ValidateContract(NativeActivityContext context, Receive receiveActivity, OperationDescription targetOperation)
{
SerializerOption targetSerializerOption = targetOperation.Behaviors.Contains(typeof(XmlSerializerOperationBehavior)) ?
SerializerOption.XmlSerializer : SerializerOption.DataContractSerializer;
if (receiveActivity.SerializerOption != targetSerializerOption)
{
Constraint.AddValidationError(context, new ValidationError(SR.PropertyMismatch(receiveActivity.SerializerOption.ToString(), "SerializerOption", targetSerializerOption.ToString(), targetOperation.DeclaringContract.Name, targetSerializerOption.ToString())));
}
if ((!targetOperation.HasProtectionLevel && receiveActivity.ProtectionLevel.HasValue && receiveActivity.ProtectionLevel != Net.Security.ProtectionLevel.None)
|| (receiveActivity.ProtectionLevel.HasValue && receiveActivity.ProtectionLevel.Value != targetOperation.ProtectionLevel)
|| (!receiveActivity.ProtectionLevel.HasValue && targetOperation.ProtectionLevel != Net.Security.ProtectionLevel.None))
{
string targetProtectionLevelString = targetOperation.HasProtectionLevel ?
targetOperation.ProtectionLevel.ToString() : SR.NotSpecified;
string receiveProtectionLevelString = receiveActivity.ProtectionLevel.HasValue ? receiveActivity.ProtectionLevel.ToString() : SR.NotSpecified;
Constraint.AddValidationError(context, new ValidationError(SR.PropertyMismatch(receiveProtectionLevelString, "ProtectionLevel", targetProtectionLevelString, targetOperation.Name, targetOperation.DeclaringContract.Name)));
}
// We validate that all known types on the contract be present on the activity.
// If activity contains more known types, we don't mind.
if (targetOperation.KnownTypes.Count > 0)
{
// We require that each Receive contains all the known types specified on the contract.
// Known type collections from multiple Receive activities with same contract name and operation name will NOT be merged.
// We expect the number of known types to be small, therefore we choose to use simple iterative search.
foreach (Type targetType in targetOperation.KnownTypes)
{
if (receiveActivity.KnownTypes == null || !receiveActivity.KnownTypes.Contains(targetType))
{
if (targetType != null && targetType != TypeHelper.VoidType)
{
Constraint.AddValidationError(context, new ValidationError(SR.MissingKnownTypes(targetType.FullName, targetOperation.Name, targetOperation.DeclaringContract.Name)));
}
}
}
}
this.ValidateTransactionBehavior(context, receiveActivity, targetOperation);
receiveActivity.InternalContent.ValidateContract(context, targetOperation, receiveActivity, MessageDirection.Input);
}
}
class ValidateSendReplyContract : NativeActivity
{
public InArgument<SendReply> ReceiveActivity
{
get;
set;
}
public InArgument<ValidationContext> ValidationContext
{
get;
set;
}
public InArgument<WorkflowService> WorkflowSerivce
{
get;
set;
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
RuntimeArgument receiveActivity = new RuntimeArgument("ReceiveActivity", typeof(SendReply), ArgumentDirection.In);
RuntimeArgument validationContext = new RuntimeArgument("ValidationContext", typeof(ValidationContext), ArgumentDirection.In);
RuntimeArgument operationProperties = new RuntimeArgument("OperationProperties", typeof(WorkflowService), ArgumentDirection.In);
if (this.ReceiveActivity == null)
{
this.ReceiveActivity = new InArgument<SendReply>();
}
metadata.Bind(this.ReceiveActivity, receiveActivity);
if (this.ValidationContext == null)
{
this.ValidationContext = new InArgument<ValidationContext>();
}
metadata.Bind(this.ValidationContext, validationContext);
if (this.WorkflowSerivce == null)
{
this.WorkflowSerivce = new InArgument<WorkflowService>();
}
metadata.Bind(this.WorkflowSerivce, operationProperties);
Collection<RuntimeArgument> arguments = new Collection<RuntimeArgument>
{
receiveActivity,
validationContext,
operationProperties
};
metadata.SetArgumentsCollection(arguments);
}
protected override void Execute(NativeActivityContext context)
{
SendReply sendReplyActivity = this.ReceiveActivity.Get(context);
Dictionary<OperationIdentifier, OperationProperty> operationProperties;
if (sendReplyActivity.Request != null)
{
if (sendReplyActivity.Request.ServiceContractName != null && sendReplyActivity.Request.OperationName != null)
{
WorkflowService workflowService = this.WorkflowSerivce.Get(context);
operationProperties = workflowService.OperationProperties;
if (operationProperties != null)
{
XName contractXName = sendReplyActivity.Request.ServiceContractName;
string contractName = contractXName.LocalName;
string contractNamespace = string.IsNullOrEmpty(contractXName.NamespaceName) ?
NamingHelper.DefaultNamespace : contractXName.NamespaceName;
string operationXmlName = NamingHelper.XmlName(sendReplyActivity.Request.OperationName);
OperationProperty property;
OperationIdentifier id = new OperationIdentifier(contractName, contractNamespace, operationXmlName);
if (operationProperties.TryGetValue(id, out property))
{
if (!property.Operation.IsOneWay)
{
property.ImplementingSendRepliesRequests.Add(sendReplyActivity.Request);
Fx.Assert(property.Operation != null, "OperationProperty.Operation should not be null!");
ValidateContract(context, sendReplyActivity, property.Operation);
}
else
{
Constraint.AddValidationError(context, new ValidationError(SR.OnewayContractIsImplementedAsTwoWay(property.Operation.Name, contractName)));
}
}
}
}
}
}
void ValidateContract(NativeActivityContext context, SendReply sendReply, OperationDescription targetOperation)
{
sendReply.InternalContent.ValidateContract(context, targetOperation, sendReply, MessageDirection.Output);
}
}
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using System.Collections.Generic;
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
using GSF.ASN1.Types;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Sequence(Name = "Unit_Control_instance", IsSet = false)]
public class Unit_Control_instance : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Unit_Control_instance));
private DefinitionChoiceType definition_;
private Identifier name_;
[ASN1Element(Name = "name", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public Identifier Name
{
get
{
return name_;
}
set
{
name_ = value;
}
}
[ASN1Element(Name = "definition", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public DefinitionChoiceType Definition
{
get
{
return definition_;
}
set
{
definition_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "definition")]
public class DefinitionChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DefinitionChoiceType));
private DetailsSequenceType details_;
private bool details_selected;
private ObjectIdentifier reference_;
private bool reference_selected;
[ASN1ObjectIdentifier(Name = "")]
[ASN1Element(Name = "reference", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public ObjectIdentifier Reference
{
get
{
return reference_;
}
set
{
selectReference(value);
}
}
[ASN1Element(Name = "details", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public DetailsSequenceType Details
{
get
{
return details_;
}
set
{
selectDetails(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isReferenceSelected()
{
return reference_selected;
}
public void selectReference(ObjectIdentifier val)
{
reference_ = val;
reference_selected = true;
details_selected = false;
}
public bool isDetailsSelected()
{
return details_selected;
}
public void selectDetails(DetailsSequenceType val)
{
details_ = val;
details_selected = true;
reference_selected = false;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "details", IsSet = false)]
public class DetailsSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DetailsSequenceType));
private Access_Control_List_instance accessControl_;
private ICollection<Domain_instance> domains_;
private ICollection<Program_Invocation_instance> programInvocations_;
[ASN1Element(Name = "accessControl", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)]
public Access_Control_List_instance AccessControl
{
get
{
return accessControl_;
}
set
{
accessControl_ = value;
}
}
[ASN1SequenceOf(Name = "domains", IsSetOf = false)]
[ASN1Element(Name = "domains", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)]
public ICollection<Domain_instance> Domains
{
get
{
return domains_;
}
set
{
domains_ = value;
}
}
[ASN1SequenceOf(Name = "programInvocations", IsSetOf = false)]
[ASN1Element(Name = "programInvocations", IsOptional = false, HasTag = true, Tag = 5, HasDefaultValue = false)]
public ICollection<Program_Invocation_instance> ProgramInvocations
{
get
{
return programInvocations_;
}
set
{
programInvocations_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
}
}
}
}
| |
#region Copyright
//
// Nini Configuration Project.
// Copyright (C) 2006 Brent R. Matzelle. All rights reserved.
//
// This software is published under the terms of the MIT X11 license, a copy of
// which has been included with this distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.IO;
using System.Xml;
using Nini.Config;
using NUnit.Framework;
namespace Nini.Test.Config
{
[TestFixture]
public class ConfigSourceBaseTests
{
#region Private variables
IConfig eventConfig = null;
IConfigSource eventSource = null;
int reloadedCount = 0;
int savedCount = 0;
string keyName = null;
string keyValue = null;
int keySetCount = 0;
int keyRemovedCount = 0;
#endregion
#region Unit tests
[Test]
public void Merge ()
{
StringWriter textWriter = new StringWriter ();
XmlTextWriter xmlWriter = NiniWriter (textWriter);
WriteSection (xmlWriter, "Pets");
WriteKey (xmlWriter, "cat", "muffy");
WriteKey (xmlWriter, "dog", "rover");
WriteKey (xmlWriter, "bird", "tweety");
xmlWriter.WriteEndDocument ();
StringReader reader = new StringReader (textWriter.ToString ());
XmlTextReader xmlReader = new XmlTextReader (reader);
XmlConfigSource xmlSource = new XmlConfigSource (xmlReader);
StringWriter writer = new StringWriter ();
writer.WriteLine ("[People]");
writer.WriteLine (" woman = Jane");
writer.WriteLine (" man = John");
IniConfigSource iniSource =
new IniConfigSource (new StringReader (writer.ToString ()));
xmlSource.Merge (iniSource);
IConfig config = xmlSource.Configs["Pets"];
Assert.AreEqual (3, config.GetKeys ().Length);
Assert.AreEqual ("muffy", config.Get ("cat"));
Assert.AreEqual ("rover", config.Get ("dog"));
config = xmlSource.Configs["People"];
Assert.AreEqual (2, config.GetKeys ().Length);
Assert.AreEqual ("Jane", config.Get ("woman"));
Assert.AreEqual ("John", config.Get ("man"));
}
[ExpectedException (typeof (ArgumentException))]
public void MergeItself ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[People]");
writer.WriteLine (" woman = Jane");
writer.WriteLine (" man = John");
IniConfigSource iniSource =
new IniConfigSource (new StringReader (writer.ToString ()));
iniSource.Merge (iniSource); // exception
}
[ExpectedException (typeof (ArgumentException))]
public void MergeExisting ()
{
StringWriter textWriter = new StringWriter ();
XmlTextWriter xmlWriter = NiniWriter (textWriter);
WriteSection (xmlWriter, "Pets");
WriteKey (xmlWriter, "cat", "muffy");
xmlWriter.WriteEndDocument ();
StringReader reader = new StringReader (xmlWriter.ToString ());
XmlTextReader xmlReader = new XmlTextReader (reader);
XmlConfigSource xmlSource = new XmlConfigSource (xmlReader);
StringWriter writer = new StringWriter ();
writer.WriteLine ("[People]");
writer.WriteLine (" woman = Jane");
IniConfigSource iniSource =
new IniConfigSource (new StringReader (writer.ToString ()));
xmlSource.Merge (iniSource);
xmlSource.Merge (iniSource); // exception
}
[Test]
public void AutoSave ()
{
string filePath = "AutoSaveTest.ini";
StreamWriter writer = new StreamWriter (filePath);
writer.WriteLine ("; some comment");
writer.WriteLine ("[new section]");
writer.WriteLine (" dog = Rover");
writer.WriteLine (""); // empty line
writer.WriteLine ("; a comment");
writer.WriteLine (" cat = Muffy");
writer.Close ();
IniConfigSource source = new IniConfigSource (filePath);
source.AutoSave = true;
IConfig config = source.Configs["new section"];
Assert.AreEqual ("Rover", config.Get ("dog"));
Assert.AreEqual ("Muffy", config.Get ("cat"));
config.Set ("dog", "Spots");
config.Set ("cat", "Misha");
Assert.AreEqual ("Spots", config.Get ("dog"));
Assert.AreEqual ("Misha", config.Get ("cat"));
source = new IniConfigSource (filePath);
config = source.Configs["new section"];
Assert.AreEqual ("Spots", config.Get ("dog"));
Assert.AreEqual ("Misha", config.Get ("cat"));
File.Delete (filePath);
}
[Test]
public void AddConfig ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" bool 1 = TrUe");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig newConfig = source.AddConfig ("NewConfig");
newConfig.Set ("NewKey", "NewValue");
newConfig.Set ("AnotherKey", "AnotherValue");
IConfig config = source.Configs["NewConfig"];
Assert.AreEqual (2, config.GetKeys ().Length);
Assert.AreEqual ("NewValue", config.Get ("NewKey"));
Assert.AreEqual ("AnotherValue", config.Get ("AnotherKey"));
}
[Test]
public void ExpandText ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Test]");
writer.WriteLine (" author = Brent");
writer.WriteLine (" domain = ${protocol}://nini.sf.net/");
writer.WriteLine (" apache = Apache implements ${protocol}");
writer.WriteLine (" developer = author of Nini: ${author} !");
writer.WriteLine (" love = We love the ${protocol} protocol");
writer.WriteLine (" combination = ${author} likes ${protocol}");
writer.WriteLine (" fact = fact: ${apache}");
writer.WriteLine (" protocol = http");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
source.ExpandKeyValues ();
IConfig config = source.Configs["Test"];
Assert.AreEqual ("http", config.Get ("protocol"));
Assert.AreEqual ("fact: Apache implements http", config.Get ("fact"));
Assert.AreEqual ("http://nini.sf.net/", config.Get ("domain"));
Assert.AreEqual ("Apache implements http", config.Get ("apache"));
Assert.AreEqual ("We love the http protocol", config.Get ("love"));
Assert.AreEqual ("author of Nini: Brent !", config.Get ("developer"));
Assert.AreEqual ("Brent likes http", config.Get ("combination"));
}
[Test]
public void ExpandTextOtherSection ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[web]");
writer.WriteLine (" apache = Apache implements ${protocol}");
writer.WriteLine (" protocol = http");
writer.WriteLine ("[server]");
writer.WriteLine (" domain = ${web|protocol}://nini.sf.net/");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
source.ExpandKeyValues ();
IConfig config = source.Configs["web"];
Assert.AreEqual ("http", config.Get ("protocol"));
Assert.AreEqual ("Apache implements http", config.Get ("apache"));
config = source.Configs["server"];
Assert.AreEqual ("http://nini.sf.net/", config.Get ("domain"));
}
[Test]
public void ExpandKeyValuesMerge ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[web]");
writer.WriteLine (" protocol = http");
writer.WriteLine ("[server]");
writer.WriteLine (" domain1 = ${web|protocol}://nini.sf.net/");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
StringWriter newWriter = new StringWriter ();
newWriter.WriteLine ("[web]");
newWriter.WriteLine (" apache = Apache implements ${protocol}");
newWriter.WriteLine ("[server]");
newWriter.WriteLine (" domain2 = ${web|protocol}://nini.sf.net/");
IniConfigSource newSource = new IniConfigSource
(new StringReader (newWriter.ToString ()));
source.Merge (newSource);
source.ExpandKeyValues ();
IConfig config = source.Configs["web"];
Assert.AreEqual ("http", config.Get ("protocol"));
Assert.AreEqual ("Apache implements http", config.Get ("apache"));
config = source.Configs["server"];
Assert.AreEqual ("http://nini.sf.net/", config.Get ("domain1"));
Assert.AreEqual ("http://nini.sf.net/", config.Get ("domain2"));
}
[Test]
public void AddNewConfigsAndKeys ()
{
// Add some new configs and keys here and test.
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Pets]");
writer.WriteLine (" cat = muffy");
writer.WriteLine (" dog = rover");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["Pets"];
Assert.AreEqual ("Pets", config.Name);
Assert.AreEqual (2, config.GetKeys ().Length);
IConfig newConfig = source.AddConfig ("NewTest");
newConfig.Set ("Author", "Brent");
newConfig.Set ("Birthday", "February 8th");
newConfig = source.AddConfig ("AnotherNew");
Assert.AreEqual (3, source.Configs.Count);
config = source.Configs["NewTest"];
Assert.IsNotNull (config);
Assert.AreEqual (2, config.GetKeys ().Length);
Assert.AreEqual ("February 8th", config.Get ("Birthday"));
Assert.AreEqual ("Brent", config.Get ("Author"));
}
[Test]
public void GetBooleanSpace ()
{
StringWriter textWriter = new StringWriter ();
XmlTextWriter xmlWriter = NiniWriter (textWriter);
WriteSection (xmlWriter, "Pets");
WriteKey (xmlWriter, "cat", "muffy");
WriteKey (xmlWriter, "dog", "rover");
WriteKey (xmlWriter, "Is Mammal", "False");
xmlWriter.WriteEndDocument ();
StringReader reader = new StringReader (textWriter.ToString ());
XmlTextReader xmlReader = new XmlTextReader (reader);
XmlConfigSource source = new XmlConfigSource (xmlReader);
source.Alias.AddAlias ("true", true);
source.Alias.AddAlias ("false", false);
Assert.IsFalse (source.Configs["Pets"].GetBoolean ("Is Mammal", false));
}
[Test]
public void RemoveNonExistingKey ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Pets]");
writer.WriteLine (" cat = muffy");
writer.WriteLine (" dog = rover");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
// This should not throw an exception
source.Configs["Pets"].Remove ("Not here");
}
[Test]
public void SavingWithNonStrings ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[Pets]");
writer.WriteLine (" cat = muffy");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
StringWriter newWriter = new StringWriter ();
IConfig config = source.Configs["Pets"];
Assert.AreEqual ("Pets", config.Name);
config.Set ("count", 1);
source.Save (newWriter);
}
[Test]
public void ConfigSourceEvents ()
{
string filePath = "EventTest.ini";
IniConfigSource source = new IniConfigSource ();
source.Saved += new EventHandler (this.source_saved);
source.Reloaded += new EventHandler (this.source_reloaded);
Assert.IsNull (eventConfig);
Assert.IsNull (eventSource);
IConfig config = source.AddConfig ("Test");
eventSource = null;
Assert.AreEqual (savedCount, 0);
source.Save (filePath);
Assert.AreEqual (savedCount, 1);
Assert.IsTrue (source == eventSource);
eventSource = null;
source.Save ();
Assert.AreEqual (savedCount, 2);
Assert.IsTrue (source == eventSource);
eventSource = null;
Assert.AreEqual (reloadedCount, 0);
source.Reload ();
Assert.AreEqual (reloadedCount, 1);
Assert.IsTrue (source == eventSource);
File.Delete (filePath);
}
[Test]
public void ConfigEvents ()
{
IConfigSource source = new IniConfigSource ();
IConfig config = source.AddConfig ("Test");
config.KeySet += new ConfigKeyEventHandler (this.config_keySet);
config.KeyRemoved += new ConfigKeyEventHandler (this.config_keyRemoved);
// Set key events
Assert.AreEqual (keySetCount, 0);
config.Set ("Test 1", "Value 1");
Assert.AreEqual (keySetCount, 1);
Assert.AreEqual ("Test 1", keyName);
Assert.AreEqual ("Value 1", keyValue);
config.Set ("Test 2", "Value 2");
Assert.AreEqual (keySetCount, 2);
Assert.AreEqual ("Test 2", keyName);
Assert.AreEqual ("Value 2", keyValue);
// Remove key events
Assert.AreEqual (keyRemovedCount, 0);
config.Remove ("Test 1");
Assert.AreEqual (keyRemovedCount, 1);
Assert.AreEqual ("Test 1", keyName);
Assert.AreEqual ("Value 1", keyValue);
config.Remove ("Test 2");
Assert.AreEqual (keyRemovedCount, 2);
Assert.AreEqual ("Test 2", keyName);
Assert.AreEqual ("Value 2", keyValue);
}
[Test]
public void ExpandKeyValuesConfigError ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[server]");
writer.WriteLine (" domain1 = ${web|protocol}://nini.sf.net/");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
try {
source.ExpandKeyValues ();
}
catch (Exception ex) {
Assert.AreEqual ("Expand config not found: web", ex.Message);
}
}
[Test]
public void ExpandKeyValuesKeyError ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[web]");
writer.WriteLine ("not-protocol = hah!");
writer.WriteLine ("[server]");
writer.WriteLine (" domain1 = ${web|protocol}://nini.sf.net/");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
try {
source.ExpandKeyValues ();
}
catch (Exception ex) {
Assert.AreEqual ("Expand key not found: protocol", ex.Message);
}
}
[Test]
public void ExpandKeyInfiniteRecursion ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[replace]");
writer.WriteLine ("test = ${test} broken");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
try {
source.ExpandKeyValues ();
}
catch (ArgumentException ex) {
Assert.AreEqual
("Key cannot have a expand value of itself: test", ex.Message);
}
}
[Test]
public void ConfigBaseGetErrors ()
{
StringWriter writer = new StringWriter ();
writer.WriteLine ("[web]");
writer.WriteLine ("; No keys");
IniConfigSource source = new IniConfigSource
(new StringReader (writer.ToString ()));
IConfig config = source.Configs["web"];
try {
config.GetInt ("not_there");
} catch (Exception ex) {
Assert.AreEqual ("Value not found: not_there", ex.Message);
}
try {
config.GetFloat ("not_there");
} catch (Exception ex) {
Assert.AreEqual ("Value not found: not_there", ex.Message);
}
try {
config.GetDouble ("not_there");
} catch (Exception ex) {
Assert.AreEqual ("Value not found: not_there", ex.Message);
}
try {
config.GetLong ("not_there");
} catch (Exception ex) {
Assert.AreEqual ("Value not found: not_there", ex.Message);
}
try {
config.GetBoolean ("not_there");
} catch (Exception ex) {
Assert.AreEqual ("Value not found: not_there", ex.Message);
}
}
[SetUp]
public void Setup ()
{
eventConfig = null;
eventSource = null;
savedCount = 0;
keySetCount = 0;
keyRemovedCount = 0;
}
#endregion
#region Private methods
private void source_saved (object sender, EventArgs e)
{
savedCount++;
eventSource = (IConfigSource)sender;
}
private void source_reloaded (object sender, EventArgs e)
{
reloadedCount++;
eventSource = (IConfigSource)sender;
}
private void config_keySet (object sender, ConfigKeyEventArgs e)
{
keySetCount++;
keyName = e.KeyName;
keyValue = e.KeyValue;
eventConfig = (IConfig)sender;
}
private void config_keyRemoved (object sender, ConfigKeyEventArgs e)
{
keyRemovedCount++;
keyName = e.KeyName;
keyValue = e.KeyValue;
eventConfig = (IConfig)sender;
}
private XmlTextWriter NiniWriter (TextWriter writer)
{
XmlTextWriter result = new XmlTextWriter (writer);
result.WriteStartDocument ();
result.WriteStartElement ("Nini");
return result;
}
private void WriteSection (XmlWriter writer, string sectionName)
{
writer.WriteStartElement ("Section");
writer.WriteAttributeString ("Name", sectionName);
}
private void WriteKey (XmlWriter writer, string key, string value)
{
writer.WriteStartElement ("Key");
writer.WriteAttributeString ("Name", key);
writer.WriteAttributeString ("Value", value);
writer.WriteEndElement ();
}
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Adxstudio.Xrm.Globalization;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Web.UI.WebControls;
using Adxstudio.Xrm.Web.UI.WebForms;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView;
using Microsoft.Xrm.Sdk;
namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView
{
/// <summary>
/// Template used when rendering a picklist (Option Set) field.
/// </summary>
public class PicklistControlTemplate : CellTemplate, ICustomFieldControlTemplate
{
/// <summary>
/// PicklistControlTemplate class intialization.
/// </summary>
/// <param name="field"></param>
/// <param name="metadata"></param>
/// <param name="validationGroup"></param>
/// <param name="bindings"></param>
public PicklistControlTemplate(CrmEntityFormViewField field, FormXmlCellMetadata metadata, string validationGroup,
IDictionary<string, CellBinding> bindings)
: base(metadata, validationGroup, bindings)
{
Field = field;
}
public override string CssClass
{
get
{
switch (Metadata.ControlStyle)
{
case WebFormMetadata.ControlStyle.MultipleChoiceMatrix:
return "picklist-matrix";
default:
return "picklist";
}
}
}
/// <summary>
/// Form field.
/// </summary>
public CrmEntityFormViewField Field { get; private set; }
private string ValidationText
{
get { return Metadata.ValidationText; }
}
private ValidatorDisplay ValidatorDisplay
{
get { return string.IsNullOrWhiteSpace(ValidationText) ? ValidatorDisplay.None : ValidatorDisplay.Dynamic; }
}
protected override bool LabelIsAssociated
{
get
{
return Metadata.ControlStyle != WebFormMetadata.ControlStyle.VerticalRadioButtonList &&
Metadata.ControlStyle != WebFormMetadata.ControlStyle.HorizontalRadioButtonList &&
Metadata.ControlStyle != WebFormMetadata.ControlStyle.MultipleChoiceMatrix;
}
}
protected override void InstantiateControlIn(Control container)
{
ListControl listControl;
switch (Metadata.ControlStyle)
{
case WebFormMetadata.ControlStyle.VerticalRadioButtonList:
listControl = new RadioButtonList
{
ID = ControlID,
CssClass = string.Join(" ", "picklist", "vertical", Metadata.CssClass),
ToolTip = Metadata.ToolTip,
RepeatDirection = RepeatDirection.Vertical,
RepeatLayout = RepeatLayout.Flow
};
break;
case WebFormMetadata.ControlStyle.HorizontalRadioButtonList:
listControl = new RadioButtonList
{
ID = ControlID,
CssClass = string.Join(" ", "picklist", "horizontal", Metadata.CssClass),
ToolTip = Metadata.ToolTip,
RepeatDirection = RepeatDirection.Horizontal,
RepeatLayout = RepeatLayout.Flow
};
break;
case WebFormMetadata.ControlStyle.MultipleChoiceMatrix:
listControl = new RadioButtonList
{
ID = ControlID,
CssClass = string.Join(" ", "picklist", "horizontal", "labels-top", Metadata.CssClass),
ToolTip = Metadata.ToolTip,
RepeatDirection = RepeatDirection.Horizontal,
RepeatLayout = RepeatLayout.Table,
TextAlign = TextAlign.Left
};
break;
default:
listControl = new DropDownList
{
ID = ControlID,
CssClass = string.Join(" ", "form-control", CssClass, Metadata.CssClass),
ToolTip = Metadata.ToolTip
};
break;
}
if (listControl is RadioButtonList)
{
listControl.Attributes.Add("role", "presentation");
}
listControl.Attributes.Add("onchange", "setIsDirty(this.id);");
container.Controls.Add(listControl);
PopulateListControl(listControl);
if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)
{
switch (Metadata.ControlStyle)
{
case WebFormMetadata.ControlStyle.VerticalRadioButtonList:
case WebFormMetadata.ControlStyle.HorizontalRadioButtonList:
case WebFormMetadata.ControlStyle.MultipleChoiceMatrix:
listControl.Attributes.Add("data-required", "true");
break;
default:
listControl.Attributes.Add("required", string.Empty);
break;
}
}
if (Metadata.ReadOnly)
{
AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(container, listControl);
}
else
{
Bindings[Metadata.DataFieldName] = new CellBinding
{
Get = () =>
{
int value;
return int.TryParse(listControl.SelectedValue, out value) ? new int?(value) : null;
},
Set = obj =>
{
var value = ((OptionSetValue)obj).Value;
var listItem = listControl.Items.FindByValue(value.ToString(CultureInfo.InvariantCulture));
if (listItem != null)
{
listControl.ClearSelection();
listItem.Selected = true;
}
}
};
}
}
protected override void InstantiateValidatorsIn(Control container)
{
if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)
{
container.Controls.Add(new RequiredFieldValidator
{
ID = string.Format("RequiredFieldValidator{0}", ControlID),
ControlToValidate = ControlID,
ValidationGroup = ValidationGroup,
Display = ValidatorDisplay,
ErrorMessage =
ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RequiredFieldValidationErrorMessage)
? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("required"))
? ResourceManager.GetString("Required_Field_Error").FormatWith(Metadata.Label)
: Metadata.Messages["required"].FormatWith(Metadata.Label)
: Metadata.RequiredFieldValidationErrorMessage)),
Text = Metadata.ValidationText,
});
}
this.InstantiateCustomValidatorsIn(container);
}
private void AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(Control container, ListControl listControl)
{
listControl.CssClass = string.Join(" ", "readonly", listControl.CssClass);
listControl.Attributes["disabled"] = "disabled";
listControl.Attributes["aria-disabled"] = "true";
var hiddenValue = new HiddenField
{
ID = "{0}_Value".FormatWith(ControlID),
Value = listControl.SelectedValue
};
container.Controls.Add(hiddenValue);
var hiddenSelectedIndex = new HiddenField
{
ID = "{0}_SelectedIndex".FormatWith(ControlID),
Value = listControl.SelectedIndex.ToString(CultureInfo.InvariantCulture)
};
container.Controls.Add(hiddenSelectedIndex);
RegisterClientSideDependencies(container);
Bindings[Metadata.DataFieldName] = new CellBinding
{
Get = () =>
{
int value;
return int.TryParse(hiddenValue.Value, out value) ? new int?(value) : null;
},
Set = obj =>
{
var value = ((OptionSetValue)obj).Value;
var listItem = listControl.Items.FindByValue(value.ToString(CultureInfo.InvariantCulture));
if (listItem != null)
{
listControl.ClearSelection();
listItem.Selected = true;
hiddenValue.Value = listItem.Value;
hiddenSelectedIndex.Value = listControl.SelectedIndex.ToString(CultureInfo.InvariantCulture);
}
}
};
}
private void PopulateListControl(ListControl listControl)
{
if (listControl.Items.Count > 0)
{
return;
}
if (listControl is DropDownList)
{
var empty = new ListItem(string.Empty, string.Empty);
empty.Attributes["label"] = " ";
listControl.Items.Add(empty);
}
var options = Metadata.RandomizeOptionSetValues ? Metadata.PicklistOptions.Randomize() : Metadata.PicklistOptions;
foreach (var option in options)
{
if (option == null || option.Value == null)
{
continue;
}
var label = option.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == Metadata.LanguageCode);
listControl.Items.Add(new ListItem
{
Value = option.Value.Value.ToString(CultureInfo.InvariantCulture),
Text = (listControl is RadioButtonList ? "<span class='sr-only'>" + Metadata.Label + " </span>" : string.Empty) +
(label == null ? option.Label.GetLocalizedLabelString() : label.Label)
});
}
if (!Metadata.IgnoreDefaultValue && Metadata.DefaultValue != null)
{
var value = Convert.ToInt32(Metadata.DefaultValue) == -1 ? string.Empty : Metadata.DefaultValue.ToString();
var listItem = listControl.Items.FindByValue(value);
if (listItem != null)
{
listControl.ClearSelection();
listItem.Selected = true;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.