context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
namespace Godot
{
public static class StringExtensions
{
private static int GetSliceCount(this string instance, string splitter)
{
if (string.IsNullOrEmpty(instance) || string.IsNullOrEmpty(splitter))
return 0;
int pos = 0;
int slices = 1;
while ((pos = instance.Find(splitter, pos, caseSensitive: true)) >= 0)
{
slices++;
pos += splitter.Length;
}
return slices;
}
private static string GetSliceCharacter(this string instance, char splitter, int slice)
{
if (!string.IsNullOrEmpty(instance) && slice >= 0)
{
int i = 0;
int prev = 0;
int count = 0;
while (true)
{
bool end = instance.Length <= i;
if (end || instance[i] == splitter)
{
if (slice == count)
{
return instance.Substring(prev, i - prev);
}
else if (end)
{
return string.Empty;
}
count++;
prev = i + 1;
}
i++;
}
}
return string.Empty;
}
/// <summary>
/// If the string is a path to a file, return the path to the file without the extension.
/// </summary>
public static string BaseName(this string instance)
{
int index = instance.LastIndexOf('.');
if (index > 0)
return instance.Substring(0, index);
return instance;
}
/// <summary>
/// Return <see langword="true"/> if the strings begins with the given string.
/// </summary>
public static bool BeginsWith(this string instance, string text)
{
return instance.StartsWith(text);
}
/// <summary>
/// Return the bigrams (pairs of consecutive letters) of this string.
/// </summary>
public static string[] Bigrams(this string instance)
{
var b = new string[instance.Length - 1];
for (int i = 0; i < b.Length; i++)
{
b[i] = instance.Substring(i, 2);
}
return b;
}
/// <summary>
/// Converts a string containing a binary number into an integer.
/// Binary strings can either be prefixed with `0b` or not,
/// and they can also start with a `-` before the optional prefix.
/// </summary>
/// <param name="instance">The string to convert.</param>
/// <returns>The converted string.</returns>
public static int BinToInt(this string instance)
{
if (instance.Length == 0)
{
return 0;
}
int sign = 1;
if (instance[0] == '-')
{
sign = -1;
instance = instance.Substring(1);
}
if (instance.StartsWith("0b"))
{
instance = instance.Substring(2);
}
return sign * Convert.ToInt32(instance, 2);
}
/// <summary>
/// Return the amount of substrings in string.
/// </summary>
public static int Count(this string instance, string what, bool caseSensitive = true, int from = 0, int to = 0)
{
if (what.Length == 0)
{
return 0;
}
int len = instance.Length;
int slen = what.Length;
if (len < slen)
{
return 0;
}
string str;
if (from >= 0 && to >= 0)
{
if (to == 0)
{
to = len;
}
else if (from >= to)
{
return 0;
}
if (from == 0 && to == len)
{
str = instance;
}
else
{
str = instance.Substring(from, to - from);
}
}
else
{
return 0;
}
int c = 0;
int idx;
do
{
idx = str.IndexOf(what, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
if (idx != -1)
{
str = str.Substring(idx + slen);
++c;
}
} while (idx != -1);
return c;
}
/// <summary>
/// Return a copy of the string with special characters escaped using the C language standard.
/// </summary>
public static string CEscape(this string instance)
{
var sb = new StringBuilder(string.Copy(instance));
sb.Replace("\\", "\\\\");
sb.Replace("\a", "\\a");
sb.Replace("\b", "\\b");
sb.Replace("\f", "\\f");
sb.Replace("\n", "\\n");
sb.Replace("\r", "\\r");
sb.Replace("\t", "\\t");
sb.Replace("\v", "\\v");
sb.Replace("\'", "\\'");
sb.Replace("\"", "\\\"");
sb.Replace("?", "\\?");
return sb.ToString();
}
/// <summary>
/// Return a copy of the string with escaped characters replaced by their meanings
/// according to the C language standard.
/// </summary>
public static string CUnescape(this string instance)
{
var sb = new StringBuilder(string.Copy(instance));
sb.Replace("\\a", "\a");
sb.Replace("\\b", "\b");
sb.Replace("\\f", "\f");
sb.Replace("\\n", "\n");
sb.Replace("\\r", "\r");
sb.Replace("\\t", "\t");
sb.Replace("\\v", "\v");
sb.Replace("\\'", "\'");
sb.Replace("\\\"", "\"");
sb.Replace("\\?", "?");
sb.Replace("\\\\", "\\");
return sb.ToString();
}
/// <summary>
/// Change the case of some letters. Replace underscores with spaces, convert all letters
/// to lowercase then capitalize first and every letter following the space character.
/// For <c>capitalize camelCase mixed_with_underscores</c> it will return
/// <c>Capitalize Camelcase Mixed With Underscores</c>.
/// </summary>
public static string Capitalize(this string instance)
{
string aux = instance.Replace("_", " ").ToLower();
var cap = string.Empty;
for (int i = 0; i < aux.GetSliceCount(" "); i++)
{
string slice = aux.GetSliceCharacter(' ', i);
if (slice.Length > 0)
{
slice = char.ToUpper(slice[0]) + slice.Substring(1);
if (i > 0)
cap += " ";
cap += slice;
}
}
return cap;
}
/// <summary>
/// Perform a case-sensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater.
/// </summary>
public static int CasecmpTo(this string instance, string to)
{
return instance.CompareTo(to, caseSensitive: true);
}
/// <summary>
/// Perform a comparison to another string, return -1 if less, 0 if equal and +1 if greater.
/// </summary>
public static int CompareTo(this string instance, string to, bool caseSensitive = true)
{
if (string.IsNullOrEmpty(instance))
return string.IsNullOrEmpty(to) ? 0 : -1;
if (string.IsNullOrEmpty(to))
return 1;
int instanceIndex = 0;
int toIndex = 0;
if (caseSensitive) // Outside while loop to avoid checking multiple times, despite some code duplication.
{
while (true)
{
if (to[toIndex] == 0 && instance[instanceIndex] == 0)
return 0; // We're equal
if (instance[instanceIndex] == 0)
return -1; // If this is empty, and the other one is not, then we're less... I think?
if (to[toIndex] == 0)
return 1; // Otherwise the other one is smaller...
if (instance[instanceIndex] < to[toIndex]) // More than
return -1;
if (instance[instanceIndex] > to[toIndex]) // Less than
return 1;
instanceIndex++;
toIndex++;
}
}
else
{
while (true)
{
if (to[toIndex] == 0 && instance[instanceIndex] == 0)
return 0; // We're equal
if (instance[instanceIndex] == 0)
return -1; // If this is empty, and the other one is not, then we're less... I think?
if (to[toIndex] == 0)
return 1; // Otherwise the other one is smaller..
if (char.ToUpper(instance[instanceIndex]) < char.ToUpper(to[toIndex])) // More than
return -1;
if (char.ToUpper(instance[instanceIndex]) > char.ToUpper(to[toIndex])) // Less than
return 1;
instanceIndex++;
toIndex++;
}
}
}
/// <summary>
/// Return <see langword="true"/> if the strings ends with the given string.
/// </summary>
public static bool EndsWith(this string instance, string text)
{
return instance.EndsWith(text);
}
/// <summary>
/// Erase <paramref name="chars"/> characters from the string starting from <paramref name="pos"/>.
/// </summary>
public static void Erase(this StringBuilder instance, int pos, int chars)
{
instance.Remove(pos, chars);
}
/// <summary>
/// If the string is a path to a file, return the extension.
/// </summary>
public static string Extension(this string instance)
{
int pos = instance.FindLast(".");
if (pos < 0)
return instance;
return instance.Substring(pos + 1);
}
/// <summary>
/// Find the first occurrence of a substring. Optionally, the search starting position can be passed.
/// </summary>
/// <returns>The starting position of the substring, or -1 if not found.</returns>
public static int Find(this string instance, string what, int from = 0, bool caseSensitive = true)
{
return instance.IndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Find the first occurrence of a char. Optionally, the search starting position can be passed.
/// </summary>
/// <returns>The first instance of the char, or -1 if not found.</returns>
public static int Find(this string instance, char what, int from = 0, bool caseSensitive = true)
{
// TODO: Could be more efficient if we get a char version of `IndexOf`.
// See https://github.com/dotnet/runtime/issues/44116
return instance.IndexOf(what.ToString(), from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
/// <summary>Find the last occurrence of a substring.</summary>
/// <returns>The starting position of the substring, or -1 if not found.</returns>
public static int FindLast(this string instance, string what, bool caseSensitive = true)
{
return instance.FindLast(what, instance.Length - 1, caseSensitive);
}
/// <summary>Find the last occurrence of a substring specifying the search starting position.</summary>
/// <returns>The starting position of the substring, or -1 if not found.</returns>
public static int FindLast(this string instance, string what, int from, bool caseSensitive = true)
{
return instance.LastIndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Find the first occurrence of a substring but search as case-insensitive.
/// Optionally, the search starting position can be passed.
/// </summary>
/// <returns>The starting position of the substring, or -1 if not found.</returns>
public static int FindN(this string instance, string what, int from = 0)
{
return instance.IndexOf(what, from, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// If the string is a path to a file, return the base directory.
/// </summary>
public static string GetBaseDir(this string instance)
{
int basepos = instance.Find("://");
string rs;
var @base = string.Empty;
if (basepos != -1)
{
var end = basepos + 3;
rs = instance.Substring(end);
@base = instance.Substring(0, end);
}
else
{
if (instance.BeginsWith("/"))
{
rs = instance.Substring(1);
@base = "/";
}
else
{
rs = instance;
}
}
int sep = Mathf.Max(rs.FindLast("/"), rs.FindLast("\\"));
if (sep == -1)
return @base;
return @base + rs.Substr(0, sep);
}
/// <summary>
/// If the string is a path to a file, return the file and ignore the base directory.
/// </summary>
public static string GetFile(this string instance)
{
int sep = Mathf.Max(instance.FindLast("/"), instance.FindLast("\\"));
if (sep == -1)
return instance;
return instance.Substring(sep + 1);
}
/// <summary>
/// Converts the given byte array of ASCII encoded text to a string.
/// Faster alternative to <see cref="GetStringFromUTF8"/> if the
/// content is ASCII-only. Unlike the UTF-8 function this function
/// maps every byte to a character in the array. Multibyte sequences
/// will not be interpreted correctly. For parsing user input always
/// use <see cref="GetStringFromUTF8"/>.
/// </summary>
/// <param name="bytes">A byte array of ASCII characters (on the range of 0-127).</param>
/// <returns>A string created from the bytes.</returns>
public static string GetStringFromASCII(this byte[] bytes)
{
return Encoding.ASCII.GetString(bytes);
}
/// <summary>
/// Converts the given byte array of UTF-8 encoded text to a string.
/// Slower than <see cref="GetStringFromASCII"/> but supports UTF-8
/// encoded data. Use this function if you are unsure about the
/// source of the data. For user input this function
/// should always be preferred.
/// </summary>
/// <param name="bytes">A byte array of UTF-8 characters (a character may take up multiple bytes).</param>
/// <returns>A string created from the bytes.</returns>
public static string GetStringFromUTF8(this byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
/// <summary>
/// Hash the string and return a 32 bits unsigned integer.
/// </summary>
public static uint Hash(this string instance)
{
uint hash = 5381;
foreach (uint c in instance)
{
hash = (hash << 5) + hash + c; // hash * 33 + c
}
return hash;
}
/// <summary>
/// Returns a hexadecimal representation of this byte as a string.
/// </summary>
/// <param name="b">The byte to encode.</param>
/// <returns>The hexadecimal representation of this byte.</returns>
internal static string HexEncode(this byte b)
{
var ret = string.Empty;
for (int i = 0; i < 2; i++)
{
char c;
int lv = b & 0xF;
if (lv < 10)
{
c = (char)('0' + lv);
}
else
{
c = (char)('a' + lv - 10);
}
b >>= 4;
ret = c + ret;
}
return ret;
}
/// <summary>
/// Returns a hexadecimal representation of this byte array as a string.
/// </summary>
/// <param name="bytes">The byte array to encode.</param>
/// <returns>The hexadecimal representation of this byte array.</returns>
public static string HexEncode(this byte[] bytes)
{
var ret = string.Empty;
foreach (byte b in bytes)
{
ret += b.HexEncode();
}
return ret;
}
/// <summary>
/// Converts a string containing a hexadecimal number into an integer.
/// Hexadecimal strings can either be prefixed with `0x` or not,
/// and they can also start with a `-` before the optional prefix.
/// </summary>
/// <param name="instance">The string to convert.</param>
/// <returns>The converted string.</returns>
public static int HexToInt(this string instance)
{
if (instance.Length == 0)
{
return 0;
}
int sign = 1;
if (instance[0] == '-')
{
sign = -1;
instance = instance.Substring(1);
}
if (instance.StartsWith("0x"))
{
instance = instance.Substring(2);
}
return sign * int.Parse(instance, NumberStyles.HexNumber);
}
/// <summary>
/// Insert a substring at a given position.
/// </summary>
public static string Insert(this string instance, int pos, string what)
{
return instance.Insert(pos, what);
}
/// <summary>
/// If the string is a path to a file or directory, return <see langword="true"/> if the path is absolute.
/// </summary>
public static bool IsAbsPath(this string instance)
{
if (string.IsNullOrEmpty(instance))
return false;
else if (instance.Length > 1)
return instance[0] == '/' || instance[0] == '\\' || instance.Contains(":/") || instance.Contains(":\\");
else
return instance[0] == '/' || instance[0] == '\\';
}
/// <summary>
/// If the string is a path to a file or directory, return <see langword="true"/> if the path is relative.
/// </summary>
public static bool IsRelPath(this string instance)
{
return !IsAbsPath(instance);
}
/// <summary>
/// Check whether this string is a subsequence of the given string.
/// </summary>
public static bool IsSubsequenceOf(this string instance, string text, bool caseSensitive = true)
{
int len = instance.Length;
if (len == 0)
return true; // Technically an empty string is subsequence of any string
if (len > text.Length)
return false;
int source = 0;
int target = 0;
while (source < len && target < text.Length)
{
bool match;
if (!caseSensitive)
{
char sourcec = char.ToLower(instance[source]);
char targetc = char.ToLower(text[target]);
match = sourcec == targetc;
}
else
{
match = instance[source] == text[target];
}
if (match)
{
source++;
if (source >= len)
return true;
}
target++;
}
return false;
}
/// <summary>
/// Check whether this string is a subsequence of the given string, ignoring case differences.
/// </summary>
public static bool IsSubsequenceOfI(this string instance, string text)
{
return instance.IsSubsequenceOf(text, caseSensitive: false);
}
/// <summary>
/// Check whether the string contains a valid <see langword="float"/>.
/// </summary>
public static bool IsValidFloat(this string instance)
{
float f;
return float.TryParse(instance, out f);
}
/// <summary>
/// Check whether the string contains a valid color in HTML notation.
/// </summary>
public static bool IsValidHtmlColor(this string instance)
{
return Color.HtmlIsValid(instance);
}
/// <summary>
/// Check whether the string is a valid identifier. As is common in
/// programming languages, a valid identifier may contain only letters,
/// digits and underscores (_) and the first character may not be a digit.
/// </summary>
public static bool IsValidIdentifier(this string instance)
{
int len = instance.Length;
if (len == 0)
return false;
for (int i = 0; i < len; i++)
{
if (i == 0)
{
if (instance[0] >= '0' && instance[0] <= '9')
return false; // Don't start with number plz
}
bool validChar = instance[i] >= '0' &&
instance[i] <= '9' || instance[i] >= 'a' &&
instance[i] <= 'z' || instance[i] >= 'A' &&
instance[i] <= 'Z' || instance[i] == '_';
if (!validChar)
return false;
}
return true;
}
/// <summary>
/// Check whether the string contains a valid integer.
/// </summary>
public static bool IsValidInteger(this string instance)
{
int f;
return int.TryParse(instance, out f);
}
/// <summary>
/// Check whether the string contains a valid IP address.
/// </summary>
public static bool IsValidIPAddress(this string instance)
{
// TODO: Support IPv6 addresses
string[] ip = instance.Split(".");
if (ip.Length != 4)
return false;
for (int i = 0; i < ip.Length; i++)
{
string n = ip[i];
if (!n.IsValidInteger())
return false;
int val = n.ToInt();
if (val < 0 || val > 255)
return false;
}
return true;
}
/// <summary>
/// Return a copy of the string with special characters escaped using the JSON standard.
/// </summary>
public static string JSONEscape(this string instance)
{
var sb = new StringBuilder(string.Copy(instance));
sb.Replace("\\", "\\\\");
sb.Replace("\b", "\\b");
sb.Replace("\f", "\\f");
sb.Replace("\n", "\\n");
sb.Replace("\r", "\\r");
sb.Replace("\t", "\\t");
sb.Replace("\v", "\\v");
sb.Replace("\"", "\\\"");
return sb.ToString();
}
/// <summary>
/// Return an amount of characters from the left of the string.
/// </summary>
public static string Left(this string instance, int pos)
{
if (pos <= 0)
return string.Empty;
if (pos >= instance.Length)
return instance;
return instance.Substring(0, pos);
}
/// <summary>
/// Return the length of the string in characters.
/// </summary>
public static int Length(this string instance)
{
return instance.Length;
}
/// <summary>
/// Returns a copy of the string with characters removed from the left.
/// </summary>
/// <param name="instance">The string to remove characters from.</param>
/// <param name="chars">The characters to be removed.</param>
/// <returns>A copy of the string with characters removed from the left.</returns>
public static string LStrip(this string instance, string chars)
{
int len = instance.Length;
int beg;
for (beg = 0; beg < len; beg++)
{
if (chars.Find(instance[beg]) == -1)
{
break;
}
}
if (beg == 0)
{
return instance;
}
return instance.Substr(beg, len - beg);
}
/// <summary>
/// Do a simple expression match, where '*' matches zero or more
/// arbitrary characters and '?' matches any single character except '.'.
/// </summary>
private static bool ExprMatch(this string instance, string expr, bool caseSensitive)
{
// case '\0':
if (expr.Length == 0)
return instance.Length == 0;
switch (expr[0])
{
case '*':
return ExprMatch(instance, expr.Substring(1), caseSensitive) || (instance.Length > 0 && ExprMatch(instance.Substring(1), expr, caseSensitive));
case '?':
return instance.Length > 0 && instance[0] != '.' && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive);
default:
if (instance.Length == 0)
return false;
if (caseSensitive)
return instance[0] == expr[0];
return (char.ToUpper(instance[0]) == char.ToUpper(expr[0])) && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive);
}
}
/// <summary>
/// Do a simple case sensitive expression match, using ? and * wildcards
/// (see <see cref="ExprMatch(string, string, bool)"/>).
/// </summary>
public static bool Match(this string instance, string expr, bool caseSensitive = true)
{
if (instance.Length == 0 || expr.Length == 0)
return false;
return instance.ExprMatch(expr, caseSensitive);
}
/// <summary>
/// Do a simple case insensitive expression match, using ? and * wildcards
/// (see <see cref="ExprMatch(string, string, bool)"/>).
/// </summary>
public static bool MatchN(this string instance, string expr)
{
if (instance.Length == 0 || expr.Length == 0)
return false;
return instance.ExprMatch(expr, caseSensitive: false);
}
/// <summary>
/// Return the MD5 hash of the string as an array of bytes.
/// </summary>
public static byte[] MD5Buffer(this string instance)
{
return godot_icall_String_md5_buffer(instance);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static byte[] godot_icall_String_md5_buffer(string str);
/// <summary>
/// Return the MD5 hash of the string as a string.
/// </summary>
public static string MD5Text(this string instance)
{
return godot_icall_String_md5_text(instance);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static string godot_icall_String_md5_text(string str);
/// <summary>
/// Perform a case-insensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater.
/// </summary>
public static int NocasecmpTo(this string instance, string to)
{
return instance.CompareTo(to, caseSensitive: false);
}
/// <summary>
/// Return the character code at position <paramref name="at"/>.
/// </summary>
public static int OrdAt(this string instance, int at)
{
return instance[at];
}
/// <summary>
/// Format a number to have an exact number of <paramref name="digits"/> after the decimal point.
/// </summary>
public static string PadDecimals(this string instance, int digits)
{
int c = instance.Find(".");
if (c == -1)
{
if (digits <= 0)
return instance;
instance += ".";
c = instance.Length - 1;
}
else
{
if (digits <= 0)
return instance.Substring(0, c);
}
if (instance.Length - (c + 1) > digits)
{
instance = instance.Substring(0, c + digits + 1);
}
else
{
while (instance.Length - (c + 1) < digits)
{
instance += "0";
}
}
return instance;
}
/// <summary>
/// Format a number to have an exact number of <paramref name="digits"/> before the decimal point.
/// </summary>
public static string PadZeros(this string instance, int digits)
{
string s = instance;
int end = s.Find(".");
if (end == -1)
end = s.Length;
if (end == 0)
return s;
int begin = 0;
while (begin < end && (s[begin] < '0' || s[begin] > '9'))
{
begin++;
}
if (begin >= end)
return s;
while (end - begin < digits)
{
s = s.Insert(begin, "0");
end++;
}
return s;
}
/// <summary>
/// If the string is a path, this concatenates <paramref name="file"/> at the end of the string as a subpath.
/// E.g. <c>"this/is".PlusFile("path") == "this/is/path"</c>.
/// </summary>
public static string PlusFile(this string instance, string file)
{
if (instance.Length > 0 && instance[instance.Length - 1] == '/')
return instance + file;
return instance + "/" + file;
}
/// <summary>
/// Replace occurrences of a substring for different ones inside the string.
/// </summary>
public static string Replace(this string instance, string what, string forwhat)
{
return instance.Replace(what, forwhat);
}
/// <summary>
/// Replace occurrences of a substring for different ones inside the string, but search case-insensitive.
/// </summary>
public static string ReplaceN(this string instance, string what, string forwhat)
{
return Regex.Replace(instance, what, forwhat, RegexOptions.IgnoreCase);
}
/// <summary>
/// Perform a search for a substring, but start from the end of the string instead of the beginning.
/// </summary>
public static int RFind(this string instance, string what, int from = -1)
{
return godot_icall_String_rfind(instance, what, from);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static int godot_icall_String_rfind(string str, string what, int from);
/// <summary>
/// Perform a search for a substring, but start from the end of the string instead of the beginning.
/// Also search case-insensitive.
/// </summary>
public static int RFindN(this string instance, string what, int from = -1)
{
return godot_icall_String_rfindn(instance, what, from);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static int godot_icall_String_rfindn(string str, string what, int from);
/// <summary>
/// Return the right side of the string from a given position.
/// </summary>
public static string Right(this string instance, int pos)
{
if (pos >= instance.Length)
return instance;
if (pos < 0)
return string.Empty;
return instance.Substring(pos, instance.Length - pos);
}
/// <summary>
/// Returns a copy of the string with characters removed from the right.
/// </summary>
/// <param name="instance">The string to remove characters from.</param>
/// <param name="chars">The characters to be removed.</param>
/// <returns>A copy of the string with characters removed from the right.</returns>
public static string RStrip(this string instance, string chars)
{
int len = instance.Length;
int end;
for (end = len - 1; end >= 0; end--)
{
if (chars.Find(instance[end]) == -1)
{
break;
}
}
if (end == len - 1)
{
return instance;
}
return instance.Substr(0, end + 1);
}
public static byte[] SHA256Buffer(this string instance)
{
return godot_icall_String_sha256_buffer(instance);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static byte[] godot_icall_String_sha256_buffer(string str);
/// <summary>
/// Return the SHA-256 hash of the string as a string.
/// </summary>
public static string SHA256Text(this string instance)
{
return godot_icall_String_sha256_text(instance);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static string godot_icall_String_sha256_text(string str);
/// <summary>
/// Return the similarity index of the text compared to this string.
/// 1 means totally similar and 0 means totally dissimilar.
/// </summary>
public static float Similarity(this string instance, string text)
{
if (instance == text)
{
// Equal strings are totally similar
return 1.0f;
}
if (instance.Length < 2 || text.Length < 2)
{
// No way to calculate similarity without a single bigram
return 0.0f;
}
string[] sourceBigrams = instance.Bigrams();
string[] targetBigrams = text.Bigrams();
int sourceSize = sourceBigrams.Length;
int targetSize = targetBigrams.Length;
float sum = sourceSize + targetSize;
float inter = 0;
for (int i = 0; i < sourceSize; i++)
{
for (int j = 0; j < targetSize; j++)
{
if (sourceBigrams[i] == targetBigrams[j])
{
inter++;
break;
}
}
}
return 2.0f * inter / sum;
}
/// <summary>
/// Split the string by a divisor string, return an array of the substrings.
/// Example "One,Two,Three" will return ["One","Two","Three"] if split by ",".
/// </summary>
public static string[] Split(this string instance, string divisor, bool allowEmpty = true)
{
return instance.Split(new[] { divisor }, allowEmpty ? StringSplitOptions.None : StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>
/// Split the string in floats by using a divisor string, return an array of the substrings.
/// Example "1,2.5,3" will return [1,2.5,3] if split by ",".
/// </summary>
public static float[] SplitFloats(this string instance, string divisor, bool allowEmpty = true)
{
var ret = new List<float>();
int from = 0;
int len = instance.Length;
while (true)
{
int end = instance.Find(divisor, from, caseSensitive: true);
if (end < 0)
end = len;
if (allowEmpty || end > from)
ret.Add(float.Parse(instance.Substring(from)));
if (end == len)
break;
from = end + divisor.Length;
}
return ret.ToArray();
}
private static readonly char[] _nonPrintable = {
(char)00, (char)01, (char)02, (char)03, (char)04, (char)05,
(char)06, (char)07, (char)08, (char)09, (char)10, (char)11,
(char)12, (char)13, (char)14, (char)15, (char)16, (char)17,
(char)18, (char)19, (char)20, (char)21, (char)22, (char)23,
(char)24, (char)25, (char)26, (char)27, (char)28, (char)29,
(char)30, (char)31, (char)32
};
/// <summary>
/// Return a copy of the string stripped of any non-printable character at the beginning and the end.
/// The optional arguments are used to toggle stripping on the left and right edges respectively.
/// </summary>
public static string StripEdges(this string instance, bool left = true, bool right = true)
{
if (left)
{
if (right)
return instance.Trim(_nonPrintable);
return instance.TrimStart(_nonPrintable);
}
return instance.TrimEnd(_nonPrintable);
}
/// <summary>
/// Return part of the string from the position <paramref name="from"/>, with length <paramref name="len"/>.
/// </summary>
public static string Substr(this string instance, int from, int len)
{
int max = instance.Length - from;
return instance.Substring(from, len > max ? max : len);
}
/// <summary>
/// Convert the String (which is a character array) to PackedByteArray (which is an array of bytes).
/// The conversion is speeded up in comparison to <see cref="ToUTF8(string)"/> with the assumption
/// that all the characters the String contains are only ASCII characters.
/// </summary>
public static byte[] ToAscii(this string instance)
{
return Encoding.ASCII.GetBytes(instance);
}
/// <summary>
/// Convert a string, containing a decimal number, into a <see langword="float" />.
/// </summary>
public static float ToFloat(this string instance)
{
return float.Parse(instance);
}
/// <summary>
/// Convert a string, containing an integer number, into an <see langword="int" />.
/// </summary>
public static int ToInt(this string instance)
{
return int.Parse(instance);
}
/// <summary>
/// Return the string converted to lowercase.
/// </summary>
public static string ToLower(this string instance)
{
return instance.ToLower();
}
/// <summary>
/// Return the string converted to uppercase.
/// </summary>
public static string ToUpper(this string instance)
{
return instance.ToUpper();
}
/// <summary>
/// Convert the String (which is an array of characters) to PackedByteArray (which is an array of bytes).
/// The conversion is a bit slower than <see cref="ToAscii(string)"/>, but supports all UTF-8 characters.
/// Therefore, you should prefer this function over <see cref="ToAscii(string)"/>.
/// </summary>
public static byte[] ToUTF8(this string instance)
{
return Encoding.UTF8.GetBytes(instance);
}
/// <summary>
/// Decodes a string in URL encoded format. This is meant to
/// decode parameters in a URL when receiving an HTTP request.
/// This mostly wraps around `System.Uri.UnescapeDataString()`,
/// but also handles `+`.
/// See <see cref="URIEncode"/> for encoding.
/// </summary>
/// <param name="instance">The string to decode.</param>
/// <returns>The unescaped string.</returns>
public static string URIDecode(this string instance)
{
return Uri.UnescapeDataString(instance.Replace("+", "%20"));
}
/// <summary>
/// Encodes a string to URL friendly format. This is meant to
/// encode parameters in a URL when sending an HTTP request.
/// This wraps around `System.Uri.EscapeDataString()`.
/// See <see cref="URIDecode"/> for decoding.
/// </summary>
/// <param name="instance">The string to encode.</param>
/// <returns>The escaped string.</returns>
public static string URIEncode(this string instance)
{
return Uri.EscapeDataString(instance);
}
/// <summary>
/// Return a copy of the string with special characters escaped using the XML standard.
/// </summary>
public static string XMLEscape(this string instance)
{
return SecurityElement.Escape(instance);
}
/// <summary>
/// Return a copy of the string with escaped characters replaced by their meanings
/// according to the XML standard.
/// </summary>
public static string XMLUnescape(this string instance)
{
return SecurityElement.FromString(instance).Text;
}
}
}
| |
using System;
using System.ComponentModel;
using Eto.Drawing;
namespace Eto.Forms
{
/// <summary>
/// State of a <see cref="Window"/>
/// </summary>
public enum WindowState
{
/// <summary>
/// Normal, windowed state
/// </summary>
Normal,
/// <summary>
/// Window is maximized, taking the entire screen space
/// </summary>
Maximized,
/// <summary>
/// Window is minimized to the dock/taskbar/etc.
/// </summary>
Minimized
}
/// <summary>
/// Style of a <see cref="Window"/>
/// </summary>
public enum WindowStyle
{
/// <summary>
/// Default, bordered style
/// </summary>
Default,
/// <summary>
/// Window with no border
/// </summary>
None
}
/// <summary>
/// Base window
/// </summary>
public abstract class Window : Panel
{
new IHandler Handler { get { return (IHandler)base.Handler; } }
#region Events
/// <summary>
/// Identifier for handlers when attaching the <see cref="Closed"/> event.
/// </summary>
public const string ClosedEvent = "Window.Closed";
/// <summary>
/// Occurs when the window is closed.
/// </summary>
public event EventHandler<EventArgs> Closed
{
add { Properties.AddHandlerEvent(ClosedEvent, value); }
remove { Properties.RemoveEvent(ClosedEvent, value); }
}
/// <summary>
/// Raises the <see cref="Closed"/> event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnClosed(EventArgs e)
{
OnUnLoad(EventArgs.Empty);
Properties.TriggerEvent(ClosedEvent, this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="Closing"/> event.
/// </summary>
public const string ClosingEvent = "Window.Closing";
/// <summary>
/// Occurs before the window is closed, giving an opportunity to cancel the close operation.
/// </summary>
public event EventHandler<CancelEventArgs> Closing
{
add { Properties.AddHandlerEvent(ClosingEvent, value); }
remove { Properties.RemoveEvent(ClosingEvent, value); }
}
/// <summary>
/// Raises the <see cref="Closing"/> event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnClosing(CancelEventArgs e)
{
Properties.TriggerEvent(ClosingEvent, this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="LocationChanged"/> event.
/// </summary>
public const string LocationChangedEvent = "Window.LocationChanged";
/// <summary>
/// Occurs when the <see cref="Location"/> of the window is changed.
/// </summary>
public event EventHandler<EventArgs> LocationChanged
{
add { Properties.AddHandlerEvent(LocationChangedEvent, value); }
remove { Properties.RemoveEvent(LocationChangedEvent, value); }
}
/// <summary>
/// Raises the <see cref="LocationChanged"/> event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnLocationChanged(EventArgs e)
{
Properties.TriggerEvent(LocationChangedEvent, this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="OwnerChanged"/> event.
/// </summary>
private const string OwnerChangedEvent = "Window.OwnerChanged";
/// <summary>
/// Occurs when the <see cref="Owner"/> is changed.
/// </summary>
public event EventHandler<EventArgs> OwnerChanged
{
add { Properties.AddEvent(OwnerChangedEvent, value); }
remove { Properties.RemoveEvent(OwnerChangedEvent, value); }
}
/// <summary>
/// Raises the <see cref="OwnerChanged"/> event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnOwnerChanged(EventArgs e)
{
Properties.TriggerEvent(OwnerChangedEvent, this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="WindowStateChanged"/> event.
/// </summary>
public const string WindowStateChangedEvent = "Window.WindowStateChanged";
/// <summary>
/// Occurs when the <see cref="WindowState"/> is changed.
/// </summary>
public event EventHandler<EventArgs> WindowStateChanged
{
add { Properties.AddHandlerEvent(WindowStateChangedEvent, value); }
remove { Properties.RemoveEvent(WindowStateChangedEvent, value); }
}
/// <summary>
/// Raises the <see cref="WindowStateChanged"/> event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnWindowStateChanged(EventArgs e)
{
Properties.TriggerEvent(WindowStateChangedEvent, this, e);
}
#endregion
static Window()
{
EventLookup.Register<Window>(c => c.OnClosed(null), ClosedEvent);
EventLookup.Register<Window>(c => c.OnClosing(null), ClosingEvent);
EventLookup.Register<Window>(c => c.OnLocationChanged(null), LocationChangedEvent);
EventLookup.Register<Window>(c => c.OnWindowStateChanged(null), WindowStateChangedEvent);
}
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Forms.Window"/> class.
/// </summary>
protected Window()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Window"/> with the specified handler
/// </summary>
/// <param name="handler">Pre-created handler to attach to this instance</param>
protected Window(IHandler handler)
: base(handler)
{
}
/// <summary>
/// Gets or sets the title of the window
/// </summary>
/// <remarks>
/// The title of the window is displayed to the user usually at the top of the window, but in cases where
/// you show a window in a mobile environment, this may be the title shown in a navigation controller.
/// </remarks>
/// <value>The title of the window</value>
public string Title
{
get { return Handler.Title; }
set { Handler.Title = value; }
}
/// <summary>
/// Gets or sets the location of the window
/// </summary>
/// <remarks>
/// Note that in multi-monitor setups, the origin of the location is at the upper-left of <see cref="Eto.Forms.Screen.PrimaryScreen"/>
/// </remarks>
public new Point Location
{
get { return Handler.Location; }
set { Handler.Location = value; }
}
/// <summary>
/// Gets or sets the size and location of the window
/// </summary>
/// <value>The bounding rectangle of the window</value>
public new Rectangle Bounds
{
get { return new Rectangle(Handler.Location, Handler.Size); }
set
{
Handler.Location = value.Location;
Handler.Size = value.Size;
}
}
/// <summary>
/// Gets or sets the tool bar for the window.
/// </summary>
/// <remarks>
/// Note that each window can only have a single tool bar
/// </remarks>
/// <value>The tool bar for the window</value>
public ToolBar ToolBar
{
get { return Handler.ToolBar; }
set
{
var toolbar = Handler.ToolBar;
if (toolbar != null)
{
toolbar.TriggerUnLoad(EventArgs.Empty);
toolbar.Parent = null;
}
if (value != null)
{
value.Parent = this;
value.TriggerPreLoad(EventArgs.Empty);
}
Handler.ToolBar = value;
if (value != null)
value.TriggerLoad(EventArgs.Empty);
}
}
/// <summary>
/// Gets or sets the opacity of the window
/// </summary>
/// <value>The window opacity.</value>
public double Opacity
{
get { return Handler.Opacity; }
set { Handler.Opacity = value; }
}
/// <summary>
/// Closes the window
/// </summary>
/// <remarks>
/// Note that once a window is closed, it cannot be shown again in most platforms.
/// </remarks>
public virtual void Close()
{
Handler.Close();
}
static readonly object OwnerKey = new object();
/// <summary>
/// Gets or sets the owner of this window.
/// </summary>
/// <remarks>
/// This sets the parent window that has ownership over this window.
/// For a <see cref="Dialog"/>, this will be the window that will be disabled while the modal dialog is shown.
/// With a <see cref="Form"/>, the specified owner will always be below the current window when shown, and will
/// still be responsive to user input. Typically, but not always, the window will move along with the owner.
/// </remarks>
/// <value>The owner of this window.</value>
public Window Owner
{
get { return Properties.Get<Window>(OwnerKey); }
set {
Properties.Set(OwnerKey, value, () =>
{
Handler.SetOwner(value);
OnOwnerChanged(EventArgs.Empty);
});
}
}
/// <summary>
/// Gets the screen this window is mostly contained in. Typically defined by the screen center of the window is visible.
/// </summary>
/// <value>The window's current screen.</value>
public Screen Screen
{
get { return Handler.Screen; }
}
/// <summary>
/// Gets or sets the menu bar for this window
/// </summary>
/// <remarks>
/// Some platforms have a global menu bar (e.g. ubuntu, OS X).
/// When the winow is in focus, the global menu bar will be changed to reflect the menu assigned.
/// </remarks>
/// <value>The menu.</value>
public virtual MenuBar Menu
{
get { return Handler.Menu; }
set
{
var menu = Handler.Menu;
if (menu != null)
{
menu.OnUnLoad(EventArgs.Empty);
menu.Parent = null;
}
if (value != null)
{
value.Parent = this;
value.OnPreLoad(EventArgs.Empty);
}
Handler.Menu = value;
if (value != null)
value.OnLoad(EventArgs.Empty);
}
}
/// <summary>
/// Gets or sets the icon for the window to show in the menu bar.
/// </summary>
/// <remarks>
/// The icon should have many variations, such as 16x16, 24x24, 32x32, 48x48, 64x64, etc. This ensures that
/// the many places it is used (title bar, task bar, switch window, etc) all have optimized icon sizes.
///
/// For OS X, the application icon is specified in the .app bundle, not by this value.
/// </remarks>
/// <value>The icon for this window.</value>
public Icon Icon
{
get { return Handler.Icon; }
set { Handler.Icon = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.Window"/> is resizable.
/// </summary>
/// <value><c>true</c> if resizable; otherwise, <c>false</c>.</value>
public bool Resizable
{
get { return Handler.Resizable; }
set { Handler.Resizable = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.Window"/> can be maximized.
/// </summary>
/// <remarks>
/// This may hide or disable the minimize button on the title bar.
/// </remarks>
/// <value><c>true</c> if maximizable; otherwise, <c>false</c>.</value>
public bool Maximizable
{
get { return Handler.Maximizable; }
set { Handler.Maximizable = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.Window"/> can be minimized.
/// </summary>
/// <remarks>
/// This may hide or disable the maximize button on the title bar.
/// </remarks>
/// <value><c>true</c> if minimizable; otherwise, <c>false</c>.</value>
public bool Minimizable
{
get { return Handler.Minimizable; }
set { Handler.Minimizable = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.Window"/> will show in the taskbar.
/// </summary>
/// <remarks>
/// Some platforms, e.g. OS X do not show a separate icon for each running window.
/// </remarks>
/// <value><c>true</c> if the window will show in taskbar; otherwise, <c>false</c>.</value>
public bool ShowInTaskbar
{
get { return Handler.ShowInTaskbar; }
set { Handler.ShowInTaskbar = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.Window"/> is above all other windows.
/// </summary>
/// <remarks>
/// The window should be above all other windows when this is true. In some platforms, this will show above all other windows only
/// when the application has focus.
/// </remarks>
/// <value><c>true</c> if the window should be topmost; otherwise, <c>false</c>.</value>
public bool Topmost
{
get { return Handler.Topmost; }
set { Handler.Topmost = value; }
}
/// <summary>
/// Gets or sets the state of the window.
/// </summary>
/// <value>The state of the window.</value>
public WindowState WindowState
{
get { return Handler.WindowState; }
set { Handler.WindowState = value; }
}
/// <summary>
/// Gets the bounds of the window before it was minimized or maximized, or the current bounds if <see cref="WindowState"/> is Normal.
/// </summary>
/// <remarks>
/// This is useful to retrieve the desired size and position of the window even though it is currently maximized or minimized.
/// </remarks>
/// <value>The restore bounds.</value>
public Rectangle RestoreBounds
{
get { return Handler.RestoreBounds; }
}
/// <summary>
/// Sets <see cref="WindowState"/> to <see cref="Eto.Forms.WindowState.Minimized"/>
/// </summary>
public void Minimize()
{
Handler.WindowState = WindowState.Minimized;
}
/// <summary>
/// Sets <see cref="WindowState"/> to <see cref="Eto.Forms.WindowState.Maximized"/>
/// </summary>
public void Maximize()
{
Handler.WindowState = WindowState.Maximized;
}
/// <summary>
/// Gets or sets the style of this window.
/// </summary>
/// <value>The window style.</value>
public WindowStyle WindowStyle
{
get { return Handler.WindowStyle; }
set { Handler.WindowStyle = value; }
}
/// <summary>
/// Brings the window in front of all other windows in the z-order.
/// </summary>
public void BringToFront()
{
Handler.BringToFront();
}
/// <summary>
/// Sends the window behind all other windows in the z-order.
/// </summary>
public void SendToBack()
{
Handler.SendToBack();
}
/// <summary>
/// Raises the <see cref="BindableWidget.DataContextChanged"/> event
/// </summary>
/// <remarks>
/// Implementors may override this to fire this event on child widgets in a heirarchy.
/// This allows a control to be bound to its own <see cref="BindableWidget.DataContext"/>, which would be set
/// on one of the parent control(s).
/// </remarks>
/// <param name="e">Event arguments</param>
protected override void OnDataContextChanged(EventArgs e)
{
base.OnDataContextChanged(e);
var tb = ToolBar;
if (tb != null)
tb.TriggerDataContextChanged(e);
var menu = Menu;
if (menu != null)
menu.TriggerDataContextChanged(e);
}
#region Callback
static readonly object callback = new Callback();
/// <summary>
/// Gets an instance of an object used to perform callbacks to the widget from handler implementations
/// </summary>
/// <returns>The callback instance to use for this widget</returns>
protected override object GetCallback() { return callback; }
/// <summary>
/// Callback interface for instances of <see cref="Window"/>
/// </summary>
public new interface ICallback : Panel.ICallback
{
/// <summary>
/// Raises the closed event.
/// </summary>
void OnClosed(Window widget, EventArgs e);
/// <summary>
/// Raises the closing event.
/// </summary>
void OnClosing(Window widget, CancelEventArgs e);
/// <summary>
/// Raises the location changed event.
/// </summary>
void OnLocationChanged(Window widget, EventArgs e);
/// <summary>
/// Raises the window state changed event.
/// </summary>
void OnWindowStateChanged(Window widget, EventArgs e);
}
/// <summary>
/// Callback methods for handlers of <see cref="Control"/>
/// </summary>
protected new class Callback : Panel.Callback, ICallback
{
/// <summary>
/// Raises the closed event.
/// </summary>
public void OnClosed(Window widget, EventArgs e)
{
widget.Platform.Invoke(() => widget.OnClosed(e));
}
/// <summary>
/// Raises the closing event.
/// </summary>
public void OnClosing(Window widget, CancelEventArgs e)
{
widget.Platform.Invoke(() => widget.OnClosing(e));
}
/// <summary>
/// Raises the location changed event.
/// </summary>
public void OnLocationChanged(Window widget, EventArgs e)
{
widget.Platform.Invoke(() => widget.OnLocationChanged(e));
}
/// <summary>
/// Raises the window state changed event.
/// </summary>
public void OnWindowStateChanged(Window widget, EventArgs e)
{
widget.Platform.Invoke(() => widget.OnWindowStateChanged(e));
}
}
#endregion
#region Handler
/// <summary>
/// Handler interface for the <see cref="Window"/>
/// </summary>
public new interface IHandler : Panel.IHandler
{
/// <summary>
/// Gets or sets the tool bar for the window.
/// </summary>
/// <remarks>
/// Note that each window can only have a single tool bar
/// </remarks>
/// <value>The tool bar for the window</value>
ToolBar ToolBar { get; set; }
/// <summary>
/// Closes the window
/// </summary>
/// <remarks>
/// Note that once a window is closed, it cannot be shown again in most platforms.
/// </remarks>
void Close();
/// <summary>
/// Gets or sets the location of the window
/// </summary>
/// <remarks>
/// Note that in multi-monitor setups, the origin of the location is at the upper-left of <see cref="Eto.Forms.Screen.PrimaryScreen"/>
/// </remarks>
new Point Location { get; set; }
/// <summary>
/// Gets or sets the opacity of the window
/// </summary>
/// <value>The window opacity.</value>
double Opacity { get; set; }
/// <summary>
/// Gets or sets the title of the window
/// </summary>
/// <remarks>
/// The title of the window is displayed to the user usually at the top of the window, but in cases where
/// you show a window in a mobile environment, this may be the title shown in a navigation controller.
/// </remarks>
/// <value>The title of the window</value>
string Title { get; set; }
/// <summary>
/// Gets the screen this window is mostly contained in. Typically defined by the screen center of the window is visible.
/// </summary>
/// <value>The window's current screen.</value>
Screen Screen { get; }
/// <summary>
/// Gets or sets the menu bar for this window
/// </summary>
/// <remarks>
/// Some platforms have a global menu bar (e.g. ubuntu, OS X).
/// When the winow is in focus, the global menu bar will be changed to reflect the menu assigned.
/// </remarks>
/// <value>The menu.</value>
MenuBar Menu { get; set; }
/// <summary>
/// Gets or sets the icon for the window to show in the menu bar.
/// </summary>
/// <remarks>
/// The icon should have many variations, such as 16x16, 24x24, 32x32, 48x48, 64x64, etc. This ensures that
/// the many places it is used (title bar, task bar, switch window, etc) all have optimized icon sizes.
///
/// For OS X, the application icon is specified in the .app bundle, not by this value.
/// </remarks>
/// <value>The icon for this window.</value>
Icon Icon { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.Window"/> is resizable.
/// </summary>
/// <value><c>true</c> if resizable; otherwise, <c>false</c>.</value>
bool Resizable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.Window"/> can be maximized.
/// </summary>
/// <remarks>
/// This may hide or disable the minimize button on the title bar.
/// </remarks>
/// <value><c>true</c> if maximizable; otherwise, <c>false</c>.</value>
bool Maximizable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.Window"/> can be minimized.
/// </summary>
/// <remarks>
/// This may hide or disable the maximize button on the title bar.
/// </remarks>
/// <value><c>true</c> if minimizable; otherwise, <c>false</c>.</value>
bool Minimizable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.Window"/> will show in the taskbar.
/// </summary>
/// <remarks>
/// Some platforms, e.g. OS X do not show a separate icon for each running window.
/// </remarks>
/// <value><c>true</c> if the window will show in taskbar; otherwise, <c>false</c>.</value>
bool ShowInTaskbar { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Eto.Forms.Window"/> is above all other windows.
/// </summary>
/// <remarks>
/// The window should be above all other windows when this is true. In some platforms, this will show above all other windows only
/// when the application has focus.
/// </remarks>
/// <value><c>true</c> if the window should be topmost; otherwise, <c>false</c>.</value>
bool Topmost { get; set; }
/// <summary>
/// Gets or sets the state of the window.
/// </summary>
/// <value>The state of the window.</value>
WindowState WindowState { get; set; }
/// <summary>
/// Gets the bounds of the window before it was minimized or maximized.
/// </summary>
/// <remarks>
/// This is useful to retrieve the desired size and position of the window even though it is currently maximized or minimized.
/// </remarks>
/// <value>The restore bounds.</value>
Rectangle RestoreBounds { get; }
/// <summary>
/// Gets or sets the style of this window.
/// </summary>
/// <value>The window style.</value>
WindowStyle WindowStyle { get; set; }
/// <summary>
/// Brings the window in front of all other windows in the z-order.
/// </summary>
void BringToFront();
/// <summary>
/// Sends the window behind all other windows in the z-order.
/// </summary>
void SendToBack();
/// <summary>
/// Sets the owner of the window
/// </summary>
/// <param name="owner">Owner of the window</param>
void SetOwner(Window owner);
}
#endregion
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
using ZXing.Common.ReedSolomon;
namespace ZXing.QrCode.Internal
{
/// <summary>
/// </summary>
/// <author>satorux@google.com (Satoru Takabayashi) - creator</author>
/// <author>dswitkin@google.com (Daniel Switkin) - ported from C++</author>
public static class Encoder
{
// The original table is defined in the table 5 of JISX0510:2004 (p.19).
private static readonly int[] ALPHANUMERIC_TABLE = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f
36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f
};
internal static String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1";
// The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
// Basically it applies four rules and summate all penalties.
private static int calculateMaskPenalty(ByteMatrix matrix)
{
return MaskUtil.applyMaskPenaltyRule1(matrix)
+ MaskUtil.applyMaskPenaltyRule2(matrix)
+ MaskUtil.applyMaskPenaltyRule3(matrix)
+ MaskUtil.applyMaskPenaltyRule4(matrix);
}
/// <summary>
/// Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen
/// internally by chooseMode(). On success, store the result in "qrCode".
/// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
/// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
/// strong error correction for this purpose.
/// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
/// with which clients can specify the encoding mode. For now, we don't need the functionality.
/// </summary>
/// <param name="content">text to encode</param>
/// <param name="ecLevel">error correction level to use</param>
/// <returns><see cref="QRCode"/> representing the encoded QR code</returns>
public static QRCode encode(String content, ErrorCorrectionLevel ecLevel)
{
return encode(content, ecLevel, null);
}
/// <summary>
/// Encodes the specified content.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="ecLevel">The ec level.</param>
/// <param name="hints">The hints.</param>
/// <returns></returns>
public static QRCode encode(String content,
ErrorCorrectionLevel ecLevel,
IDictionary<EncodeHintType, object> hints)
{
// Determine what character encoding has been specified by the caller, if any
bool hasEncodingHint = hints != null && hints.ContainsKey(EncodeHintType.CHARACTER_SET);
#if !SILVERLIGHT || WINDOWS_PHONE
var encoding = hints == null || !hints.ContainsKey(EncodeHintType.CHARACTER_SET) ? null : (String)hints[EncodeHintType.CHARACTER_SET];
if (encoding == null)
{
encoding = DEFAULT_BYTE_MODE_ENCODING;
}
var generateECI = hasEncodingHint || !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding);
#else
// Silverlight supports only UTF-8 and UTF-16 out-of-the-box
const string encoding = "UTF-8";
// caller of the method can only control if the ECI segment should be written
// character set is fixed to UTF-8; but some scanners doesn't like the ECI segment
var generateECI = hasEncodingHint;
#endif
// Pick an encoding mode appropriate for the content. Note that this will not attempt to use
// multiple modes / segments even if that were more efficient. Twould be nice.
var mode = chooseMode(content, encoding);
// This will store the header information, like mode and
// length, as well as "header" segments like an ECI segment.
var headerBits = new BitArray();
// Append ECI segment if applicable
if (mode == Mode.BYTE && generateECI)
{
var eci = CharacterSetECI.getCharacterSetECIByName(encoding);
if (eci != null)
{
var eciIsExplicitDisabled = (hints != null && hints.ContainsKey(EncodeHintType.DISABLE_ECI) && hints[EncodeHintType.DISABLE_ECI] != null && Convert.ToBoolean(hints[EncodeHintType.DISABLE_ECI].ToString()));
if (!eciIsExplicitDisabled)
{
appendECI(eci, headerBits);
}
}
}
// (With ECI in place,) Write the mode marker
appendModeInfo(mode, headerBits);
// Collect data within the main segment, separately, to count its size if needed. Don't add it to
// main payload yet.
var dataBits = new BitArray();
appendBytes(content, mode, dataBits, encoding);
Version version;
if (hints != null && hints.ContainsKey(EncodeHintType.QR_VERSION))
{
int versionNumber = Int32.Parse(hints[EncodeHintType.QR_VERSION].ToString());
version = Version.getVersionForNumber(versionNumber);
int bitsNeeded = calculateBitsNeeded(mode, headerBits, dataBits, version);
if (!willFit(bitsNeeded, version, ecLevel))
{
throw new WriterException("Data too big for requested version");
}
}
else
{
version = recommendVersion(ecLevel, mode, headerBits, dataBits);
}
var headerAndDataBits = new BitArray();
headerAndDataBits.appendBitArray(headerBits);
// Find "length" of main segment and write it
var numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length;
appendLengthInfo(numLetters, version, mode, headerAndDataBits);
// Put data together into the overall payload
headerAndDataBits.appendBitArray(dataBits);
var ecBlocks = version.getECBlocksForLevel(ecLevel);
var numDataBytes = version.TotalCodewords - ecBlocks.TotalECCodewords;
// Terminate the bits properly.
terminateBits(numDataBytes, headerAndDataBits);
// Interleave data bits with error correction code.
var finalBits = interleaveWithECBytes(headerAndDataBits,
version.TotalCodewords,
numDataBytes,
ecBlocks.NumBlocks);
var qrCode = new QRCode
{
ECLevel = ecLevel,
Mode = mode,
Version = version
};
// Choose the mask pattern and set to "qrCode".
var dimension = version.DimensionForVersion;
var matrix = new ByteMatrix(dimension, dimension);
var maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix);
qrCode.MaskPattern = maskPattern;
// Build the matrix and set it to "qrCode".
MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
qrCode.Matrix = matrix;
return qrCode;
}
/// <summary>
/// Decides the smallest version of QR code that will contain all of the provided data.
/// </summary>
/// <exception cref="WriterException">if the data cannot fit in any version</exception>
private static Version recommendVersion(ErrorCorrectionLevel ecLevel, Mode mode, BitArray headerBits, BitArray dataBits)
{
// Hard part: need to know version to know how many bits length takes. But need to know how many
// bits it takes to know version. First we take a guess at version by assuming version will be
// the minimum, 1:
var provisionalBitsNeeded = calculateBitsNeeded(mode, headerBits, dataBits, Version.getVersionForNumber(1));
var provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel);
// Use that guess to calculate the right version. I am still not sure this works in 100% of cases.
var bitsNeeded = calculateBitsNeeded(mode, headerBits, dataBits, provisionalVersion);
return chooseVersion(bitsNeeded, ecLevel);
}
private static int calculateBitsNeeded(Mode mode, BitArray headerBits, BitArray dataBits, Version version)
{
return headerBits.Size + mode.getCharacterCountBits(version) + dataBits.Size;
}
/// <summary>
/// Gets the alphanumeric code.
/// </summary>
/// <param name="code">The code.</param>
/// <returns>the code point of the table used in alphanumeric mode or
/// -1 if there is no corresponding code in the table.</returns>
internal static int getAlphanumericCode(int code)
{
if (code < ALPHANUMERIC_TABLE.Length)
{
return ALPHANUMERIC_TABLE[code];
}
return -1;
}
/// <summary>
/// Chooses the mode.
/// </summary>
/// <param name="content">The content.</param>
/// <returns></returns>
public static Mode chooseMode(String content)
{
return chooseMode(content, null);
}
/// <summary>
/// Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
/// if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="encoding">The encoding.</param>
/// <returns></returns>
private static Mode chooseMode(String content, String encoding)
{
if ("Shift_JIS".Equals(encoding) && isOnlyDoubleByteKanji(content))
{
// Choose Kanji mode if all input are double-byte characters
return Mode.KANJI;
}
bool hasNumeric = false;
bool hasAlphanumeric = false;
for (int i = 0; i < content.Length; ++i)
{
char c = content[i];
if (c >= '0' && c <= '9')
{
hasNumeric = true;
}
else if (getAlphanumericCode(c) != -1)
{
hasAlphanumeric = true;
}
else
{
return Mode.BYTE;
}
}
if (hasAlphanumeric)
{
return Mode.ALPHANUMERIC;
}
if (hasNumeric)
{
return Mode.NUMERIC;
}
return Mode.BYTE;
}
private static bool isOnlyDoubleByteKanji(String content)
{
byte[] bytes;
try
{
bytes = Encoding.GetEncoding("Shift_JIS").GetBytes(content);
}
catch (Exception )
{
return false;
}
int length = bytes.Length;
if (length % 2 != 0)
{
return false;
}
for (int i = 0; i < length; i += 2)
{
int byte1 = bytes[i] & 0xFF;
if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB))
{
return false;
}
}
return true;
}
private static int chooseMaskPattern(BitArray bits,
ErrorCorrectionLevel ecLevel,
Version version,
ByteMatrix matrix)
{
int minPenalty = Int32.MaxValue; // Lower penalty is better.
int bestMaskPattern = -1;
// We try all mask patterns to choose the best one.
for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++)
{
MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
int penalty = calculateMaskPenalty(matrix);
if (penalty < minPenalty)
{
minPenalty = penalty;
bestMaskPattern = maskPattern;
}
}
return bestMaskPattern;
}
private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel)
{
for (int versionNum = 1; versionNum <= 40; versionNum++)
{
var version = Version.getVersionForNumber(versionNum);
if (willFit(numInputBits, version, ecLevel))
{
return version;
}
}
throw new WriterException("Data too big");
}
/// <summary></summary>
/// <returns>true if the number of input bits will fit in a code with the specified version and error correction level.</returns>
private static bool willFit(int numInputBits, Version version, ErrorCorrectionLevel ecLevel)
{
// In the following comments, we use numbers of Version 7-H.
// numBytes = 196
var numBytes = version.TotalCodewords;
// getNumECBytes = 130
var ecBlocks = version.getECBlocksForLevel(ecLevel);
var numEcBytes = ecBlocks.TotalECCodewords;
// getNumDataBytes = 196 - 130 = 66
var numDataBytes = numBytes - numEcBytes;
var totalInputBytes = (numInputBits + 7) / 8;
return numDataBytes >= totalInputBytes;
}
/// <summary>
/// Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
/// </summary>
/// <param name="numDataBytes">The num data bytes.</param>
/// <param name="bits">The bits.</param>
internal static void terminateBits(int numDataBytes, BitArray bits)
{
int capacity = numDataBytes << 3;
if (bits.Size > capacity)
{
throw new WriterException("data bits cannot fit in the QR Code" + bits.Size + " > " +
capacity);
}
for (int i = 0; i < 4 && bits.Size < capacity; ++i)
{
bits.appendBit(false);
}
// Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
// If the last byte isn't 8-bit aligned, we'll add padding bits.
int numBitsInLastByte = bits.Size & 0x07;
if (numBitsInLastByte > 0)
{
for (int i = numBitsInLastByte; i < 8; i++)
{
bits.appendBit(false);
}
}
// If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
int numPaddingBytes = numDataBytes - bits.SizeInBytes;
for (int i = 0; i < numPaddingBytes; ++i)
{
bits.appendBits((i & 0x01) == 0 ? 0xEC : 0x11, 8);
}
if (bits.Size != capacity)
{
throw new WriterException("Bits size does not equal capacity");
}
}
/// <summary>
/// Get number of data bytes and number of error correction bytes for block id "blockID". Store
/// the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
/// JISX0510:2004 (p.30)
/// </summary>
/// <param name="numTotalBytes">The num total bytes.</param>
/// <param name="numDataBytes">The num data bytes.</param>
/// <param name="numRSBlocks">The num RS blocks.</param>
/// <param name="blockID">The block ID.</param>
/// <param name="numDataBytesInBlock">The num data bytes in block.</param>
/// <param name="numECBytesInBlock">The num EC bytes in block.</param>
internal static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes,
int numDataBytes,
int numRSBlocks,
int blockID,
int[] numDataBytesInBlock,
int[] numECBytesInBlock)
{
if (blockID >= numRSBlocks)
{
throw new WriterException("Block ID too large");
}
// numRsBlocksInGroup2 = 196 % 5 = 1
int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
// numRsBlocksInGroup1 = 5 - 1 = 4
int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
// numTotalBytesInGroup1 = 196 / 5 = 39
int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
// numTotalBytesInGroup2 = 39 + 1 = 40
int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
// numDataBytesInGroup1 = 66 / 5 = 13
int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
// numDataBytesInGroup2 = 13 + 1 = 14
int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
// numEcBytesInGroup1 = 39 - 13 = 26
int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
// numEcBytesInGroup2 = 40 - 14 = 26
int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
// Sanity checks.
// 26 = 26
if (numEcBytesInGroup1 != numEcBytesInGroup2)
{
throw new WriterException("EC bytes mismatch");
}
// 5 = 4 + 1.
if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2)
{
throw new WriterException("RS blocks mismatch");
}
// 196 = (13 + 26) * 4 + (14 + 26) * 1
if (numTotalBytes !=
((numDataBytesInGroup1 + numEcBytesInGroup1) *
numRsBlocksInGroup1) +
((numDataBytesInGroup2 + numEcBytesInGroup2) *
numRsBlocksInGroup2))
{
throw new WriterException("Total bytes mismatch");
}
if (blockID < numRsBlocksInGroup1)
{
numDataBytesInBlock[0] = numDataBytesInGroup1;
numECBytesInBlock[0] = numEcBytesInGroup1;
}
else
{
numDataBytesInBlock[0] = numDataBytesInGroup2;
numECBytesInBlock[0] = numEcBytesInGroup2;
}
}
/// <summary>
/// Interleave "bits" with corresponding error correction bytes. On success, store the result in
/// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
/// </summary>
/// <param name="bits">The bits.</param>
/// <param name="numTotalBytes">The num total bytes.</param>
/// <param name="numDataBytes">The num data bytes.</param>
/// <param name="numRSBlocks">The num RS blocks.</param>
/// <returns></returns>
internal static BitArray interleaveWithECBytes(BitArray bits,
int numTotalBytes,
int numDataBytes,
int numRSBlocks)
{
// "bits" must have "getNumDataBytes" bytes of data.
if (bits.SizeInBytes != numDataBytes)
{
throw new WriterException("Number of bits and data bytes does not match");
}
// Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
// store the divided data bytes blocks and error correction bytes blocks into "blocks".
int dataBytesOffset = 0;
int maxNumDataBytes = 0;
int maxNumEcBytes = 0;
// Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
var blocks = new List<BlockPair>(numRSBlocks);
for (int i = 0; i < numRSBlocks; ++i)
{
int[] numDataBytesInBlock = new int[1];
int[] numEcBytesInBlock = new int[1];
getNumDataBytesAndNumECBytesForBlockID(
numTotalBytes, numDataBytes, numRSBlocks, i,
numDataBytesInBlock, numEcBytesInBlock);
int size = numDataBytesInBlock[0];
byte[] dataBytes = new byte[size];
bits.toBytes(8 * dataBytesOffset, dataBytes, 0, size);
byte[] ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
blocks.Add(new BlockPair(dataBytes, ecBytes));
maxNumDataBytes = Math.Max(maxNumDataBytes, size);
maxNumEcBytes = Math.Max(maxNumEcBytes, ecBytes.Length);
dataBytesOffset += numDataBytesInBlock[0];
}
if (numDataBytes != dataBytesOffset)
{
throw new WriterException("Data bytes does not match offset");
}
BitArray result = new BitArray();
// First, place data blocks.
for (int i = 0; i < maxNumDataBytes; ++i)
{
foreach (BlockPair block in blocks)
{
byte[] dataBytes = block.DataBytes;
if (i < dataBytes.Length)
{
result.appendBits(dataBytes[i], 8);
}
}
}
// Then, place error correction blocks.
for (int i = 0; i < maxNumEcBytes; ++i)
{
foreach (BlockPair block in blocks)
{
byte[] ecBytes = block.ErrorCorrectionBytes;
if (i < ecBytes.Length)
{
result.appendBits(ecBytes[i], 8);
}
}
}
if (numTotalBytes != result.SizeInBytes)
{ // Should be same.
throw new WriterException("Interleaving error: " + numTotalBytes + " and " +
result.SizeInBytes + " differ.");
}
return result;
}
internal static byte[] generateECBytes(byte[] dataBytes, int numEcBytesInBlock)
{
int numDataBytes = dataBytes.Length;
int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
for (int i = 0; i < numDataBytes; i++)
{
toEncode[i] = dataBytes[i] & 0xFF;
}
new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode, numEcBytesInBlock);
byte[] ecBytes = new byte[numEcBytesInBlock];
for (int i = 0; i < numEcBytesInBlock; i++)
{
ecBytes[i] = (byte)toEncode[numDataBytes + i];
}
return ecBytes;
}
/// <summary>
/// Append mode info. On success, store the result in "bits".
/// </summary>
/// <param name="mode">The mode.</param>
/// <param name="bits">The bits.</param>
internal static void appendModeInfo(Mode mode, BitArray bits)
{
bits.appendBits(mode.Bits, 4);
}
/// <summary>
/// Append length info. On success, store the result in "bits".
/// </summary>
/// <param name="numLetters">The num letters.</param>
/// <param name="version">The version.</param>
/// <param name="mode">The mode.</param>
/// <param name="bits">The bits.</param>
internal static void appendLengthInfo(int numLetters, Version version, Mode mode, BitArray bits)
{
int numBits = mode.getCharacterCountBits(version);
if (numLetters >= (1 << numBits))
{
throw new WriterException(numLetters + " is bigger than " + ((1 << numBits) - 1));
}
bits.appendBits(numLetters, numBits);
}
/// <summary>
/// Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
/// </summary>
/// <param name="content">The content.</param>
/// <param name="mode">The mode.</param>
/// <param name="bits">The bits.</param>
/// <param name="encoding">The encoding.</param>
internal static void appendBytes(String content,
Mode mode,
BitArray bits,
String encoding)
{
if (mode.Equals(Mode.NUMERIC))
appendNumericBytes(content, bits);
else
if (mode.Equals(Mode.ALPHANUMERIC))
appendAlphanumericBytes(content, bits);
else
if (mode.Equals(Mode.BYTE))
append8BitBytes(content, bits, encoding);
else
if (mode.Equals(Mode.KANJI))
appendKanjiBytes(content, bits);
else
throw new WriterException("Invalid mode: " + mode);
}
internal static void appendNumericBytes(String content, BitArray bits)
{
int length = content.Length;
int i = 0;
while (i < length)
{
int num1 = content[i] - '0';
if (i + 2 < length)
{
// Encode three numeric letters in ten bits.
int num2 = content[i + 1] - '0';
int num3 = content[i + 2] - '0';
bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
i += 3;
}
else if (i + 1 < length)
{
// Encode two numeric letters in seven bits.
int num2 = content[i + 1] - '0';
bits.appendBits(num1 * 10 + num2, 7);
i += 2;
}
else
{
// Encode one numeric letter in four bits.
bits.appendBits(num1, 4);
i++;
}
}
}
internal static void appendAlphanumericBytes(String content, BitArray bits)
{
int length = content.Length;
int i = 0;
while (i < length)
{
int code1 = getAlphanumericCode(content[i]);
if (code1 == -1)
{
throw new WriterException();
}
if (i + 1 < length)
{
int code2 = getAlphanumericCode(content[i + 1]);
if (code2 == -1)
{
throw new WriterException();
}
// Encode two alphanumeric letters in 11 bits.
bits.appendBits(code1 * 45 + code2, 11);
i += 2;
}
else
{
// Encode one alphanumeric letter in six bits.
bits.appendBits(code1, 6);
i++;
}
}
}
internal static void append8BitBytes(String content, BitArray bits, String encoding)
{
byte[] bytes;
try
{
bytes = Encoding.GetEncoding(encoding).GetBytes(content);
}
#if WindowsCE
catch (PlatformNotSupportedException)
{
try
{
// WindowsCE doesn't support all encodings. But it is device depended.
// So we try here the some different ones
if (encoding == "ISO-8859-1")
{
bytes = Encoding.GetEncoding(1252).GetBytes(content);
}
else
{
bytes = Encoding.GetEncoding("UTF-8").GetBytes(content);
}
}
catch (Exception uee)
{
throw new WriterException(uee.Message, uee);
}
}
#endif
catch (Exception uee)
{
throw new WriterException(uee.Message, uee);
}
foreach (byte b in bytes)
{
bits.appendBits(b, 8);
}
}
internal static void appendKanjiBytes(String content, BitArray bits)
{
byte[] bytes;
try
{
bytes = Encoding.GetEncoding("Shift_JIS").GetBytes(content);
}
catch (Exception uee)
{
throw new WriterException(uee.Message, uee);
}
int length = bytes.Length;
for (int i = 0; i < length; i += 2)
{
int byte1 = bytes[i] & 0xFF;
int byte2 = bytes[i + 1] & 0xFF;
int code = (byte1 << 8) | byte2;
int subtracted = -1;
if (code >= 0x8140 && code <= 0x9ffc)
{
subtracted = code - 0x8140;
}
else if (code >= 0xe040 && code <= 0xebbf)
{
subtracted = code - 0xc140;
}
if (subtracted == -1)
{
throw new WriterException("Invalid byte sequence");
}
int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
bits.appendBits(encoded, 13);
}
}
private static void appendECI(CharacterSetECI eci, BitArray bits)
{
bits.appendBits(Mode.ECI.Bits, 4);
// This is correct for values up to 127, which is all we need now.
bits.appendBits(eci.Value, 8);
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// StatisticsValue.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Text;
using Microsoft.Xna.Framework.Content;
#endregion
namespace RolePlayingGameData
{
/// <summary>
/// The set of relevant statistics for characters.
/// </summary>
public struct StatisticsValue
{
[ContentSerializer(Optional = true)]
public Int32 HealthPoints;
[ContentSerializer(Optional = true)]
public Int32 MagicPoints;
[ContentSerializer(Optional = true)]
public Int32 PhysicalOffense;
[ContentSerializer(Optional = true)]
public Int32 PhysicalDefense;
[ContentSerializer(Optional = true)]
public Int32 MagicalOffense;
[ContentSerializer(Optional = true)]
public Int32 MagicalDefense;
/// <summary>
/// Returns true if this object is trivial - all values at zero.
/// </summary>
public bool IsZero
{
get
{
return ((HealthPoints == 0) && (MagicPoints == 0) &&
(PhysicalOffense == 0) && (PhysicalDefense == 0) &&
(MagicalOffense == 0) && (MagicalDefense == 0));
}
}
#region Initialization
/// <summary>
/// Create a new StatisticsValue object, fully specified by the parameters.
/// </summary>
public StatisticsValue(int healthPoints, int magicPoints, int physicalOffense,
int physicalDefense, int magicalOffense, int magicalDefense)
{
HealthPoints = healthPoints;
MagicPoints = magicPoints;
PhysicalOffense = physicalOffense;
PhysicalDefense = physicalDefense;
MagicalOffense = magicalOffense;
MagicalDefense = magicalDefense;
}
#endregion
#region Operator: StatisticsValue + StatisticsValue
/// <summary>
/// Add one value to another, piecewise, and return the result.
/// </summary>
public static StatisticsValue Add(StatisticsValue value1,
StatisticsValue value2)
{
StatisticsValue outputValue = new StatisticsValue();
outputValue.HealthPoints =
value1.HealthPoints + value2.HealthPoints;
outputValue.MagicPoints =
value1.MagicPoints + value2.MagicPoints;
outputValue.PhysicalOffense =
value1.PhysicalOffense + value2.PhysicalOffense;
outputValue.PhysicalDefense =
value1.PhysicalDefense + value2.PhysicalDefense;
outputValue.MagicalOffense =
value1.MagicalOffense + value2.MagicalOffense;
outputValue.MagicalDefense =
value1.MagicalDefense + value2.MagicalDefense;
return outputValue;
}
/// <summary>
/// Add one value to another, piecewise, and return the result.
/// </summary>
public static StatisticsValue operator +(StatisticsValue value1,
StatisticsValue value2)
{
return Add(value1, value2);
}
#endregion
#region Operator: StatisticsValue - StatisticsValue
/// <summary>
/// Subtract one value from another, piecewise, and return the result.
/// </summary>
public static StatisticsValue Subtract(StatisticsValue value1,
StatisticsValue value2)
{
StatisticsValue outputValue = new StatisticsValue();
outputValue.HealthPoints =
value1.HealthPoints - value2.HealthPoints;
outputValue.MagicPoints =
value1.MagicPoints - value2.MagicPoints;
outputValue.PhysicalOffense =
value1.PhysicalOffense - value2.PhysicalOffense;
outputValue.PhysicalDefense =
value1.PhysicalDefense - value2.PhysicalDefense;
outputValue.MagicalOffense =
value1.MagicalOffense - value2.MagicalOffense;
outputValue.MagicalDefense =
value1.MagicalDefense - value2.MagicalDefense;
return outputValue;
}
/// <summary>
/// Subtract one value from another, piecewise, and return the result.
/// </summary>
public static StatisticsValue operator -(StatisticsValue value1,
StatisticsValue value2)
{
return Subtract(value1, value2);
}
#endregion
// Compound assignment (+=, etc.) operators use the overloaded binary operators,
// so there is no need in this case to override them explicitly
#region Limiting
/// <summary>
/// Clamp all values piecewise with the provided minimum values.
/// </summary>
public void ApplyMinimum(StatisticsValue minimumValue)
{
HealthPoints = Math.Max(HealthPoints, minimumValue.HealthPoints);
MagicPoints = Math.Max(MagicPoints, minimumValue.MagicPoints);
PhysicalOffense = Math.Max(PhysicalOffense, minimumValue.PhysicalOffense);
PhysicalDefense = Math.Max(PhysicalDefense, minimumValue.PhysicalDefense);
MagicalOffense = Math.Max(MagicalOffense, minimumValue.MagicalOffense);
MagicalDefense = Math.Max(MagicalDefense, minimumValue.MagicalDefense);
}
/// <summary>
/// Clamp all values piecewise with the provided maximum values.
/// </summary>
public void ApplyMaximum(StatisticsValue maximumValue)
{
HealthPoints = Math.Min(HealthPoints, maximumValue.HealthPoints);
MagicPoints = Math.Min(MagicPoints, maximumValue.MagicPoints);
PhysicalOffense = Math.Min(PhysicalOffense, maximumValue.PhysicalOffense);
PhysicalDefense = Math.Min(PhysicalDefense, maximumValue.PhysicalDefense);
MagicalOffense = Math.Min(MagicalOffense, maximumValue.MagicalOffense);
MagicalDefense = Math.Min(MagicalDefense, maximumValue.MagicalDefense);
}
#endregion
#region String Output
/// <summary>
/// Builds a string that describes this object.
/// </summary>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("HP:");
sb.Append(HealthPoints.ToString());
sb.Append("; MP:");
sb.Append(MagicPoints.ToString());
sb.Append("; PO:");
sb.Append(PhysicalOffense.ToString());
sb.Append("; PD:");
sb.Append(PhysicalDefense.ToString());
sb.Append("; MO:");
sb.Append(MagicalOffense.ToString());
sb.Append("; MD:");
sb.Append(MagicalDefense.ToString());
return sb.ToString();
}
/// <summary>
/// Builds a string that describes a modifier, where non-zero stats are skipped.
/// </summary>
public string GetModifierString()
{
StringBuilder sb = new StringBuilder();
bool firstStatistic = true;
// add the health points value, if any
if (HealthPoints != 0)
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("HP:");
sb.Append(HealthPoints.ToString());
}
// add the magic points value, if any
if (MagicPoints != 0)
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("MP:");
sb.Append(MagicPoints.ToString());
}
// add the physical offense value, if any
if (PhysicalOffense != 0)
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("PO:");
sb.Append(PhysicalOffense.ToString());
}
// add the physical defense value, if any
if (PhysicalDefense != 0)
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("PD:");
sb.Append(PhysicalDefense.ToString());
}
// add the magical offense value, if any
if (MagicalOffense != 0)
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("MO:");
sb.Append(MagicalOffense.ToString());
}
// add the magical defense value, if any
if (MagicalDefense != 0)
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("MD:");
sb.Append(MagicalDefense.ToString());
}
return sb.ToString();
}
#endregion
#region Content Type Reader
public class StatisticsValueReader : ContentTypeReader<StatisticsValue>
{
protected override StatisticsValue Read(ContentReader input,
StatisticsValue existingInstance)
{
StatisticsValue output = new StatisticsValue();
output.HealthPoints = input.ReadInt32();
output.MagicPoints = input.ReadInt32();
output.PhysicalOffense = input.ReadInt32();
output.PhysicalDefense = input.ReadInt32();
output.MagicalOffense = input.ReadInt32();
output.MagicalDefense = input.ReadInt32();
return output;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using NuDoq;
using Scriban.Functions;
using Scriban.Parsing;
using Scriban.Runtime;
namespace Scriban.DocGen
{
/// <summary>
/// Program generating the documentation for all builtin functions by extracting the code comments from xml files
/// </summary>
static class Program
{
static void Main()
{
var options = new ReaderOptions
{
KeepNewLinesInText = true
};
var members = DocReader.Read(typeof(Template).Assembly, options);
var builtinClassNames = new Dictionary<string, string>
{
[nameof(ArrayFunctions)] = "array",
[nameof(DateTimeFunctions)] = "date",
[nameof(HtmlFunctions)] = "html",
[nameof(MathFunctions)] = "math",
[nameof(ObjectFunctions)] = "object",
[nameof(RegexFunctions)] = "regex",
[nameof(StringFunctions)] = "string",
[nameof(TimeSpanFunctions)] = "timespan"
};
var writer = new StreamWriter("../../../../../doc/builtins.md");
writer.WriteLine(@"# Builtins
This document describes the various built-in functions available in scriban.
");
var visitor = new MarkdownVisitor(builtinClassNames);
members.Accept(visitor);
writer.WriteLine(visitor.Toc);
foreach (var classWriter in visitor.ClassWriters.OrderBy(c => c.Key).Select(c => c.Value))
{
writer.Write(classWriter.Head);
writer.Write(classWriter.Body);
}
writer.WriteLine();
writer.WriteLine("> Note: This document was automatically generated from the sourcecode using `Scriban.DocGen` program");
writer.Flush();
writer.Close();
}
public class MarkdownVisitor : Visitor
{
private readonly Dictionary<string, string> _builtinClassNames;
private readonly Dictionary<string, ClassWriter> _classWriters;
private readonly StringWriter _writerToc;
private StringWriter _writer;
private StringWriter _writerParameters;
private StringWriter _writerReturns;
private StringWriter _writerSummary;
private StringWriter _writerRemarks;
public class ClassWriter
{
public ClassWriter()
{
Head = new StringWriter();
Body = new StringWriter();
}
public readonly StringWriter Head;
public readonly StringWriter Body;
}
public MarkdownVisitor(Dictionary<string, string> builtinClassNames)
{
_classWriters = new Dictionary<string, ClassWriter>();
_writerToc = new StringWriter();
_writerParameters = new StringWriter();
_writerReturns = new StringWriter();
_writerSummary = new StringWriter();
_writerRemarks = new StringWriter();
_builtinClassNames = builtinClassNames;
}
public StringWriter Toc => _writerToc;
public Dictionary<string, ClassWriter> ClassWriters => _classWriters;
private bool IsBuiltinType(Type type, out string shortName)
{
shortName = null;
return type.Namespace == "Scriban.Functions" && _builtinClassNames.TryGetValue(type.Name, out shortName);
}
public override void VisitMember(Member member)
{
var type = member.Info as Type;
var methodInfo = member.Info as MethodInfo;
if (type != null && IsBuiltinType(type, out string shortName))
{
var classWriter = new ClassWriter();
_classWriters[shortName] = classWriter;
_writer = classWriter.Head;
_writer.WriteLine("[:top:](#builtins)");
_writer.WriteLine();
_writer.WriteLine($"## `{shortName}` functions");
_writer.WriteLine();
base.VisitMember(member);
_writer = classWriter.Head;
_writer.WriteLine(_writerSummary);
_writer.WriteLine();
// Write the toc
_writerToc.WriteLine($"- [`{shortName}` functions](#{shortName}-functions)");
}
else if (methodInfo != null && IsBuiltinType(methodInfo.DeclaringType, out shortName) && methodInfo.IsPublic)
{
var methodShortName = StandardMemberRenamer.Default(methodInfo);
var classWriter = _classWriters[shortName];
// Write the toc
classWriter.Head.WriteLine($"- [`{shortName}.{methodShortName}`](#{shortName}{methodShortName})");
_writer = classWriter.Body;
_writer.WriteLine();
_writer.WriteLine("[:top:](#builtins)");
_writer.WriteLine($"### `{shortName}.{methodShortName}`");
_writer.WriteLine();
_writer.WriteLine("```");
_writer.Write($"{shortName}.{methodShortName}");
foreach (var parameter in methodInfo.GetParameters())
{
if (parameter.ParameterType == typeof(TemplateContext) || parameter.ParameterType == typeof(SourceSpan))
{
continue;
}
_writer.Write(" ");
_writer.Write($"<{parameter.Name}");
if (parameter.IsOptional)
{
var defaultValue = parameter.DefaultValue;
if (defaultValue is string)
{
defaultValue = "\"" + defaultValue + "\"";
}
if (defaultValue != null)
{
defaultValue = ": " + defaultValue;
}
_writer.Write($"{defaultValue}>?");
}
else
{
_writer.Write(">");
}
}
_writer.WriteLine();
_writer.WriteLine("```");
_writer.WriteLine();
base.VisitMember(member);
_writer = classWriter.Body;
// Write parameters after the signature
_writer.WriteLine("#### Description");
_writer.WriteLine();
_writer.WriteLine(_writerSummary);
_writer.WriteLine();
_writer.WriteLine("#### Arguments");
_writer.WriteLine();
_writer.WriteLine(_writerParameters);
_writer.WriteLine("#### Returns");
_writer.WriteLine();
_writer.WriteLine(_writerReturns);
_writer.WriteLine();
_writer.WriteLine("#### Examples");
_writer.WriteLine();
_writer.WriteLine(_writerRemarks);
}
_writerSummary = new StringWriter();
_writerParameters = new StringWriter();
_writerReturns = new StringWriter();
_writerRemarks = new StringWriter();
}
public override void VisitSummary(Summary summary)
{
_writer = _writerSummary;
base.VisitSummary(summary);
}
public override void VisitRemarks(Remarks remarks)
{
_writer = _writerRemarks;
base.VisitRemarks(remarks);
}
public override void VisitExample(Example example)
{
//base.VisitExample(example);
}
public override void VisitC(C code)
{
//// Wrap inline code in ` according to Markdown syntax.
//Console.Write(" `");
//Console.Write(code.Content);
//Console.Write("` ");
base.VisitC(code);
}
public override void VisitParam(Param param)
{
if (param.Name == "context" || param.Name == "span")
{
return;
}
_writer = _writerParameters;
_writer.Write($"- `{param.Name}`: ");
base.VisitParam(param);
_writer.WriteLine();
}
public override void VisitReturns(Returns returns)
{
_writer = _writerReturns;
base.VisitReturns(returns);
}
public override void VisitCode(Code code)
{
//base.VisitCode(code);
}
public override void VisitText(Text text)
{
var content = text.Content;
content = content.Replace("```scriban-html", "> **input**\r\n```scriban-html");
content = content.Replace("```html", "> **output**\r\n```html");
_writer.Write(content);
}
public override void VisitPara(Para para)
{
//base.VisitPara(para);
}
public override void VisitSee(See see)
{
//var cref = NormalizeLink(see.Cref);
//Console.Write(" [{0}]({1}) ", cref.Substring(2), cref);
}
public override void VisitSeeAlso(SeeAlso seeAlso)
{
//if (seeAlso.Cref != null)
//{
// var cref = NormalizeLink(seeAlso.Cref);
// Console.WriteLine("[{0}]({1})", cref.Substring(2), cref);
//}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) 2002 Ville Palo
// (C) 2003 Martin Willemoes Hansen
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using Xunit;
using System.Xml;
using System.Data.SqlTypes;
using System.Globalization;
using System.Xml.Serialization;
using System.IO;
namespace System.Data.Tests.SqlTypes
{
public class SqlDecimalTest
{
private CultureInfo _originalCulture;
private SqlDecimal _test1;
private SqlDecimal _test2;
private SqlDecimal _test3;
private SqlDecimal _test4;
private SqlDecimal _test5;
public SqlDecimalTest()
{
_test1 = new SqlDecimal(6464.6464m);
_test2 = new SqlDecimal(10000.00m);
_test3 = new SqlDecimal(10000.00m);
_test4 = new SqlDecimal(-6m);
_test5 = new SqlDecimal(decimal.MaxValue);
}
// Test constructor
[Fact]
public void Create()
{
// SqlDecimal (decimal)
SqlDecimal Test = new SqlDecimal(30.3098m);
Assert.Equal((decimal)30.3098, Test.Value);
try
{
decimal d = decimal.MaxValue;
SqlDecimal test = new SqlDecimal(d + 1);
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// SqlDecimal (double)
Test = new SqlDecimal(10E+10d);
Assert.Equal(100000000000.00000m, Test.Value);
try
{
SqlDecimal test = new SqlDecimal(10E+200d);
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// SqlDecimal (int)
Test = new SqlDecimal(-1);
Assert.Equal(-1m, Test.Value);
// SqlDecimal (long)
Test = new SqlDecimal((long)(-99999));
Assert.Equal(-99999m, Test.Value);
// SqlDecimal (byte, byte, bool. int[]
Test = new SqlDecimal(10, 3, false, new int[4] { 200, 1, 0, 0 });
Assert.Equal(-4294967.496m, Test.Value);
try
{
Test = new SqlDecimal(100, 100, false,
new int[4] {int.MaxValue,
int.MaxValue, int.MaxValue,
int.MaxValue});
Assert.False(true);
}
catch (SqlTypeException)
{
}
// sqlDecimal (byte, byte, bool, int, int, int, int)
Test = new SqlDecimal(12, 2, true, 100, 100, 0, 0);
Assert.Equal(4294967297.00m, Test.Value);
try
{
Test = new SqlDecimal(100, 100, false,
int.MaxValue,
int.MaxValue, int.MaxValue,
int.MaxValue);
Assert.False(true);
}
catch (SqlTypeException)
{
}
}
// Test public fields
[Fact]
public void PublicFields()
{
Assert.Equal((byte)38, SqlDecimal.MaxPrecision);
Assert.Equal((byte)38, SqlDecimal.MaxScale);
// FIXME: on windows: Conversion overflow
Assert.Equal(1262177448, SqlDecimal.MaxValue.Data[3]);
Assert.Equal(1262177448, SqlDecimal.MinValue.Data[3]);
Assert.True(SqlDecimal.Null.IsNull);
Assert.True(!_test1.IsNull);
}
// Test properties
[Fact]
public void Properties()
{
byte[] b = _test1.BinData;
Assert.Equal((byte)64, b[0]);
int[] i = _test1.Data;
Assert.Equal(64646464, i[0]);
Assert.True(SqlDecimal.Null.IsNull);
Assert.True(_test1.IsPositive);
Assert.True(!_test4.IsPositive);
Assert.Equal((byte)8, _test1.Precision);
Assert.Equal((byte)2, _test2.Scale);
Assert.Equal(6464.6464m, _test1.Value);
Assert.Equal((byte)4, _test1.Scale);
Assert.Equal((byte)7, _test2.Precision);
Assert.Equal((byte)1, _test4.Precision);
}
// PUBLIC METHODS
[Fact]
public void ArithmeticMethods()
{
// Abs
Assert.Equal(6m, SqlDecimal.Abs(_test4));
Assert.Equal(new SqlDecimal(6464.6464m).Value, SqlDecimal.Abs(_test1).Value);
Assert.Equal(SqlDecimal.Null, SqlDecimal.Abs(SqlDecimal.Null));
// Add()
SqlDecimal test2 = new SqlDecimal(-2000m);
Assert.Equal(16464.6464m, SqlDecimal.Add(_test1, _test2).Value);
Assert.Equal("158456325028528675187087900670", SqlDecimal.Add(_test5, _test5).ToString());
Assert.Equal(9994.00m, SqlDecimal.Add(_test3, _test4));
Assert.Equal(-2006m, SqlDecimal.Add(_test4, test2));
Assert.Equal(8000.00m, SqlDecimal.Add(test2, _test3));
try
{
SqlDecimal test = SqlDecimal.Add(SqlDecimal.MaxValue, SqlDecimal.MaxValue);
Assert.False(true);
}
catch (OverflowException)
{
}
Assert.Equal(6465m, SqlDecimal.Ceiling(_test1));
Assert.Equal(SqlDecimal.Null, SqlDecimal.Ceiling(SqlDecimal.Null));
// Divide() => Notworking
/*
Assert.Equal ((SqlDecimal)(-1077.441066m), SqlDecimal.Divide (Test1, Test4));
Assert.Equal (1.54687501546m, SqlDecimal.Divide (Test2, Test1).Value);
try {
SqlDecimal test = SqlDecimal.Divide(Test1, new SqlDecimal(0)).Value;
Assert.False(true);
} catch (DivideByZeroException e) {
Assert.Equal (typeof (DivideByZeroException), e.GetType ());
}
*/
Assert.Equal(6464m, SqlDecimal.Floor(_test1));
// Multiply()
SqlDecimal Test;
SqlDecimal test1 = new SqlDecimal(2m);
Assert.Equal(64646464.000000m, SqlDecimal.Multiply(_test1, _test2).Value);
Assert.Equal(-38787.8784m, SqlDecimal.Multiply(_test1, _test4).Value);
Test = SqlDecimal.Multiply(_test5, test1);
Assert.Equal("158456325028528675187087900670", Test.ToString());
try
{
SqlDecimal test = SqlDecimal.Multiply(SqlDecimal.MaxValue, _test1);
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// Power => NotWorking
//Assert.Equal ((SqlDecimal)41791653.0770m, SqlDecimal.Power (Test1, 2));
// Round
Assert.Equal(6464.65m, SqlDecimal.Round(_test1, 2));
// Subtract()
Assert.Equal(-3535.3536m, SqlDecimal.Subtract(_test1, _test3).Value);
Assert.Equal(10006.00m, SqlDecimal.Subtract(_test3, _test4).Value);
Assert.Equal("99999999920771837485735662406456049664", SqlDecimal.Subtract(SqlDecimal.MaxValue, decimal.MaxValue).ToString());
try
{
SqlDecimal test = SqlDecimal.Subtract(SqlDecimal.MinValue, SqlDecimal.MaxValue);
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
Assert.Equal(1, SqlDecimal.Sign(_test1));
Assert.Equal(new SqlInt32(-1), SqlDecimal.Sign(_test4));
}
[Fact]
public void AdjustScale()
{
Assert.Equal(6464.646400m.ToString(), SqlDecimal.AdjustScale(_test1, 2, false).Value.ToString());
Assert.Equal(6464.65.ToString(), SqlDecimal.AdjustScale(_test1, -2, true).Value.ToString());
Assert.Equal(6464.64.ToString(), SqlDecimal.AdjustScale(_test1, -2, false).Value.ToString());
Assert.Equal(10000.000000000000m.ToString(), SqlDecimal.AdjustScale(_test2, 10, false).Value.ToString());
Assert.Equal("79228162514264337593543950335.00", SqlDecimal.AdjustScale(_test5, 2, false).ToString());
try
{
SqlDecimal test = SqlDecimal.AdjustScale(_test1, -5, false);
Assert.False(true);
}
catch (SqlTruncateException)
{
}
}
[Fact]
public void ConvertToPrecScale()
{
Assert.Equal(new SqlDecimal(6464.6m).Value, SqlDecimal.ConvertToPrecScale(_test1, 5, 1).Value);
try
{
SqlDecimal test = SqlDecimal.ConvertToPrecScale(_test1, 6, 4);
Assert.False(true);
}
catch (SqlTruncateException e)
{
Assert.Equal(typeof(SqlTruncateException), e.GetType());
}
Assert.Equal("10000.00", SqlDecimal.ConvertToPrecScale(_test2, 7, 2).ToSqlString());
SqlDecimal tmp = new SqlDecimal(38, 4, true, 64646464, 0, 0, 0);
Assert.Equal("6465", SqlDecimal.ConvertToPrecScale(tmp, 4, 0).ToString());
}
[Fact]
public void CompareTo()
{
SqlString TestString = new SqlString("This is a test");
Assert.True(_test1.CompareTo(_test3) < 0);
Assert.True(_test2.CompareTo(_test1) > 0);
Assert.True(_test2.CompareTo(_test3) == 0);
Assert.True(_test4.CompareTo(SqlDecimal.Null) > 0);
try
{
_test1.CompareTo(TestString);
Assert.False(true);
}
catch (ArgumentException e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
}
}
[Fact]
public void EqualsMethods()
{
Assert.True(!_test1.Equals(_test2));
Assert.True(!_test2.Equals(new SqlString("TEST")));
Assert.True(_test2.Equals(_test3));
// Static Equals()-method
Assert.True(SqlDecimal.Equals(_test2, _test2).Value);
Assert.True(!SqlDecimal.Equals(_test1, _test2).Value);
// NotEquals
Assert.True(SqlDecimal.NotEquals(_test1, _test2).Value);
Assert.True(SqlDecimal.NotEquals(_test4, _test1).Value);
Assert.True(!SqlDecimal.NotEquals(_test2, _test3).Value);
Assert.True(SqlDecimal.NotEquals(SqlDecimal.Null, _test3).IsNull);
}
/* Don't do such environment-dependent test. It will never succeed under Portable.NET and MS.NET
[Fact]
public void GetHashCodeTest()
{
// FIXME: Better way to test HashCode
Assert.Equal (-1281249885, Test1.GetHashCode ());
}
*/
[Fact]
public void GetTypeTest()
{
Assert.Equal("System.Data.SqlTypes.SqlDecimal", _test1.GetType().ToString());
Assert.Equal("System.Decimal", _test1.Value.GetType().ToString());
}
[Fact]
public void Greaters()
{
// GreateThan ()
Assert.True(!SqlDecimal.GreaterThan(_test1, _test2).Value);
Assert.True(SqlDecimal.GreaterThan(_test2, _test1).Value);
Assert.True(!SqlDecimal.GreaterThan(_test2, _test3).Value);
// GreaterTharOrEqual ()
Assert.True(!SqlDecimal.GreaterThanOrEqual(_test1, _test2).Value);
Assert.True(SqlDecimal.GreaterThanOrEqual(_test2, _test1).Value);
Assert.True(SqlDecimal.GreaterThanOrEqual(_test2, _test3).Value);
}
[Fact]
public void Lessers()
{
// LessThan()
Assert.True(!SqlDecimal.LessThan(_test3, _test2).Value);
Assert.True(!SqlDecimal.LessThan(_test2, _test1).Value);
Assert.True(SqlDecimal.LessThan(_test1, _test2).Value);
// LessThanOrEqual ()
Assert.True(SqlDecimal.LessThanOrEqual(_test1, _test2).Value);
Assert.True(!SqlDecimal.LessThanOrEqual(_test2, _test1).Value);
Assert.True(SqlDecimal.LessThanOrEqual(_test2, _test3).Value);
Assert.True(SqlDecimal.LessThanOrEqual(_test1, SqlDecimal.Null).IsNull);
}
[Fact]
public void Conversions()
{
// ToDouble
Assert.Equal(6464.6464, _test1.ToDouble());
// ToSqlBoolean ()
Assert.Equal(new SqlBoolean(1), _test1.ToSqlBoolean());
SqlDecimal Test = new SqlDecimal(0);
Assert.True(!Test.ToSqlBoolean().Value);
Test = new SqlDecimal(0);
Assert.True(!Test.ToSqlBoolean().Value);
Assert.True(SqlDecimal.Null.ToSqlBoolean().IsNull);
// ToSqlByte ()
Test = new SqlDecimal(250);
Assert.Equal((byte)250, Test.ToSqlByte().Value);
try
{
SqlByte b = (byte)_test2.ToSqlByte();
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlDouble ()
Assert.Equal(6464.6464, _test1.ToSqlDouble());
// ToSqlInt16 ()
Assert.Equal((short)1, new SqlDecimal(1).ToSqlInt16().Value);
try
{
SqlInt16 test = SqlDecimal.MaxValue.ToSqlInt16().Value;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlInt32 ()
// LAMESPEC: 6464.6464 --> 64646464 ??? with windows
// MS.NET seems to return the first 32 bit integer (i.e.
// Data [0]) but we don't have to follow such stupidity.
// Assert.Equal ((int)64646464, Test1.ToSqlInt32 ().Value);
// Assert.Equal ((int)1212, new SqlDecimal(12.12m).ToSqlInt32 ().Value);
try
{
SqlInt32 test = SqlDecimal.MaxValue.ToSqlInt32().Value;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlInt64 ()
Assert.Equal(6464, _test1.ToSqlInt64().Value);
// ToSqlMoney ()
Assert.Equal((decimal)6464.6464, _test1.ToSqlMoney().Value);
try
{
SqlMoney test = SqlDecimal.MaxValue.ToSqlMoney().Value;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// ToSqlSingle ()
Assert.Equal((float)6464.6464, _test1.ToSqlSingle().Value);
// ToSqlString ()
Assert.Equal("6464.6464", _test1.ToSqlString().Value);
// ToString ()
Assert.Equal("6464.6464", _test1.ToString());
// NOT WORKING
Assert.Equal("792281625142643375935439503350000.00", SqlDecimal.Multiply(_test5, _test2).ToString());
Assert.Equal(1E+38, SqlDecimal.MaxValue.ToSqlDouble());
}
[Fact]
public void Truncate()
{
// NOT WORKING
Assert.Equal(new SqlDecimal(6464.6400m).Value, SqlDecimal.Truncate(_test1, 2).Value);
Assert.Equal(6464.6400m, SqlDecimal.Truncate(_test1, 2).Value);
}
// OPERATORS
[Fact]
public void ArithmeticOperators()
{
// "+"-operator
Assert.Equal(new SqlDecimal(16464.6464m), _test1 + _test2);
Assert.Equal("79228162514264337593543960335.00", (_test5 + _test3).ToString());
SqlDecimal test2 = new SqlDecimal(-2000m);
Assert.Equal(8000.00m, _test3 + test2);
Assert.Equal(-2006m, _test4 + test2);
Assert.Equal(8000.00m, test2 + _test3);
try
{
SqlDecimal test = SqlDecimal.MaxValue + SqlDecimal.MaxValue;
Assert.False(true);
}
catch (OverflowException) { }
// "/"-operator => NotWorking
//Assert.Equal ((SqlDecimal)1.54687501546m, Test2 / Test1);
try
{
SqlDecimal test = _test3 / new SqlDecimal(0);
Assert.False(true);
}
catch (DivideByZeroException e)
{
Assert.Equal(typeof(DivideByZeroException), e.GetType());
}
// "*"-operator
Assert.Equal(64646464.000000m, _test1 * _test2);
SqlDecimal Test = _test5 * (new SqlDecimal(2m));
Assert.Equal("158456325028528675187087900670", Test.ToString());
try
{
SqlDecimal test = SqlDecimal.MaxValue * _test1;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
// "-"-operator
Assert.Equal(3535.3536m, _test2 - _test1);
Assert.Equal(-10006.00m, _test4 - _test3);
try
{
SqlDecimal test = SqlDecimal.MinValue - SqlDecimal.MaxValue;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
Assert.Equal(SqlDecimal.Null, SqlDecimal.Null + _test1);
}
[Fact]
public void ThanOrEqualOperators()
{
SqlDecimal pval = new SqlDecimal(10m);
SqlDecimal nval = new SqlDecimal(-10m);
SqlDecimal val = new SqlDecimal(5m);
// == -operator
Assert.True((_test2 == _test3).Value);
Assert.True(!(_test1 == _test2).Value);
Assert.True((_test1 == SqlDecimal.Null).IsNull);
Assert.False((pval == nval).Value);
// != -operator
Assert.True(!(_test2 != _test3).Value);
Assert.True((_test1 != _test3).Value);
Assert.True((_test4 != _test3).Value);
Assert.True((_test1 != SqlDecimal.Null).IsNull);
Assert.True((pval != nval).Value);
// > -operator
Assert.True((_test2 > _test1).Value);
Assert.True(!(_test1 > _test3).Value);
Assert.True(!(_test2 > _test3).Value);
Assert.True((_test1 > SqlDecimal.Null).IsNull);
Assert.False((nval > val).Value);
// >= -operator
Assert.True(!(_test1 >= _test3).Value);
Assert.True((_test3 >= _test1).Value);
Assert.True((_test2 >= _test3).Value);
Assert.True((_test1 >= SqlDecimal.Null).IsNull);
Assert.False((nval > val).Value);
// < -operator
Assert.True(!(_test2 < _test1).Value);
Assert.True((_test1 < _test3).Value);
Assert.True(!(_test2 < _test3).Value);
Assert.True((_test1 < SqlDecimal.Null).IsNull);
Assert.False((val < nval).Value);
// <= -operator
Assert.True((_test1 <= _test3).Value);
Assert.True(!(_test3 <= _test1).Value);
Assert.True((_test2 <= _test3).Value);
Assert.True((_test1 <= SqlDecimal.Null).IsNull);
Assert.False((val <= nval).Value);
}
[Fact]
public void UnaryNegation()
{
Assert.Equal(6m, -_test4.Value);
Assert.Equal(-6464.6464m, -_test1.Value);
Assert.Equal(SqlDecimal.Null, SqlDecimal.Null);
}
[Fact]
public void SqlBooleanToSqlDecimal()
{
SqlBoolean TestBoolean = new SqlBoolean(true);
SqlDecimal Result;
Result = (SqlDecimal)TestBoolean;
Assert.Equal(1m, Result.Value);
Result = (SqlDecimal)SqlBoolean.Null;
Assert.True(Result.IsNull);
Assert.Equal(SqlDecimal.Null, (SqlDecimal)SqlBoolean.Null);
}
[Fact]
public void SqlDecimalToDecimal()
{
Assert.Equal(6464.6464m, (decimal)_test1);
}
[Fact]
public void SqlDoubleToSqlDecimal()
{
SqlDouble Test = new SqlDouble(12E+10);
Assert.Equal(120000000000.00000m, ((SqlDecimal)Test).Value);
}
[Fact]
public void SqlSingleToSqlDecimal()
{
SqlSingle Test = new SqlSingle(1E+9);
Assert.Equal(1000000000.0000000m, ((SqlDecimal)Test).Value);
try
{
SqlDecimal test = (SqlDecimal)SqlSingle.MaxValue;
Assert.False(true);
}
catch (OverflowException e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlStringToSqlDecimal()
{
SqlString TestString = new SqlString("Test string");
SqlString TestString100 = new SqlString("100");
Assert.Equal(100m, ((SqlDecimal)TestString100).Value);
try
{
SqlDecimal test = (SqlDecimal)TestString;
Assert.False(true);
}
catch (FormatException e)
{
Assert.Equal(typeof(FormatException), e.GetType());
}
try
{
SqlDecimal test = (SqlDecimal)new SqlString("9E+100");
Assert.False(true);
}
catch (FormatException e)
{
Assert.Equal(typeof(FormatException), e.GetType());
}
}
[Fact]
public void DecimalToSqlDecimal()
{
decimal d = 1000.1m;
Assert.Equal(1000.1m, (SqlDecimal)d);
}
[Fact]
public void ByteToSqlDecimal()
{
Assert.Equal(255m, ((SqlDecimal)SqlByte.MaxValue).Value);
}
[Fact]
public void SqlIntToSqlDouble()
{
SqlInt16 Test64 = new SqlInt16(64);
SqlInt32 Test640 = new SqlInt32(640);
SqlInt64 Test64000 = new SqlInt64(64000);
Assert.Equal(64m, ((SqlDecimal)Test64).Value);
Assert.Equal(640m, ((SqlDecimal)Test640).Value);
Assert.Equal(64000m, ((SqlDecimal)Test64000).Value);
}
[Fact]
public void SqlMoneyToSqlDecimal()
{
SqlMoney TestMoney64 = new SqlMoney(64);
Assert.Equal(64.0000M, ((SqlDecimal)TestMoney64).Value);
}
[Fact]
public void ToStringTest()
{
Assert.Equal("Null", SqlDecimal.Null.ToString());
Assert.Equal("-99999999999999999999999999999999999999", SqlDecimal.MinValue.ToString());
Assert.Equal("99999999999999999999999999999999999999", SqlDecimal.MaxValue.ToString());
}
[Fact]
public void Value()
{
decimal d = decimal.Parse("9999999999999999999999999999");
Assert.Equal(9999999999999999999999999999m, d);
}
[Fact]
public void GetXsdTypeTest()
{
XmlQualifiedName qualifiedName = SqlDecimal.GetXsdType(null);
Assert.Equal("decimal", qualifiedName.Name);
}
internal void ReadWriteXmlTestInternal(string xml,
decimal testval,
string unit_test_id)
{
SqlDecimal test;
SqlDecimal test1;
XmlSerializer ser;
StringWriter sw;
XmlTextWriter xw;
StringReader sr;
XmlTextReader xr;
test = new SqlDecimal(testval);
ser = new XmlSerializer(typeof(SqlDecimal));
sw = new StringWriter();
xw = new XmlTextWriter(sw);
ser.Serialize(xw, test);
// Assert.Equal (xml, sw.ToString ());
sr = new StringReader(xml);
xr = new XmlTextReader(sr);
test1 = (SqlDecimal)ser.Deserialize(xr);
Assert.Equal(testval, test1.Value);
}
[Fact]
//[Category ("MobileNotWorking")]
public void ReadWriteXmlTest()
{
string xml1 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><decimal>4556.89756</decimal>";
string xml2 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><decimal>-6445.9999</decimal>";
string xml3 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><decimal>0x455687AB3E4D56F</decimal>";
decimal test1 = new decimal(4556.89756);
// This one fails because of a possible conversion bug
//decimal test2 = new Decimal (-6445.999999999999999999999);
decimal test2 = new decimal(-6445.9999);
decimal test3 = new decimal(0x455687AB3E4D56F);
ReadWriteXmlTestInternal(xml1, test1, "BA01");
ReadWriteXmlTestInternal(xml2, test2, "BA02");
try
{
ReadWriteXmlTestInternal(xml3, test3, "BA03");
Assert.False(true);
}
catch (InvalidOperationException e)
{
Assert.Equal(typeof(FormatException), e.InnerException.GetType());
}
}
}
}
| |
//#define dbg_level_1
//#define dbg_level_2
#define dbg_controls
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Vexe.Editor.Helpers;
using Vexe.Runtime.Extensions;
using Vexe.Runtime.Helpers;
using Vexe.Runtime.Types;
using UnityObject = UnityEngine.Object;
namespace Vexe.Editor.GUIs
{
public class RabbitGUI : BaseGUI, IDisposable
{
public Action OnFinishedLayoutReserve, OnRepaint;
public float Height { private set; get; }
public float Width { private set; get; }
public override Rect LastRect
{
get
{
if (!_allocatedMemory)
return kDummyRect;
if (_nextControlIdx == 0)
throw new InvalidOperationException("Can't get last rect - there are no previous controls to get the last rect from");
if (_nextControlIdx - 1 >= _controls.Count)
{
#if dbg_level_1
Debug.Log("Last rect out of range. Returning dummy rect. If that's causing problems, maybe request a seek instead. nextControlIdx {0}. controls.Count {1}".FormatWith(_nextControlIdx, _controls.Count));
#endif
return kDummyRect; // or maybe request reset?
}
return _controls[_nextControlIdx - 1].rect;
}
}
private enum GUIPhase { Layout, Draw }
private GUIPhase _currentPhase;
private List<GUIControl> _controls;
private List<GUIBlock> _blocks;
private Stack<GUIBlock> _blockStack;
private Rect _startRect;
private Rect? _validRect;
private int _nextControlIdx;
private int _nextBlockIdx;
private float _prevInspectorWidth;
private bool _pendingLayout;
private bool _pendingRepaint;
private bool _allocatedMemory;
private bool _storedValidRect;
private int _id;
private static BetterPrefs _prefs;
private float _widthCorrection = 0f;
static MethodCaller<object, string> _scrollableTextArea;
static MethodCaller<object, Gradient> _gradientField;
#if dbg_level_1
private int dbgMaxDepth;
public static void LogCallStack()
{
string stack = RuntimeHelper.GetCallStack();
Debug.Log("Call stack: " + stack);
}
#endif
#if dbg_level_2
private bool m_pendingReset;
private bool _pendingReset
{
get { return m_pendingReset; }
set
{
if (value)
Debug.Log("Setting Reset Request to True! Came from: " + RuntimeHelper.GetCallStack());
m_pendingReset = value;
}
}
#else
private bool _pendingReset;
#endif
public RabbitGUI()
{
_currentPhase = GUIPhase.Layout;
_controls = new List<GUIControl>();
_blocks = new List<GUIBlock>();
_blockStack = new Stack<GUIBlock>();
_prefs = BetterPrefs.GetEditorInstance();
#if dbg_level_1
Debug.Log("Instantiated Rabbit");
#endif
}
static RabbitGUI()
{
var editorGUIType = typeof(EditorGUI);
// ScrollabeTextArea
{
var method = editorGUIType.GetMethod("ScrollableTextAreaInternal",
new Type[] { typeof(Rect), typeof(string), typeof(Vector2).MakeByRefType(), typeof(GUIStyle) },
Flags.StaticAnyVisibility);
_scrollableTextArea = method.DelegateForCall<object, string>();
}
// GradientField
{
var method = editorGUIType.GetMethod("GradientField",
new Type[] { typeof(GUIContent), typeof(Rect), typeof(Gradient) },
Flags.StaticAnyVisibility);
_gradientField = method.DelegateForCall<object, Gradient>();
}
}
void OnEditorUpdate()
{
if (!EditorApplication.isCompiling)
return;
StoreValidRect();
}
void OnPlaymodeChanged()
{
StoreValidRect();
}
void StoreValidRect()
{
if (!_storedValidRect && _validRect.HasValue)
{
var key = RuntimeHelper.CombineHashCodes(_id, "rabbit_coords");
_prefs.Vector3s[key] = new Vector3(_validRect.Value.x, _validRect.Value.y);
_storedValidRect = true;
}
}
public override void OnGUI(Action guiCode, Vector4 padding, int targetId)
{
_widthCorrection = padding.y;
_id = targetId;
if (!_validRect.HasValue)
{
var key = RuntimeHelper.CombineHashCodes(_id, "rabbit_coords");
Vector3 prevCoords;
if (_prefs.Vector3s.TryGetValue(key, out prevCoords))
{
//Log("Seems we changed play modes and rabbit doesn't have a coord. but we have in store a prev coord from a previous editor session that should work");
var tmp = new Rect();
tmp.x = prevCoords.x;
tmp.y = prevCoords.y;
_validRect = tmp;
}
}
var unityRect = GUILayoutUtility.GetRect(0f, 0f);
if (Event.current.type == EventType.Repaint)
{
if (!_validRect.HasValue || _validRect.Value.y != unityRect.y)
{
_validRect = unityRect;
_pendingLayout = true;
}
}
if (_validRect.HasValue)
{
var start = new Rect(_validRect.Value.x + padding.x, _validRect.Value.y + padding.z,
EditorGUIUtility.currentViewWidth - padding.y, _validRect.Value.height);
using (Begin(start))
guiCode();
}
GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth - 35f, Height - padding.w);
OnFinishedLayoutReserve.SafeInvoke();
}
public RabbitGUI Begin(Rect start)
{
if (_currentPhase == GUIPhase.Layout)
{
#if dbg_level_1
Debug.Log("Layout phase. Was pending layout: {0}. Was pending reset: {1}".FormatWith(_pendingLayout, _pendingReset));
#endif
Width = start.width;
Height = 0f;
_startRect = start;
_pendingLayout = false;
_pendingReset = false;
}
_nextControlIdx = 0;
_nextBlockIdx = 0;
BeginVertical(GUIStyles.None);
return this;
}
public override void OnEnable()
{
EditorApplication.playmodeStateChanged += OnPlaymodeChanged;
EditorApplication.update += OnEditorUpdate;
}
public override void OnDisable()
{
EditorApplication.playmodeStateChanged -= OnPlaymodeChanged;
EditorApplication.update -= OnEditorUpdate;
}
private void End()
{
_allocatedMemory = true;
var main = _blocks[0];
main.Dispose();
if (_currentPhase == GUIPhase.Layout)
{
main.ResetDimensions();
main.Layout(_startRect);
Height = main.height.Value;
_currentPhase = GUIPhase.Draw;
if (_pendingRepaint)
{
EditorHelper.RepaintAllInspectors();
OnRepaint.SafeInvoke();
_pendingRepaint = false;
}
#if dbg_level_1
Debug.Log("Done layout. Deepest Block depth: {0}. Total number of blocks created: {1}. Total number of controls {2}"
.FormatWith(dbgMaxDepth, _blocks.Count, _controls.Count));
#endif
}
else
{
if (_pendingReset || _nextControlIdx != _controls.Count || _nextBlockIdx != _blocks.Count)
{
#if dbg_level_1
if (_pendingReset)
Debug.Log("Resetting - Theres a reset request pending");
else Debug.Log("Resetting - The number of controls/blocks drawn doesn't match the total number of controls/blocks");
#endif
_controls.Clear();
_blocks.Clear();
_allocatedMemory = false;
_pendingRepaint = true;
_currentPhase = GUIPhase.Layout;
}
else if (_pendingLayout)
{
#if dbg_level_1
Debug.Log("Pending layout request. Doing layout in next phase");
#endif
_currentPhase = GUIPhase.Layout;
EditorHelper.RepaintAllInspectors();
}
else {
bool resized = _prevInspectorWidth != EditorGUIUtility.currentViewWidth + _widthCorrection;
if (resized)
{
#if dbg_level_1
Debug.Log("Resized inspector. Doing layout in next phase");
#endif
_prevInspectorWidth = EditorGUIUtility.currentViewWidth + _widthCorrection;
_currentPhase = GUIPhase.Layout;
}
}
}
}
private T BeginBlock<T>(GUIStyle style) where T : GUIBlock, new()
{
if (_pendingReset)
{
#if dbg_level_1
Debug.Log("Pending reset. Can't begin block of type: " + typeof(T).Name);
#endif
return null;
}
if (_allocatedMemory && _nextBlockIdx >= _blocks.Count)
{
#if dbg_level_1
Debug.Log("Requesting Reset. Can't begin block {0}. We seem to have created controls yet nextBlockIdx {1} > blocks.Count {2}"
.FormatWith(typeof(T).Name, _nextBlockIdx, _blocks.Count));
#endif
_pendingReset = true;
return null;
}
T result;
if (!_allocatedMemory)
{
_blocks.Add(result = new T
{
onDisposed = EndBlock,
data = new ControlData
{
type = typeof(T).Name.ParseEnum<ControlType>(),
style = style,
}
});
if (_blockStack.Count > 0)
{
var owner = _blockStack.Peek();
owner.AddBlock(result);
}
#if dbg_level_1
Debug.Log("Created new block of type {0}. Blocks count {1}. Is pending reset? {2}".FormatWith(typeof(T).Name, _blocks.Count, _pendingReset));
#endif
}
else
{
result = _blocks[_nextBlockIdx] as T;
if (result != null)
{
GUI.Box(result.rect, string.Empty, result.data.style = style);
}
else
{
var requestedType = typeof(T);
var resultType = _blocks[_nextBlockIdx].GetType();
if (requestedType != resultType)
{
#if dbg_level_1
Debug.Log("Requested block result is null. " +
"The type of block requested {0} doesn't match the block type {1} at index {2}. " +
"This is probably due to the occurance of new blocks revealed by a foldout for ex. " +
"Requesting Reset".FormatWith(requestedType.Name, resultType.Name, _nextBlockIdx));
#endif
_pendingReset = true;
return null;
}
#if dbg_level_1
Debug.Log("Result block is null. Count {0}, Idx {1}, Request type {2}".FormatWith(_blocks.Count, _nextBlockIdx, typeof(T).Name));
for (int i = 0; i < _blocks.Count; i++)
Debug.Log("Block {0} at {1} has {2} controls".FormatWith(_blocks[i].data.type.ToString(), i, _blocks[i].controls.Count));
Debug.Log("Block Stack count " + _blockStack.Count);
var array = _blockStack.ToArray();
for (int i = 0; i < array.Length; i++)
Debug.Log("Block {0} at {1} has {2} controls".FormatWith(array[i].data.type.ToString(), i, array[i].controls.Count));
#endif
throw new NullReferenceException("result");
}
}
_nextBlockIdx++;
_blockStack.Push(result);
#if dbg_level_2
Debug.Log("Pushed {0}. Stack {1}. Total {2}. Next {3}".FormatWith(result.GetType().Name, _blockStack.Count, _blocks.Count, _nextBlockIdx));
#endif
#if dbg_level_1
if (_blockStack.Count > dbgMaxDepth)
dbgMaxDepth = _blockStack.Count;
#endif
return result;
}
private void EndBlock()
{
if (!_pendingReset)
_blockStack.Pop();
}
private bool CanDrawControl(out Rect position, ControlData data)
{
position = kDummyRect;
if (_pendingReset)
{
#if dbg_level_1
Debug.Log("Can't draw control of type " + data.type + " There's a Reset pending.");
#endif
return false;
}
if (_nextControlIdx >= _controls.Count && _currentPhase == GUIPhase.Draw)
{
#if dbg_level_1
Debug.Log("Can't draw control of type {0} nextControlIdx {1} is >= controls.Count {2}. Requesting reset".FormatWith(data.type, _nextControlIdx, _controls.Count));
LogCallStack();
#endif
_pendingReset = true;
return false;
}
if (!_allocatedMemory)
{
NewControl(data);
return false;
}
position = _controls[_nextControlIdx++].rect;
return true;
}
private GUIControl NewControl(ControlData data)
{
var parent = _blockStack.Peek();
var control = new GUIControl(data);
parent.controls.Add(control);
_controls.Add(control);
#if dbg_level_2
Debug.Log("Created control {0}. Count {1}".FormatWith(data.type, _controls.Count));
#endif
return control;
}
public void RequestReset()
{
_pendingReset = true;
}
public void RequestLayout()
{
_pendingLayout = true;
}
void IDisposable.Dispose()
{
End();
}
public override IDisposable If(bool condition, IDisposable body)
{
if (condition)
return body;
body.Dispose();
return null;
}
public override Bounds BoundsField(GUIContent content, Bounds value, Layout option)
{
var bounds = new ControlData(content, GUIStyles.None, option, ControlType.Bounds);
Rect position;
if (CanDrawControl(out position, bounds))
{
return EditorGUI.BoundsField(position, content, value);
}
return value;
}
public override Rect Rect(GUIContent content, Rect value, Layout option)
{
var data = new ControlData(content, GUIStyles.None, option, ControlType.RectField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.RectField(position, content, value);
}
return value;
}
public override AnimationCurve Curve (GUIContent content, AnimationCurve value, Layout option)
{
var data = new ControlData (content, GUIStyles.None, option, ControlType.CurveField);
Rect position;
if (CanDrawControl (out position, data))
{
if(value == null)
value = new AnimationCurve();
return EditorGUI.CurveField(position, content, value);
}
return value;
}
public override Gradient GradientField(GUIContent content, Gradient value, Layout option)
{
var data = new ControlData(content, GUIStyles.None, option, ControlType.GradientField);
Rect position;
if (CanDrawControl(out position, data))
{
if (value == null)
value = new Gradient();
return _gradientField(null, new object[] { content, position, value });
}
return value;
}
public override void Box(GUIContent content, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.Box);
Rect position;
if (CanDrawControl(out position, data))
{
GUI.Box(position, content, style);
}
}
public override void HelpBox(string message, MessageType type)
{
var content = GetContent(message);
var height = GUIStyles.HelpBox.CalcHeight(content, Width);
var layout = Layout.sHeight(height);
var data = new ControlData(content, GUIStyles.HelpBox, layout, ControlType.HelpBox);
Rect position;
if (CanDrawControl(out position, data))
{
EditorGUI.HelpBox(position, message, type);
}
}
public override bool Button(GUIContent content, GUIStyle style, Layout option, ControlType buttonType)
{
var data = new ControlData(content, style, option, buttonType);
Rect position;
if (!CanDrawControl(out position, data))
return false;
#if dbg_controls
// due to the inability of unity's debugger to successfully break inside generic classes
// I'm forced to write things this way so I could break when I hit buttons in my drawers,
// since I can't break inside them cause they're generics... Unity...
var pressed = GUI.Button(position, content, style);
if (pressed)
return true;
return false;
#else
return GUI.Button(position, content, style);
#endif
}
public override Color Color(GUIContent content, Color value, Layout option)
{
var data = new ControlData(content, GUIStyles.ColorField, option, ControlType.ColorField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.ColorField(position, content, value);
}
return value;
}
public override Enum EnumPopup(GUIContent content, Enum selected, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.EnumPopup);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.EnumPopup(position, content, selected, style);
}
return selected;
}
public override float Float(GUIContent content, float value, Layout option)
{
var data = new ControlData(content, GUIStyles.NumberField, option, ControlType.Float);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.FloatField(position, content, value);
}
return value;
}
public override bool Foldout(GUIContent content, bool value, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.Foldout);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.Foldout(position, value, content, true, style);
}
return value;
}
public override int Int(GUIContent content, int value, Layout option)
{
var data = new ControlData(content, GUIStyles.NumberField, option, ControlType.IntField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.IntField(position, content, value);
}
return value;
}
public override void Label(GUIContent content, GUIStyle style, Layout option)
{
var label = new ControlData(content, style, option, ControlType.Label);
Rect position;
if (CanDrawControl(out position, label))
{
EditorGUI.LabelField(position, content, style);
}
}
public override int MaskField(GUIContent content, int mask, string[] displayedOptions, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.MaskField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.MaskField(position, content, mask, displayedOptions, style);
}
return mask;
}
public override UnityObject Object(GUIContent content, UnityObject value, Type type, bool allowSceneObjects, Layout option)
{
var data = new ControlData(content, GUIStyles.ObjectField, option, ControlType.ObjectField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.ObjectField(position, content, value, type, allowSceneObjects);
}
return value;
}
public override int Popup(string text, int selectedIndex, string[] displayedOptions, GUIStyle style, Layout option)
{
var content = GetContent(text);
var popup = new ControlData(content, style, option, ControlType.Popup);
Rect position;
if (CanDrawControl(out position, popup))
{
return EditorGUI.Popup(position, content.text, selectedIndex, displayedOptions, style);
}
return selectedIndex;
}
protected override void BeginScrollView(ref Vector2 pos, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background, Layout option)
{
throw new NotImplementedException("I need to implement ExpandWidth and ExpandHeight first, sorry");
}
protected override void EndScrollView()
{
throw new NotImplementedException();
}
public override float FloatSlider(GUIContent content, float value, float leftValue, float rightValue, Layout option)
{
var data = new ControlData(content, GUIStyles.HorizontalSlider, option, ControlType.Slider);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.Slider(position, content, value, leftValue, rightValue);
}
return value;
}
public override void Space(float pixels)
{
if (!_allocatedMemory)
{
var parent = _blockStack.Peek();
var option = parent.Space(pixels);
var space = new ControlData(GUIContent.none, GUIStyle.none, option, ControlType.Space);
NewControl(space);
}
else
{
_nextControlIdx++;
}
}
public override void FlexibleSpace()
{
if (!_allocatedMemory)
{
var flexible = new ControlData(GUIContent.none, GUIStyle.none, null, ControlType.FlexibleSpace);
NewControl(flexible);
}
else
{
_nextControlIdx++;
}
}
public override string Text(GUIContent content, string value, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.TextField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.TextField(position, content, value, style);
}
return value;
}
public override string ToolbarSearch(string value, Layout option)
{
var data = new ControlData(GetContent(value), GUIStyles.TextField, option, ControlType.TextField);
Rect position;
if (CanDrawControl(out position, data))
{
int searchMode = 0;
return GUIHelper.ToolbarSearchField(null, new object[] { position, null, searchMode, value }) as string;
}
return value;
}
public override bool ToggleLeft(GUIContent content, bool value, GUIStyle labelStyle, Layout option)
{
var data = new ControlData(content, labelStyle, option, ControlType.Toggle);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.ToggleLeft(position, content, value, labelStyle);
}
return value;
}
public override bool Toggle(GUIContent content, bool value, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.Toggle);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.Toggle(position, content, value, style);
}
return value;
}
protected override HorizontalBlock BeginHorizontal(GUIStyle style)
{
return BeginBlock<HorizontalBlock>(style);
}
protected override VerticalBlock BeginVertical(GUIStyle style)
{
return BeginBlock<VerticalBlock>(style);
}
protected override void EndHorizontal()
{
EndBlock();
}
protected override void EndVertical()
{
EndBlock();
}
public override string TextArea(string value, Layout option)
{
if (option == null)
option = new Layout();
if (!option.height.HasValue)
option.height = 50f;
var data = new ControlData(GetContent(value), GUIStyles.TextArea, option, ControlType.TextArea);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.TextArea(position, value);
}
return value;
}
public override bool InspectorTitlebar(bool foldout, UnityObject target)
{
var data = new ControlData(GUIContent.none, GUIStyles.None, null, ControlType.Foldout);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.InspectorTitlebar(position, foldout, target, true);
}
return foldout;
}
public override string Tag(GUIContent content, string tag, GUIStyle style, Layout layout)
{
var data = new ControlData(content, style, layout, ControlType.Popup);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.TagField(position, content, tag, style);
}
return tag;
}
public override int LayerField(GUIContent content, int layer, GUIStyle style, Layout layout)
{
var data = new ControlData(content, style, layout, ControlType.Popup);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.LayerField(position, content, layer, style);
}
return layer;
}
public override void Prefix(string label)
{
if (string.IsNullOrEmpty(label)) return;
var content = GetContent(label);
var style = EditorStyles.label;
var data = new ControlData(content, style, Layout.sWidth(EditorGUIUtility.labelWidth), ControlType.PrefixLabel);
Rect position;
if (CanDrawControl(out position, data))
{
EditorGUI.HandlePrefixLabel(position, position, content, 0, style);
}
}
public override string ScrollableTextArea(string value, ref Vector2 scrollPos, GUIStyle style, Layout option)
{
if (option == null)
option = Layout.None;
if (!option.height.HasValue)
option.height = 50f;
var content = GetContent(value);
var data = new ControlData(content, style, option, ControlType.TextArea);
Rect position;
if (CanDrawControl(out position, data))
{
var args = new object[] { position, value, scrollPos, style };
var newValue = _scrollableTextArea.Invoke(null, args);
scrollPos = (Vector2)args[2];
return newValue;
}
return value;
}
static bool hoveringOnPopup;
static readonly string[] emptyStringArray = new string[0];
public override string TextFieldDropDown(GUIContent label, string value, string[] dropDownElements, Layout option)
{
var data = new ControlData(label, GUIStyles.TextFieldDropDown, option, ControlType.TextFieldDropDown);
Rect totalRect;
if (CanDrawControl(out totalRect, data))
{
Rect textRect = new Rect(totalRect.x, totalRect.y, totalRect.width - GUIStyles.TextFieldDropDown.fixedWidth, totalRect.height);
Rect popupRect = new Rect(textRect.xMax, textRect.y, GUIStyles.TextFieldDropDown.fixedWidth, totalRect.height);
value = EditorGUI.TextField(textRect, "", value, GUIStyles.TextFieldDropDownText);
string[] displayedOptions;
if (dropDownElements.Length > 0)
displayedOptions = dropDownElements;
else
(displayedOptions = new string[1])[0] = "--empty--";
if (popupRect.Contains(Event.current.mousePosition))
hoveringOnPopup = true;
// if there were a lot of options to be displayed, we don't need to always invoke
// Popup cause Unity does a lot of allocation inside and it would have a huge negative impact
// on editor performance so we only display the options when we're hoving over it
if (!hoveringOnPopup)
EditorGUI.Popup(popupRect, string.Empty, -1, emptyStringArray, GUIStyles.TextFieldDropDown);
else
{
EditorGUI.BeginChangeCheck();
int selection = EditorGUI.Popup(popupRect, string.Empty, -1, displayedOptions, GUIStyles.TextFieldDropDown);
if (EditorGUI.EndChangeCheck() && displayedOptions.Length > 0)
{
hoveringOnPopup = false;
value = displayedOptions[selection];
}
}
}
return value;
}
public override double Double(GUIContent content, double value, Layout option)
{
var data = new ControlData(content, GUIStyles.NumberField, option, ControlType.Double);
Rect position;
if (CanDrawControl(out position, data))
return EditorGUI.DoubleField(position, content, value);
return value;
}
public override long Long(GUIContent content, long value, Layout option)
{
var data = new ControlData(content, GUIStyles.NumberField, option, ControlType.Long);
Rect position;
if (CanDrawControl(out position, data))
return EditorGUI.LongField(position, content, value);
return value;
}
public override void MinMaxSlider(GUIContent label, ref float minValue, ref float maxValue, float minLimit, float maxLimit, Layout option)
{
var data = new ControlData(label, GUIStyles.MinMaxSlider, option, ControlType.Slider);
Rect position;
if (CanDrawControl(out position, data))
EditorGUI.MinMaxSlider(label, position, ref minValue, ref maxValue, minLimit, maxLimit);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using FunWithSqlite.Models;
using FunWithSqlite.Models.ManageViewModels;
using FunWithSqlite.Services;
namespace FunWithSqlite.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly string _externalCookieScheme;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IOptions<IdentityCookieOptions> identityCookieOptions,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_externalCookieScheme = identityCookieOptions.Value.ExternalCookieAuthenticationScheme;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LinkLogin(string provider)
{
// Clear the existing external cookie to ensure a clean login process
await HttpContext.Authentication.SignOutAsync(_externalCookieScheme);
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action(nameof(LinkLoginCallback), "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = ManageMessageId.Error;
if (result.Succeeded)
{
message = ManageMessageId.AddLoginSuccess;
// Clear the existing external cookie to ensure a clean login process
await HttpContext.Authentication.SignOutAsync(_externalCookieScheme);
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Talent.V4
{
/// <summary>Settings for <see cref="EventServiceClient"/> instances.</summary>
public sealed partial class EventServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="EventServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="EventServiceSettings"/>.</returns>
public static EventServiceSettings GetDefault() => new EventServiceSettings();
/// <summary>Constructs a new <see cref="EventServiceSettings"/> object with default settings.</summary>
public EventServiceSettings()
{
}
private EventServiceSettings(EventServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CreateClientEventSettings = existing.CreateClientEventSettings;
OnCopy(existing);
}
partial void OnCopy(EventServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>EventServiceClient.CreateClientEvent</c> and <c>EventServiceClient.CreateClientEventAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 30 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateClientEventSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(30000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="EventServiceSettings"/> object.</returns>
public EventServiceSettings Clone() => new EventServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="EventServiceClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class EventServiceClientBuilder : gaxgrpc::ClientBuilderBase<EventServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public EventServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public EventServiceClientBuilder()
{
UseJwtAccessWithScopes = EventServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref EventServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<EventServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override EventServiceClient Build()
{
EventServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<EventServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<EventServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private EventServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return EventServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<EventServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return EventServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => EventServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => EventServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => EventServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>EventService client wrapper, for convenient use.</summary>
/// <remarks>
/// A service handles client event report.
/// </remarks>
public abstract partial class EventServiceClient
{
/// <summary>
/// The default endpoint for the EventService service, which is a host of "jobs.googleapis.com" and a port of
/// 443.
/// </summary>
public static string DefaultEndpoint { get; } = "jobs.googleapis.com:443";
/// <summary>The default EventService scopes.</summary>
/// <remarks>
/// The default EventService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/jobs</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/jobs",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="EventServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="EventServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="EventServiceClient"/>.</returns>
public static stt::Task<EventServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new EventServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="EventServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="EventServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="EventServiceClient"/>.</returns>
public static EventServiceClient Create() => new EventServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="EventServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="EventServiceSettings"/>.</param>
/// <returns>The created <see cref="EventServiceClient"/>.</returns>
internal static EventServiceClient Create(grpccore::CallInvoker callInvoker, EventServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
EventService.EventServiceClient grpcClient = new EventService.EventServiceClient(callInvoker);
return new EventServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC EventService client</summary>
public virtual EventService.EventServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ClientEvent CreateClientEvent(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(CreateClientEventRequest request, st::CancellationToken cancellationToken) =>
CreateClientEventAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ClientEvent CreateClientEvent(string parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEvent(new CreateClientEventRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(string parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEventAsync(new CreateClientEventRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(string parent, ClientEvent clientEvent, st::CancellationToken cancellationToken) =>
CreateClientEventAsync(parent, clientEvent, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ClientEvent CreateClientEvent(TenantName parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEvent(new CreateClientEventRequest
{
ParentAsTenantName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(TenantName parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEventAsync(new CreateClientEventRequest
{
ParentAsTenantName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(TenantName parent, ClientEvent clientEvent, st::CancellationToken cancellationToken) =>
CreateClientEventAsync(parent, clientEvent, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>EventService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A service handles client event report.
/// </remarks>
public sealed partial class EventServiceClientImpl : EventServiceClient
{
private readonly gaxgrpc::ApiCall<CreateClientEventRequest, ClientEvent> _callCreateClientEvent;
/// <summary>
/// Constructs a client wrapper for the EventService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="EventServiceSettings"/> used within this client.</param>
public EventServiceClientImpl(EventService.EventServiceClient grpcClient, EventServiceSettings settings)
{
GrpcClient = grpcClient;
EventServiceSettings effectiveSettings = settings ?? EventServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callCreateClientEvent = clientHelper.BuildApiCall<CreateClientEventRequest, ClientEvent>(grpcClient.CreateClientEventAsync, grpcClient.CreateClientEvent, effectiveSettings.CreateClientEventSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateClientEvent);
Modify_CreateClientEventApiCall(ref _callCreateClientEvent);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_CreateClientEventApiCall(ref gaxgrpc::ApiCall<CreateClientEventRequest, ClientEvent> call);
partial void OnConstruction(EventService.EventServiceClient grpcClient, EventServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC EventService client</summary>
public override EventService.EventServiceClient GrpcClient { get; }
partial void Modify_CreateClientEventRequest(ref CreateClientEventRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ClientEvent CreateClientEvent(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateClientEventRequest(ref request, ref callSettings);
return _callCreateClientEvent.Sync(request, callSettings);
}
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ClientEvent> CreateClientEventAsync(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateClientEventRequest(ref request, ref callSettings);
return _callCreateClientEvent.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Quartz.Util;
using Serilog.Core;
using Titan.Account;
using Titan.Logging;
using Titan.Meta;
using Titan.Util;
namespace Titan.Managers
{
public class ThreadManager
{
private Logger _log = LogCreator.Create();
private Dictionary<TitanAccount, Task> _taskDic = new Dictionary<TitanAccount, Task>();
private int _successCount; // Amount of accounts that successfully reported or commended
private int _failCount; // Amount of accounts that failed to report or commend
private int _count; // Amount of accounts that started reporting / commending
public void StartReport(TitanAccount account, ReportInfo info)
{
if (_taskDic.ContainsKey(account))
{
_log.Warning("Account is already reporting / commending. Aborting forcefully!");
FinishBotting(account);
}
account.FeedReportInfo(info);
_successCount = 0;
_failCount = 0;
_count = 0;
Titan.Instance.IsBotting = true;
_log.Debug("Starting reporting thread for {Target} in {Match} using account {Account}.",
info.SteamID, info.MatchID, account.JsonAccount.Username);
_taskDic.Add(account, Task.Run(() =>
{
var timedOut = false;
try
{
account.StartEpoch = DateTime.Now.ToEpochTime();
// Timeout on Sentry Account: 3min (so the user has enough time to input the 2FA code), else 60sec.
var origin = Task.Run(() => account.Start());
var result = origin.RunUntil(account.JsonAccount.Sentry
? TimeSpan.FromMinutes(3)
: TimeSpan.FromSeconds(60));
_count++;
switch (result.Result)
{
case Result.Success:
_successCount++;
break;
case Result.AlreadyLoggedInSomewhereElse:
_log.Error("Could not report with account {Account}. The account is " +
"already logged in somewhere else.", account.JsonAccount.Username);
_failCount++;
break;
case Result.AccountBanned:
_log.Error("Account {Account} has a cooldown on record. The report has been aborted.",
account.JsonAccount.Username);
_failCount++;
break;
case Result.NoMatches:
_log.Error("Could not receive match information for {Account}: User is not in live match.",
account._liveGameInfo.SteamID.ConvertToUInt64());
_failCount++;
break;
case Result.TimedOut:
_log.Error("Processing thread for {Account} has timed out.");
_failCount++;
break;
case Result.SentryRequired:
_log.Error("The account has 2FA enabled. Please set {sentry} to {true} " +
"in the accounts.json file.", "sentry", true);
_failCount++;
break;
case Result.RateLimit:
_log.Error("The Steam Rate Limit has been reached. Please try again in a " +
"few minutes.");
_failCount++;
break;
case Result.Code2FAWrong:
_log.Error("The provided SteamGuard code was wrong. Please retry.");
_failCount++;
break;
case Result.NoGame:
_log.Error("The bot account does not own the required app.");
_failCount++;
break;
default:
_failCount++;
break;
}
if (_count - _successCount - _failCount == 0)
{
if (_successCount == 0)
{
_log.Error("FAIL! Titan was not able to report target {Target}.",
info.SteamID.ConvertToUInt64());
Titan.Instance.UIManager.SendNotification(
"Titan", "Titan was not able to report your target."
);
if (Titan.Instance.ParsedObject != null)
{
Titan.Instance.IsBotting = false;
}
}
else
{
_log.Information(
"SUCCESS! Titan has successfully sent {Amount} out of {Fail} reports to target {Target}.",
_successCount, _count, info.SteamID.ConvertToUInt64());
Titan.Instance.UIManager.SendNotification(
"Titan", _successCount + " reports have been successfully sent!"
);
if (Titan.Instance.ParsedObject != null)
{
Titan.Instance.IsBotting = false;
}
}
}
}
catch (TimeoutException)
{
var timeSpent = DateTime.Now.Subtract(account.StartEpoch.ToDateTime());
_log.Error("Connection to account {Account} timed out. It was not possible to " +
"report the target after {Timespan} seconds.", account.JsonAccount.Username,
timeSpent.Seconds);
timedOut = true;
}
finally
{
if (timedOut)
{
account.Stop();
}
_taskDic.Remove(account);
}
}));
}
public void StartCommend(TitanAccount account, CommendInfo info)
{
if (_taskDic.ContainsKey(account))
{
_log.Warning("Account is already reporting / commending. Aborting forcefully!");
FinishBotting(account);
}
account.FeedCommendInfo(info);
_successCount = 0;
_failCount = 0;
_count = 0;
Titan.Instance.IsBotting = true;
_log.Debug("Starting commending thread for {Target} using account {Account}.",
info.SteamID, account.JsonAccount.Username);
_taskDic.Add(account, Task.Run(() =>
{
var timedOut = false;
try
{
account.StartEpoch = DateTime.Now.ToEpochTime();
// Timeout on Sentry Account: 3min (so the user has enough time to input the 2FA code), else 60sec.
var origin = Task.Run(() => account.Start());
var result = origin.RunUntil(account.JsonAccount.Sentry
? TimeSpan.FromMinutes(3)
: TimeSpan.FromSeconds(60));
_count++;
switch (result.Result)
{
case Result.Success:
_successCount++;
break;
case Result.AlreadyLoggedInSomewhereElse:
_log.Error("Could not commend with account {Account}. The account is " +
"already logged in somewhere else.", account.JsonAccount.Username);
_failCount++;
break;
case Result.AccountBanned:
_log.Error("Account {Account} has a cooldown on record. The report has been aborted.",
account.JsonAccount.Username);
_failCount++;
break;
case Result.TimedOut:
_log.Error("Processing thread for {Account} has timed out.");
_failCount++;
break;
case Result.SentryRequired:
_log.Error("The account has 2FA enabled. Please set {sentry} to {true} " +
"in the accounts.json file.", "sentry", true);
_failCount++;
break;
case Result.RateLimit:
_log.Error("The Steam Rate Limit has been reached. Please try again in a " +
"few minutes.");
_failCount++;
break;
case Result.Code2FAWrong:
_log.Error("The provided SteamGuard code was wrong. Please retry.");
_failCount++;
break;
default:
_failCount++;
break;
}
if (_count - _successCount - _failCount == 0)
{
if (_successCount == 0)
{
_log.Error("FAIL! Titan was not able to commend target {Target}.",
info.SteamID.ConvertToUInt64());
Titan.Instance.UIManager.SendNotification(
"Titan", "Titan was not able to commend your target."
);
if (Titan.Instance.ParsedObject != null)
{
Titan.Instance.IsBotting = false;
}
}
else
{
_log.Information(
"SUCCESS! Titan has successfully sent {Amount} out of {Fail} commends to target {Target}.",
_successCount, _count, info.SteamID.ConvertToUInt64());
Titan.Instance.UIManager.SendNotification(
"Titan", _successCount + " commends have been successfully sent!"
);
if (Titan.Instance.ParsedObject != null)
{
Titan.Instance.IsBotting = false;
}
}
}
}
catch (TimeoutException)
{
var timeSpent = DateTime.Now.Subtract(account.StartEpoch.ToDateTime());
_log.Error("Connection to account {Account} timed out. It was not possible to " +
"commend the target after {Timespan} seconds.", account.JsonAccount.Username,
timeSpent.Seconds);
timedOut = true;
}
finally
{
if (timedOut)
{
account.Stop();
}
_taskDic.Remove(account);
}
}));
}
public void StartMatchResolving(TitanAccount account, LiveGameInfo info)
{
if (_taskDic.ContainsKey(account))
{
_log.Warning("Account is already reporting / commending. Aborting forcefully!");
FinishBotting(account);
}
account.FeedLiveGameInfo(info);
_successCount = 0;
_failCount = 0;
_count = 0;
Titan.Instance.IsBotting = true;
_log.Debug("Starting Match ID resolving thread for {Target} using account {Account}.",
info.SteamID, account.JsonAccount.Username);
_taskDic.Add(account, Task.Run(() =>
{
var timedOut = false;
try
{
account.StartEpoch = DateTime.Now.ToEpochTime();
// Timeout on Sentry Account: 3min (so the user has enough time to input the 2FA code), else 60sec.
var origin = Task.Run(() => account.Start());
var result = origin.RunUntil(account.JsonAccount.Sentry
? TimeSpan.FromMinutes(3)
: TimeSpan.FromSeconds(60));
switch (result.Result)
{
case Result.Success:
_successCount++;
break;
case Result.AlreadyLoggedInSomewhereElse:
_log.Error("Could not resolve Match ID with account {Account}. The account is " +
"already logged in somewhere else.", account.JsonAccount.Username);
break;
case Result.TimedOut:
_log.Error("Processing thread for {Account} has timed out.");
break;
case Result.SentryRequired:
_log.Error("The account has 2FA enabled. Please set {sentry} to {true} " +
"in the accounts.json file.", "sentry", true);
break;
case Result.RateLimit:
_log.Error("The Steam Rate Limit has been reached. Please try again in a " +
"few minutes.");
break;
case Result.Code2FAWrong:
_log.Error("The provided SteamGuard code was wrong. Please retry.");
break;
}
}
catch (TimeoutException)
{
var timeSpent = DateTime.Now.Subtract(account.StartEpoch.ToDateTime());
_log.Error("Connection to account {Account} timed out. It was not possible to resolve the Match " +
"ID for the target after {Timespan} seconds.", account.JsonAccount.Username,
timeSpent.Seconds);
timedOut = true;
}
finally
{
if (timedOut)
{
account.Stop();
}
_taskDic.Remove(account);
}
}));
_successCount = 0;
}
public void FinishBotting(TitanAccount acc = null)
{
if (acc != null)
{
if (acc.IsRunning)
{
acc.Stop();
}
if (_taskDic.ContainsKey(acc))
{
_taskDic.Remove(acc);
}
}
else
{
foreach (var pair in _taskDic)
{
if (pair.Key.IsRunning || !pair.Value.IsCompleted)
{
pair.Key.Stop();
_log.Warning("Forcefully finished botting of account {account}.",
pair.Key.JsonAccount.Username);
}
_taskDic.Remove(pair.Key);
}
}
}
}
}
| |
using XenAdmin.Alerts;
using XenAdmin.Network;
using XenAdmin.Commands;
using XenAdmin.Controls;
using XenAdmin.Plugins;
using XenAPI;
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace XenAdmin
{
partial class MainWindow
{
/// <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)
{
Program.Exiting = true;
XenAdmin.Core.Clip.UnregisterClipboardViewer();
pluginManager.PluginsChanged -= pluginManager_PluginsChanged;
pluginManager.Dispose();
OtherConfigAndTagsWatcher.DeregisterEventHandlers();
ConnectionsManager.History.CollectionChanged -= History_CollectionChanged;
Alert.DeregisterAlertCollectionChanged(XenCenterAlerts_CollectionChanged);
XenAdmin.Core.Updates.DeregisterCollectionChanged(Updates_CollectionChanged);
ConnectionsManager.XenConnections.CollectionChanged -= XenConnection_CollectionChanged;
Properties.Settings.Default.SettingChanging -= new System.Configuration.SettingChangingEventHandler(Default_SettingChanging);
SearchPage.SearchChanged -= SearchPanel_SearchChanged;
if (disposing && (components != null))
{
components.Dispose();
log.Debug("MainWindow disoposing license timer");
if (licenseTimer != null)
licenseTimer.Dispose();
}
log.Debug("Before MainWindow base.Dispose()");
base.Dispose(disposing);
log.Debug("After MainWindow base.Dispose()");
}
#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(MainWindow));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.navigationPane = new XenAdmin.Controls.MainWindowControls.NavigationPane();
this.TheTabControl = new System.Windows.Forms.TabControl();
this.TabPageHome = new System.Windows.Forms.TabPage();
this.TabPageGeneral = new System.Windows.Forms.TabPage();
this.TabPageBallooning = new System.Windows.Forms.TabPage();
this.TabPageBallooningUpsell = new System.Windows.Forms.TabPage();
this.TabPageConsole = new System.Windows.Forms.TabPage();
this.TabPageCvmConsole = new System.Windows.Forms.TabPage();
this.TabPageStorage = new System.Windows.Forms.TabPage();
this.TabPagePhysicalStorage = new System.Windows.Forms.TabPage();
this.TabPageSR = new System.Windows.Forms.TabPage();
this.TabPageNetwork = new System.Windows.Forms.TabPage();
this.TabPageNICs = new System.Windows.Forms.TabPage();
this.TabPagePeformance = new System.Windows.Forms.TabPage();
this.TabPageHA = new System.Windows.Forms.TabPage();
this.TabPageHAUpsell = new System.Windows.Forms.TabPage();
this.TabPageSnapshots = new System.Windows.Forms.TabPage();
this.snapshotPage = new XenAdmin.TabPages.SnapshotsPage();
this.TabPageWLB = new System.Windows.Forms.TabPage();
this.TabPageWLBUpsell = new System.Windows.Forms.TabPage();
this.TabPageAD = new System.Windows.Forms.TabPage();
this.TabPageADUpsell = new System.Windows.Forms.TabPage();
this.TabPageGPU = new System.Windows.Forms.TabPage();
this.TabPagePvs = new System.Windows.Forms.TabPage();
this.TabPageSearch = new System.Windows.Forms.TabPage();
this.TabPageDockerProcess = new System.Windows.Forms.TabPage();
this.TabPageDockerDetails = new System.Windows.Forms.TabPage();
this.alertPage = new XenAdmin.TabPages.AlertSummaryPage();
this.updatesPage = new XenAdmin.TabPages.ManageUpdatesPage();
this.eventsPage = new XenAdmin.TabPages.HistoryPage();
this.TitleBackPanel = new XenAdmin.Controls.GradientPanel.GradientPanel();
this.TitleIcon = new System.Windows.Forms.PictureBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.TitleLabel = new System.Windows.Forms.Label();
this.LicenseStatusTitleLabel = new System.Windows.Forms.Label();
this.toolTipContainer1 = new XenAdmin.Controls.ToolTipContainer();
this.loggedInLabel1 = new XenAdmin.Controls.LoggedInLabel();
this.ToolStrip = new XenAdmin.Controls.ToolStripEx();
this.backButton = new System.Windows.Forms.ToolStripSplitButton();
this.forwardButton = new System.Windows.Forms.ToolStripSplitButton();
this.toolStripSeparator17 = new System.Windows.Forms.ToolStripSeparator();
this.AddServerToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
this.AddPoolToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.newStorageToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.NewVmToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator();
this.shutDownToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.powerOnHostToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.startVMToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.RebootToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.resumeToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.SuspendToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.ForceShutdownToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.ForceRebootToolbarButton = new XenAdmin.Commands.CommandToolStripButton();
this.stopContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.startContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.restartContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.resumeContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.pauseContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton();
this.statusToolTip = new System.Windows.Forms.ToolTip(this.components);
this.ToolBarContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.ShowToolbarMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.FileImportVMToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.importSearchToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator21 = new System.Windows.Forms.ToolStripSeparator();
this.importSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator31 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.customTemplatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.templatesToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.localStorageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ShowHiddenObjectsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator24 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolbarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.poolToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.AddPoolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.addServerToolStripMenuItem = new XenAdmin.Commands.AddHostToSelectedPoolToolStripMenuItem();
this.removeServerToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.poolReconnectAsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.disconnectPoolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator27 = new System.Windows.Forms.ToolStripSeparator();
this.virtualAppliancesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator30 = new System.Windows.Forms.ToolStripSeparator();
this.highAvailabilityToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.disasterRecoveryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.drConfigureToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.DrWizardToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.VMSnapshotScheduleToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.exportResourceReportPoolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.wlbReportsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.wlbDisconnectToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.changePoolPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.deleteToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator26 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.PoolPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.HostMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.AddHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripMenuItem11 = new System.Windows.Forms.ToolStripSeparator();
this.RebootHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.powerOnToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.ShutdownHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.restartToolstackToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.connectDisconnectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ReconnectToolStripMenuItem1 = new XenAdmin.Commands.CommandToolStripMenuItem();
this.DisconnectToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.reconnectAsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.connectAllToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.disconnectAllToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.addServerToPoolMenuItem = new XenAdmin.Commands.AddSelectedHostToPoolToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.backupToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.restoreFromBackupToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator23 = new System.Windows.Forms.ToolStripSeparator();
this.maintenanceModeToolStripMenuItem1 = new XenAdmin.Commands.CommandToolStripMenuItem();
this.controlDomainMemoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.RemoveCrashdumpsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.HostPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.ChangeRootPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.forgetSavedPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator25 = new System.Windows.Forms.ToolStripSeparator();
this.destroyServerToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.removeHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator15 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem();
this.ServerPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.VMToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.NewVmToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.startShutdownToolStripMenuItem = new XenAdmin.Commands.VMLifeCycleToolStripMenuItem();
this.resumeOnToolStripMenuItem = new XenAdmin.Commands.ResumeVMOnHostToolStripMenuItem();
this.relocateToolStripMenuItem = new XenAdmin.Commands.MigrateVMToolStripMenuItem();
this.startOnHostToolStripMenuItem = new XenAdmin.Commands.StartVMOnHostToolStripMenuItem();
this.toolStripSeparator20 = new System.Windows.Forms.ToolStripSeparator();
this.assignSnapshotScheduleToolStripMenuItem = new XenAdmin.Commands.AssignGroupToolStripMenuItemVMSS();
this.assignToVirtualApplianceToolStripMenuItem = new XenAdmin.Commands.AssignGroupToolStripMenuItemVM_appliance();
this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator();
this.copyVMtoSharedStorageMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.MoveVMToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.snapshotToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.convertToTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.exportToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.enablePVSReadcachingToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.disablePVSReadcachingToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripMenuItem12 = new System.Windows.Forms.ToolStripSeparator();
this.installToolsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.sendCtrlAltDelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.uninstallToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem();
this.VMPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripSeparator();
this.StorageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.AddStorageToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator22 = new System.Windows.Forms.ToolStripSeparator();
this.RepairStorageToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.DefaultSRToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.virtualDisksToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.addVirtualDiskToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.attachVirtualDiskToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.reclaimFreedSpacetripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator19 = new System.Windows.Forms.ToolStripSeparator();
this.DetachStorageToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.ReattachStorageRepositoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.ForgetStorageRepositoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.DestroyStorageRepositoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator18 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();
this.SRPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.templatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.CreateVmFromTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.newVMFromTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.InstantVmToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator29 = new System.Windows.Forms.ToolStripSeparator();
this.exportTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.duplicateTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator16 = new System.Windows.Forms.ToolStripSeparator();
this.uninstallTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator28 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem();
this.templatePropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.bugToolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.healthCheckToolStripMenuItem1 = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator14 = new System.Windows.Forms.ToolStripSeparator();
this.LicenseManagerMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator();
this.installNewUpdateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.rollingUpgradeToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem();
this.preferencesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.windowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pluginItemsPlaceHolderToolStripMenuItem9 = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpTopicsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem15 = new System.Windows.Forms.ToolStripSeparator();
this.viewApplicationLogToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem17 = new System.Windows.Forms.ToolStripSeparator();
this.xenSourceOnTheWebToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.xenCenterPluginsOnlineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.pluginItemsPlaceHolderToolStripMenuItem8 = new System.Windows.Forms.ToolStripMenuItem();
this.aboutXenSourceAdminToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MainMenuBar = new XenAdmin.Controls.MenuStripEx();
this.securityGroupsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
this.MenuPanel = new System.Windows.Forms.Panel();
this.StatusStrip = new System.Windows.Forms.StatusStrip();
this.statusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.statusProgressBar = new System.Windows.Forms.ToolStripProgressBar();
this.TabPageUSB = new System.Windows.Forms.TabPage();
this.disableCbtToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.TheTabControl.SuspendLayout();
this.TabPageSnapshots.SuspendLayout();
this.TitleBackPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.TitleIcon)).BeginInit();
this.tableLayoutPanel1.SuspendLayout();
this.toolTipContainer1.SuspendLayout();
this.ToolStrip.SuspendLayout();
this.ToolBarContextMenu.SuspendLayout();
this.MainMenuBar.SuspendLayout();
this.MenuPanel.SuspendLayout();
this.StatusStrip.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.BackColor = System.Drawing.SystemColors.Control;
resources.ApplyResources(this.splitContainer1, "splitContainer1");
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.navigationPane);
resources.ApplyResources(this.splitContainer1.Panel1, "splitContainer1.Panel1");
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.BackColor = System.Drawing.SystemColors.Control;
this.splitContainer1.Panel2.Controls.Add(this.TheTabControl);
this.splitContainer1.Panel2.Controls.Add(this.alertPage);
this.splitContainer1.Panel2.Controls.Add(this.updatesPage);
this.splitContainer1.Panel2.Controls.Add(this.eventsPage);
this.splitContainer1.Panel2.Controls.Add(this.TitleBackPanel);
resources.ApplyResources(this.splitContainer1.Panel2, "splitContainer1.Panel2");
this.splitContainer1.SplitterMoved += new System.Windows.Forms.SplitterEventHandler(this.splitContainer1_SplitterMoved);
//
// navigationPane
//
resources.ApplyResources(this.navigationPane, "navigationPane");
this.navigationPane.Name = "navigationPane";
this.navigationPane.NavigationModeChanged += new System.Action<XenAdmin.Controls.MainWindowControls.NavigationPane.NavigationMode>(this.navigationPane_NavigationModeChanged);
this.navigationPane.NotificationsSubModeChanged += new System.Action<XenAdmin.Controls.MainWindowControls.NotificationsSubModeItem>(this.navigationPane_NotificationsSubModeChanged);
this.navigationPane.TreeViewSelectionChanged += new System.Action(this.navigationPane_TreeViewSelectionChanged);
this.navigationPane.TreeNodeBeforeSelected += new System.Action(this.navigationPane_TreeNodeBeforeSelected);
this.navigationPane.TreeNodeClicked += new System.Action(this.navigationPane_TreeNodeClicked);
this.navigationPane.TreeNodeRightClicked += new System.Action(this.navigationPane_TreeNodeRightClicked);
this.navigationPane.TreeViewRefreshed += new System.Action(this.navigationPane_TreeViewRefreshed);
this.navigationPane.TreeViewRefreshSuspended += new System.Action(this.navigationPane_TreeViewRefreshSuspended);
this.navigationPane.TreeViewRefreshResumed += new System.Action(this.navigationPane_TreeViewRefreshResumed);
//
// TheTabControl
//
resources.ApplyResources(this.TheTabControl, "TheTabControl");
this.TheTabControl.Controls.Add(this.TabPageHome);
this.TheTabControl.Controls.Add(this.TabPageGeneral);
this.TheTabControl.Controls.Add(this.TabPageBallooning);
this.TheTabControl.Controls.Add(this.TabPageBallooningUpsell);
this.TheTabControl.Controls.Add(this.TabPageConsole);
this.TheTabControl.Controls.Add(this.TabPageCvmConsole);
this.TheTabControl.Controls.Add(this.TabPageStorage);
this.TheTabControl.Controls.Add(this.TabPagePhysicalStorage);
this.TheTabControl.Controls.Add(this.TabPageSR);
this.TheTabControl.Controls.Add(this.TabPageNetwork);
this.TheTabControl.Controls.Add(this.TabPageNICs);
this.TheTabControl.Controls.Add(this.TabPagePeformance);
this.TheTabControl.Controls.Add(this.TabPageHA);
this.TheTabControl.Controls.Add(this.TabPageHAUpsell);
this.TheTabControl.Controls.Add(this.TabPageSnapshots);
this.TheTabControl.Controls.Add(this.TabPageWLB);
this.TheTabControl.Controls.Add(this.TabPageWLBUpsell);
this.TheTabControl.Controls.Add(this.TabPageAD);
this.TheTabControl.Controls.Add(this.TabPageADUpsell);
this.TheTabControl.Controls.Add(this.TabPageGPU);
this.TheTabControl.Controls.Add(this.TabPagePvs);
this.TheTabControl.Controls.Add(this.TabPageSearch);
this.TheTabControl.Controls.Add(this.TabPageDockerProcess);
this.TheTabControl.Controls.Add(this.TabPageDockerDetails);
this.TheTabControl.Controls.Add(this.TabPageUSB);
this.TheTabControl.Name = "TheTabControl";
this.TheTabControl.SelectedIndex = 4;
//
// TabPageHome
//
resources.ApplyResources(this.TabPageHome, "TabPageHome");
this.TabPageHome.Name = "TabPageHome";
this.TabPageHome.UseVisualStyleBackColor = true;
//
// TabPageGeneral
//
resources.ApplyResources(this.TabPageGeneral, "TabPageGeneral");
this.TabPageGeneral.Name = "TabPageGeneral";
this.TabPageGeneral.UseVisualStyleBackColor = true;
//
// TabPageBallooning
//
resources.ApplyResources(this.TabPageBallooning, "TabPageBallooning");
this.TabPageBallooning.Name = "TabPageBallooning";
this.TabPageBallooning.UseVisualStyleBackColor = true;
//
// TabPageBallooningUpsell
//
resources.ApplyResources(this.TabPageBallooningUpsell, "TabPageBallooningUpsell");
this.TabPageBallooningUpsell.Name = "TabPageBallooningUpsell";
this.TabPageBallooningUpsell.UseVisualStyleBackColor = true;
//
// TabPageConsole
//
resources.ApplyResources(this.TabPageConsole, "TabPageConsole");
this.TabPageConsole.Name = "TabPageConsole";
this.TabPageConsole.UseVisualStyleBackColor = true;
//
// TabPageCvmConsole
//
resources.ApplyResources(this.TabPageCvmConsole, "TabPageCvmConsole");
this.TabPageCvmConsole.Name = "TabPageCvmConsole";
this.TabPageCvmConsole.UseVisualStyleBackColor = true;
//
// TabPageStorage
//
resources.ApplyResources(this.TabPageStorage, "TabPageStorage");
this.TabPageStorage.Name = "TabPageStorage";
this.TabPageStorage.UseVisualStyleBackColor = true;
//
// TabPagePhysicalStorage
//
resources.ApplyResources(this.TabPagePhysicalStorage, "TabPagePhysicalStorage");
this.TabPagePhysicalStorage.Name = "TabPagePhysicalStorage";
this.TabPagePhysicalStorage.UseVisualStyleBackColor = true;
//
// TabPageSR
//
resources.ApplyResources(this.TabPageSR, "TabPageSR");
this.TabPageSR.Name = "TabPageSR";
this.TabPageSR.UseVisualStyleBackColor = true;
//
// TabPageNetwork
//
resources.ApplyResources(this.TabPageNetwork, "TabPageNetwork");
this.TabPageNetwork.Name = "TabPageNetwork";
this.TabPageNetwork.UseVisualStyleBackColor = true;
//
// TabPageNICs
//
resources.ApplyResources(this.TabPageNICs, "TabPageNICs");
this.TabPageNICs.Name = "TabPageNICs";
this.TabPageNICs.UseVisualStyleBackColor = true;
//
// TabPagePeformance
//
resources.ApplyResources(this.TabPagePeformance, "TabPagePeformance");
this.TabPagePeformance.Name = "TabPagePeformance";
this.TabPagePeformance.UseVisualStyleBackColor = true;
//
// TabPageHA
//
resources.ApplyResources(this.TabPageHA, "TabPageHA");
this.TabPageHA.Name = "TabPageHA";
this.TabPageHA.UseVisualStyleBackColor = true;
//
// TabPageHAUpsell
//
resources.ApplyResources(this.TabPageHAUpsell, "TabPageHAUpsell");
this.TabPageHAUpsell.Name = "TabPageHAUpsell";
this.TabPageHAUpsell.UseVisualStyleBackColor = true;
//
// TabPageSnapshots
//
this.TabPageSnapshots.Controls.Add(this.snapshotPage);
resources.ApplyResources(this.TabPageSnapshots, "TabPageSnapshots");
this.TabPageSnapshots.Name = "TabPageSnapshots";
this.TabPageSnapshots.UseVisualStyleBackColor = true;
//
// snapshotPage
//
resources.ApplyResources(this.snapshotPage, "snapshotPage");
this.snapshotPage.Name = "snapshotPage";
this.snapshotPage.VM = null;
//
// TabPageWLB
//
resources.ApplyResources(this.TabPageWLB, "TabPageWLB");
this.TabPageWLB.Name = "TabPageWLB";
this.TabPageWLB.UseVisualStyleBackColor = true;
//
// TabPageWLBUpsell
//
resources.ApplyResources(this.TabPageWLBUpsell, "TabPageWLBUpsell");
this.TabPageWLBUpsell.Name = "TabPageWLBUpsell";
this.TabPageWLBUpsell.UseVisualStyleBackColor = true;
//
// TabPageAD
//
resources.ApplyResources(this.TabPageAD, "TabPageAD");
this.TabPageAD.Name = "TabPageAD";
this.TabPageAD.UseVisualStyleBackColor = true;
//
// TabPageADUpsell
//
resources.ApplyResources(this.TabPageADUpsell, "TabPageADUpsell");
this.TabPageADUpsell.Name = "TabPageADUpsell";
this.TabPageADUpsell.UseVisualStyleBackColor = true;
//
// TabPageGPU
//
resources.ApplyResources(this.TabPageGPU, "TabPageGPU");
this.TabPageGPU.Name = "TabPageGPU";
this.TabPageGPU.UseVisualStyleBackColor = true;
//
// TabPagePvs
//
resources.ApplyResources(this.TabPagePvs, "TabPagePvs");
this.TabPagePvs.Name = "TabPagePvs";
this.TabPagePvs.UseVisualStyleBackColor = true;
//
// TabPageSearch
//
resources.ApplyResources(this.TabPageSearch, "TabPageSearch");
this.TabPageSearch.Name = "TabPageSearch";
this.TabPageSearch.UseVisualStyleBackColor = true;
//
// TabPageDockerProcess
//
resources.ApplyResources(this.TabPageDockerProcess, "TabPageDockerProcess");
this.TabPageDockerProcess.Name = "TabPageDockerProcess";
this.TabPageDockerProcess.UseVisualStyleBackColor = true;
//
// TabPageDockerDetails
//
resources.ApplyResources(this.TabPageDockerDetails, "TabPageDockerDetails");
this.TabPageDockerDetails.Name = "TabPageDockerDetails";
this.TabPageDockerDetails.UseVisualStyleBackColor = true;
//
// alertPage
//
resources.ApplyResources(this.alertPage, "alertPage");
this.alertPage.BackColor = System.Drawing.SystemColors.Window;
this.alertPage.Name = "alertPage";
//
// updatesPage
//
resources.ApplyResources(this.updatesPage, "updatesPage");
this.updatesPage.BackColor = System.Drawing.SystemColors.Window;
this.updatesPage.Name = "updatesPage";
//
// eventsPage
//
resources.ApplyResources(this.eventsPage, "eventsPage");
this.eventsPage.BackColor = System.Drawing.SystemColors.Window;
this.eventsPage.Name = "eventsPage";
//
// TitleBackPanel
//
resources.ApplyResources(this.TitleBackPanel, "TitleBackPanel");
this.TitleBackPanel.BackColor = System.Drawing.Color.Transparent;
this.TitleBackPanel.Controls.Add(this.TitleIcon);
this.TitleBackPanel.Controls.Add(this.tableLayoutPanel1);
this.TitleBackPanel.Name = "TitleBackPanel";
this.TitleBackPanel.Scheme = XenAdmin.Controls.GradientPanel.GradientPanel.Schemes.Title;
//
// TitleIcon
//
resources.ApplyResources(this.TitleIcon, "TitleIcon");
this.TitleIcon.Name = "TitleIcon";
this.TitleIcon.TabStop = false;
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.TitleLabel, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.LicenseStatusTitleLabel, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.toolTipContainer1, 3, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// TitleLabel
//
resources.ApplyResources(this.TitleLabel, "TitleLabel");
this.TitleLabel.AutoEllipsis = true;
this.TitleLabel.ForeColor = System.Drawing.SystemColors.HighlightText;
this.TitleLabel.Name = "TitleLabel";
this.TitleLabel.UseMnemonic = false;
//
// LicenseStatusTitleLabel
//
resources.ApplyResources(this.LicenseStatusTitleLabel, "LicenseStatusTitleLabel");
this.LicenseStatusTitleLabel.ForeColor = System.Drawing.SystemColors.HighlightText;
this.LicenseStatusTitleLabel.Name = "LicenseStatusTitleLabel";
this.LicenseStatusTitleLabel.UseMnemonic = false;
//
// toolTipContainer1
//
resources.ApplyResources(this.toolTipContainer1, "toolTipContainer1");
this.toolTipContainer1.Controls.Add(this.loggedInLabel1);
this.toolTipContainer1.Name = "toolTipContainer1";
//
// loggedInLabel1
//
resources.ApplyResources(this.loggedInLabel1, "loggedInLabel1");
this.loggedInLabel1.BackColor = System.Drawing.Color.Transparent;
this.loggedInLabel1.Connection = null;
this.loggedInLabel1.Name = "loggedInLabel1";
//
// ToolStrip
//
resources.ApplyResources(this.ToolStrip, "ToolStrip");
this.ToolStrip.ClickThrough = true;
this.ToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.ToolStrip.ImageScalingSize = new System.Drawing.Size(24, 24);
this.ToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.backButton,
this.forwardButton,
this.toolStripSeparator17,
this.AddServerToolbarButton,
this.toolStripSeparator11,
this.AddPoolToolbarButton,
this.newStorageToolbarButton,
this.NewVmToolbarButton,
this.toolStripSeparator12,
this.shutDownToolStripButton,
this.powerOnHostToolStripButton,
this.startVMToolStripButton,
this.RebootToolbarButton,
this.resumeToolStripButton,
this.SuspendToolbarButton,
this.ForceShutdownToolbarButton,
this.ForceRebootToolbarButton,
this.stopContainerToolStripButton,
this.startContainerToolStripButton,
this.restartContainerToolStripButton,
this.resumeContainerToolStripButton,
this.pauseContainerToolStripButton});
this.ToolStrip.Name = "ToolStrip";
this.ToolStrip.Stretch = true;
this.ToolStrip.TabStop = true;
this.ToolStrip.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MainMenuBar_MouseClick);
//
// backButton
//
this.backButton.Image = global::XenAdmin.Properties.Resources._001_Back_h32bit_24;
resources.ApplyResources(this.backButton, "backButton");
this.backButton.Name = "backButton";
this.backButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.backButton.ButtonClick += new System.EventHandler(this.backButton_Click);
this.backButton.DropDownOpening += new System.EventHandler(this.backButton_DropDownOpening);
//
// forwardButton
//
this.forwardButton.Image = global::XenAdmin.Properties.Resources._001_Forward_h32bit_24;
resources.ApplyResources(this.forwardButton, "forwardButton");
this.forwardButton.Margin = new System.Windows.Forms.Padding(0, 2, 0, 2);
this.forwardButton.Name = "forwardButton";
this.forwardButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.forwardButton.ButtonClick += new System.EventHandler(this.forwardButton_Click);
this.forwardButton.DropDownOpening += new System.EventHandler(this.forwardButton_DropDownOpening);
//
// toolStripSeparator17
//
resources.ApplyResources(this.toolStripSeparator17, "toolStripSeparator17");
this.toolStripSeparator17.Margin = new System.Windows.Forms.Padding(2, 0, 7, 0);
this.toolStripSeparator17.Name = "toolStripSeparator17";
this.toolStripSeparator17.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// AddServerToolbarButton
//
this.AddServerToolbarButton.Command = new XenAdmin.Commands.AddHostCommand();
resources.ApplyResources(this.AddServerToolbarButton, "AddServerToolbarButton");
this.AddServerToolbarButton.Image = global::XenAdmin.Properties.Resources._000_AddApplicationServer_h32bit_24;
this.AddServerToolbarButton.Name = "AddServerToolbarButton";
this.AddServerToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// toolStripSeparator11
//
resources.ApplyResources(this.toolStripSeparator11, "toolStripSeparator11");
this.toolStripSeparator11.Margin = new System.Windows.Forms.Padding(2, 0, 7, 0);
this.toolStripSeparator11.Name = "toolStripSeparator11";
this.toolStripSeparator11.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// AddPoolToolbarButton
//
this.AddPoolToolbarButton.Command = new XenAdmin.Commands.NewPoolCommand();
resources.ApplyResources(this.AddPoolToolbarButton, "AddPoolToolbarButton");
this.AddPoolToolbarButton.Image = global::XenAdmin.Properties.Resources._000_PoolNew_h32bit_24;
this.AddPoolToolbarButton.Name = "AddPoolToolbarButton";
this.AddPoolToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// newStorageToolbarButton
//
this.newStorageToolbarButton.Command = new XenAdmin.Commands.NewSRCommand();
resources.ApplyResources(this.newStorageToolbarButton, "newStorageToolbarButton");
this.newStorageToolbarButton.Image = global::XenAdmin.Properties.Resources._000_NewStorage_h32bit_24;
this.newStorageToolbarButton.Name = "newStorageToolbarButton";
this.newStorageToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// NewVmToolbarButton
//
this.NewVmToolbarButton.Command = new XenAdmin.Commands.NewVMCommand();
resources.ApplyResources(this.NewVmToolbarButton, "NewVmToolbarButton");
this.NewVmToolbarButton.Image = global::XenAdmin.Properties.Resources._000_CreateVM_h32bit_24;
this.NewVmToolbarButton.Name = "NewVmToolbarButton";
this.NewVmToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// toolStripSeparator12
//
resources.ApplyResources(this.toolStripSeparator12, "toolStripSeparator12");
this.toolStripSeparator12.Margin = new System.Windows.Forms.Padding(2, 0, 7, 0);
this.toolStripSeparator12.Name = "toolStripSeparator12";
//
// shutDownToolStripButton
//
this.shutDownToolStripButton.Command = new XenAdmin.Commands.ShutDownCommand();
resources.ApplyResources(this.shutDownToolStripButton, "shutDownToolStripButton");
this.shutDownToolStripButton.Name = "shutDownToolStripButton";
//
// powerOnHostToolStripButton
//
this.powerOnHostToolStripButton.Command = new XenAdmin.Commands.PowerOnHostCommand();
resources.ApplyResources(this.powerOnHostToolStripButton, "powerOnHostToolStripButton");
this.powerOnHostToolStripButton.Name = "powerOnHostToolStripButton";
//
// startVMToolStripButton
//
this.startVMToolStripButton.Command = new XenAdmin.Commands.StartVMCommand();
resources.ApplyResources(this.startVMToolStripButton, "startVMToolStripButton");
this.startVMToolStripButton.Name = "startVMToolStripButton";
//
// RebootToolbarButton
//
this.RebootToolbarButton.Command = new XenAdmin.Commands.RebootCommand();
resources.ApplyResources(this.RebootToolbarButton, "RebootToolbarButton");
this.RebootToolbarButton.Name = "RebootToolbarButton";
//
// resumeToolStripButton
//
this.resumeToolStripButton.Command = new XenAdmin.Commands.ResumeVMCommand();
resources.ApplyResources(this.resumeToolStripButton, "resumeToolStripButton");
this.resumeToolStripButton.Image = global::XenAdmin.Properties.Resources._000_Paused_h32bit_24;
this.resumeToolStripButton.Name = "resumeToolStripButton";
//
// SuspendToolbarButton
//
this.SuspendToolbarButton.Command = new XenAdmin.Commands.SuspendVMCommand();
resources.ApplyResources(this.SuspendToolbarButton, "SuspendToolbarButton");
this.SuspendToolbarButton.Image = global::XenAdmin.Properties.Resources._000_Paused_h32bit_24;
this.SuspendToolbarButton.Name = "SuspendToolbarButton";
//
// ForceShutdownToolbarButton
//
this.ForceShutdownToolbarButton.Command = new XenAdmin.Commands.ForceVMShutDownCommand();
resources.ApplyResources(this.ForceShutdownToolbarButton, "ForceShutdownToolbarButton");
this.ForceShutdownToolbarButton.Image = global::XenAdmin.Properties.Resources._001_ForceShutDown_h32bit_24;
this.ForceShutdownToolbarButton.Name = "ForceShutdownToolbarButton";
//
// ForceRebootToolbarButton
//
this.ForceRebootToolbarButton.Command = new XenAdmin.Commands.ForceVMRebootCommand();
resources.ApplyResources(this.ForceRebootToolbarButton, "ForceRebootToolbarButton");
this.ForceRebootToolbarButton.Image = global::XenAdmin.Properties.Resources._001_ForceReboot_h32bit_24;
this.ForceRebootToolbarButton.Name = "ForceRebootToolbarButton";
//
// stopContainerToolStripButton
//
this.stopContainerToolStripButton.Command = new XenAdmin.Commands.StopDockerContainerCommand();
resources.ApplyResources(this.stopContainerToolStripButton, "stopContainerToolStripButton");
this.stopContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._001_ShutDown_h32bit_24;
this.stopContainerToolStripButton.Name = "stopContainerToolStripButton";
//
// startContainerToolStripButton
//
this.startContainerToolStripButton.Command = new XenAdmin.Commands.StartDockerContainerCommand();
resources.ApplyResources(this.startContainerToolStripButton, "startContainerToolStripButton");
this.startContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._001_PowerOn_h32bit_24;
this.startContainerToolStripButton.Name = "startContainerToolStripButton";
//
// restartContainerToolStripButton
//
this.restartContainerToolStripButton.Command = new XenAdmin.Commands.RestartDockerContainerCommand();
resources.ApplyResources(this.restartContainerToolStripButton, "restartContainerToolStripButton");
this.restartContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._001_Reboot_h32bit_24;
this.restartContainerToolStripButton.Name = "restartContainerToolStripButton";
//
// resumeContainerToolStripButton
//
this.resumeContainerToolStripButton.Command = new XenAdmin.Commands.ResumeDockerContainerCommand();
resources.ApplyResources(this.resumeContainerToolStripButton, "resumeContainerToolStripButton");
this.resumeContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._000_Resumed_h32bit_24;
this.resumeContainerToolStripButton.Name = "resumeContainerToolStripButton";
//
// pauseContainerToolStripButton
//
this.pauseContainerToolStripButton.Command = new XenAdmin.Commands.PauseDockerContainerCommand();
resources.ApplyResources(this.pauseContainerToolStripButton, "pauseContainerToolStripButton");
this.pauseContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._000_Paused_h32bit_24;
this.pauseContainerToolStripButton.Name = "pauseContainerToolStripButton";
//
// ToolBarContextMenu
//
this.ToolBarContextMenu.ImageScalingSize = new System.Drawing.Size(40, 40);
this.ToolBarContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ShowToolbarMenuItem});
this.ToolBarContextMenu.Name = "ToolBarContextMenu";
resources.ApplyResources(this.ToolBarContextMenu, "ToolBarContextMenu");
//
// ShowToolbarMenuItem
//
this.ShowToolbarMenuItem.Checked = true;
this.ShowToolbarMenuItem.CheckOnClick = true;
this.ShowToolbarMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.ShowToolbarMenuItem.Name = "ShowToolbarMenuItem";
resources.ApplyResources(this.ShowToolbarMenuItem, "ShowToolbarMenuItem");
this.ShowToolbarMenuItem.Click += new System.EventHandler(this.ShowToolbarMenuItem_Click);
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileImportVMToolStripMenuItem,
this.importSearchToolStripMenuItem,
this.toolStripSeparator21,
this.importSettingsToolStripMenuItem,
this.exportSettingsToolStripMenuItem,
this.toolStripSeparator31,
this.pluginItemsPlaceHolderToolStripMenuItem1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// FileImportVMToolStripMenuItem
//
this.FileImportVMToolStripMenuItem.Command = new XenAdmin.Commands.ImportCommand();
this.FileImportVMToolStripMenuItem.Name = "FileImportVMToolStripMenuItem";
resources.ApplyResources(this.FileImportVMToolStripMenuItem, "FileImportVMToolStripMenuItem");
//
// importSearchToolStripMenuItem
//
this.importSearchToolStripMenuItem.Command = new XenAdmin.Commands.ImportSearchCommand();
this.importSearchToolStripMenuItem.Name = "importSearchToolStripMenuItem";
resources.ApplyResources(this.importSearchToolStripMenuItem, "importSearchToolStripMenuItem");
//
// toolStripSeparator21
//
this.toolStripSeparator21.Name = "toolStripSeparator21";
resources.ApplyResources(this.toolStripSeparator21, "toolStripSeparator21");
//
// importSettingsToolStripMenuItem
//
this.importSettingsToolStripMenuItem.Name = "importSettingsToolStripMenuItem";
resources.ApplyResources(this.importSettingsToolStripMenuItem, "importSettingsToolStripMenuItem");
this.importSettingsToolStripMenuItem.Click += new System.EventHandler(this.importSettingsToolStripMenuItem_Click);
//
// exportSettingsToolStripMenuItem
//
this.exportSettingsToolStripMenuItem.Name = "exportSettingsToolStripMenuItem";
resources.ApplyResources(this.exportSettingsToolStripMenuItem, "exportSettingsToolStripMenuItem");
this.exportSettingsToolStripMenuItem.Click += new System.EventHandler(this.exportSettingsToolStripMenuItem_Click);
//
// toolStripSeparator31
//
this.toolStripSeparator31.Name = "toolStripSeparator31";
resources.ApplyResources(this.toolStripSeparator31, "toolStripSeparator31");
//
// pluginItemsPlaceHolderToolStripMenuItem1
//
this.pluginItemsPlaceHolderToolStripMenuItem1.Name = "pluginItemsPlaceHolderToolStripMenuItem1";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem1, "pluginItemsPlaceHolderToolStripMenuItem1");
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem");
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.customTemplatesToolStripMenuItem,
this.templatesToolStripMenuItem1,
this.localStorageToolStripMenuItem,
this.ShowHiddenObjectsToolStripMenuItem,
this.toolStripSeparator24,
this.pluginItemsPlaceHolderToolStripMenuItem,
this.toolbarToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
resources.ApplyResources(this.viewToolStripMenuItem, "viewToolStripMenuItem");
//
// customTemplatesToolStripMenuItem
//
this.customTemplatesToolStripMenuItem.Name = "customTemplatesToolStripMenuItem";
resources.ApplyResources(this.customTemplatesToolStripMenuItem, "customTemplatesToolStripMenuItem");
this.customTemplatesToolStripMenuItem.Click += new System.EventHandler(this.customTemplatesToolStripMenuItem_Click);
//
// templatesToolStripMenuItem1
//
this.templatesToolStripMenuItem1.Name = "templatesToolStripMenuItem1";
resources.ApplyResources(this.templatesToolStripMenuItem1, "templatesToolStripMenuItem1");
this.templatesToolStripMenuItem1.Click += new System.EventHandler(this.templatesToolStripMenuItem1_Click);
//
// localStorageToolStripMenuItem
//
this.localStorageToolStripMenuItem.Name = "localStorageToolStripMenuItem";
resources.ApplyResources(this.localStorageToolStripMenuItem, "localStorageToolStripMenuItem");
this.localStorageToolStripMenuItem.Click += new System.EventHandler(this.localStorageToolStripMenuItem_Click);
//
// ShowHiddenObjectsToolStripMenuItem
//
this.ShowHiddenObjectsToolStripMenuItem.Name = "ShowHiddenObjectsToolStripMenuItem";
resources.ApplyResources(this.ShowHiddenObjectsToolStripMenuItem, "ShowHiddenObjectsToolStripMenuItem");
this.ShowHiddenObjectsToolStripMenuItem.Click += new System.EventHandler(this.ShowHiddenObjectsToolStripMenuItem_Click);
//
// toolStripSeparator24
//
this.toolStripSeparator24.Name = "toolStripSeparator24";
resources.ApplyResources(this.toolStripSeparator24, "toolStripSeparator24");
//
// pluginItemsPlaceHolderToolStripMenuItem
//
this.pluginItemsPlaceHolderToolStripMenuItem.Name = "pluginItemsPlaceHolderToolStripMenuItem";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem, "pluginItemsPlaceHolderToolStripMenuItem");
//
// toolbarToolStripMenuItem
//
this.toolbarToolStripMenuItem.Name = "toolbarToolStripMenuItem";
resources.ApplyResources(this.toolbarToolStripMenuItem, "toolbarToolStripMenuItem");
this.toolbarToolStripMenuItem.Click += new System.EventHandler(this.ShowToolbarMenuItem_Click);
//
// poolToolStripMenuItem
//
this.poolToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AddPoolToolStripMenuItem,
this.toolStripSeparator8,
this.addServerToolStripMenuItem,
this.removeServerToolStripMenuItem,
this.poolReconnectAsToolStripMenuItem,
this.disconnectPoolToolStripMenuItem,
this.toolStripSeparator27,
this.virtualAppliancesToolStripMenuItem,
this.toolStripSeparator30,
this.highAvailabilityToolStripMenuItem,
this.disasterRecoveryToolStripMenuItem,
this.VMSnapshotScheduleToolStripMenuItem,
this.exportResourceReportPoolToolStripMenuItem,
this.wlbReportsToolStripMenuItem,
this.wlbDisconnectToolStripMenuItem,
this.toolStripSeparator9,
this.changePoolPasswordToolStripMenuItem,
this.toolStripMenuItem1,
this.deleteToolStripMenuItem,
this.toolStripSeparator26,
this.pluginItemsPlaceHolderToolStripMenuItem2,
this.PoolPropertiesToolStripMenuItem});
this.poolToolStripMenuItem.Name = "poolToolStripMenuItem";
resources.ApplyResources(this.poolToolStripMenuItem, "poolToolStripMenuItem");
//
// AddPoolToolStripMenuItem
//
this.AddPoolToolStripMenuItem.Command = new XenAdmin.Commands.NewPoolCommand();
this.AddPoolToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_PoolNew_h32bit_16;
this.AddPoolToolStripMenuItem.Name = "AddPoolToolStripMenuItem";
resources.ApplyResources(this.AddPoolToolStripMenuItem, "AddPoolToolStripMenuItem");
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
resources.ApplyResources(this.toolStripSeparator8, "toolStripSeparator8");
//
// addServerToolStripMenuItem
//
this.addServerToolStripMenuItem.Name = "addServerToolStripMenuItem";
resources.ApplyResources(this.addServerToolStripMenuItem, "addServerToolStripMenuItem");
//
// removeServerToolStripMenuItem
//
this.removeServerToolStripMenuItem.Command = new XenAdmin.Commands.RemoveHostFromPoolCommand();
this.removeServerToolStripMenuItem.Name = "removeServerToolStripMenuItem";
resources.ApplyResources(this.removeServerToolStripMenuItem, "removeServerToolStripMenuItem");
//
// poolReconnectAsToolStripMenuItem
//
this.poolReconnectAsToolStripMenuItem.Command = new XenAdmin.Commands.PoolReconnectAsCommand();
this.poolReconnectAsToolStripMenuItem.Name = "poolReconnectAsToolStripMenuItem";
resources.ApplyResources(this.poolReconnectAsToolStripMenuItem, "poolReconnectAsToolStripMenuItem");
//
// disconnectPoolToolStripMenuItem
//
this.disconnectPoolToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectPoolCommand();
this.disconnectPoolToolStripMenuItem.Name = "disconnectPoolToolStripMenuItem";
resources.ApplyResources(this.disconnectPoolToolStripMenuItem, "disconnectPoolToolStripMenuItem");
//
// toolStripSeparator27
//
this.toolStripSeparator27.Name = "toolStripSeparator27";
resources.ApplyResources(this.toolStripSeparator27, "toolStripSeparator27");
//
// virtualAppliancesToolStripMenuItem
//
this.virtualAppliancesToolStripMenuItem.Command = new XenAdmin.Commands.VMGroupCommandVM_appliance();
this.virtualAppliancesToolStripMenuItem.Name = "virtualAppliancesToolStripMenuItem";
resources.ApplyResources(this.virtualAppliancesToolStripMenuItem, "virtualAppliancesToolStripMenuItem");
//
// toolStripSeparator30
//
this.toolStripSeparator30.Name = "toolStripSeparator30";
resources.ApplyResources(this.toolStripSeparator30, "toolStripSeparator30");
//
// highAvailabilityToolStripMenuItem
//
this.highAvailabilityToolStripMenuItem.Command = new XenAdmin.Commands.HACommand();
this.highAvailabilityToolStripMenuItem.Name = "highAvailabilityToolStripMenuItem";
resources.ApplyResources(this.highAvailabilityToolStripMenuItem, "highAvailabilityToolStripMenuItem");
//
// disasterRecoveryToolStripMenuItem
//
this.disasterRecoveryToolStripMenuItem.Command = new XenAdmin.Commands.DRCommand();
this.disasterRecoveryToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.drConfigureToolStripMenuItem,
this.DrWizardToolStripMenuItem});
this.disasterRecoveryToolStripMenuItem.Name = "disasterRecoveryToolStripMenuItem";
resources.ApplyResources(this.disasterRecoveryToolStripMenuItem, "disasterRecoveryToolStripMenuItem");
//
// drConfigureToolStripMenuItem
//
this.drConfigureToolStripMenuItem.Command = new XenAdmin.Commands.DRConfigureCommand();
this.drConfigureToolStripMenuItem.Name = "drConfigureToolStripMenuItem";
resources.ApplyResources(this.drConfigureToolStripMenuItem, "drConfigureToolStripMenuItem");
//
// DrWizardToolStripMenuItem
//
this.DrWizardToolStripMenuItem.Command = new XenAdmin.Commands.DisasterRecoveryCommand();
this.DrWizardToolStripMenuItem.Name = "DrWizardToolStripMenuItem";
resources.ApplyResources(this.DrWizardToolStripMenuItem, "DrWizardToolStripMenuItem");
//
// VMSnapshotScheduleToolStripMenuItem
//
this.VMSnapshotScheduleToolStripMenuItem.Command = new XenAdmin.Commands.VMGroupCommandVMSS();
this.VMSnapshotScheduleToolStripMenuItem.Name = "VMSnapshotScheduleToolStripMenuItem";
resources.ApplyResources(this.VMSnapshotScheduleToolStripMenuItem, "VMSnapshotScheduleToolStripMenuItem");
//
// exportResourceReportPoolToolStripMenuItem
//
this.exportResourceReportPoolToolStripMenuItem.Command = new XenAdmin.Commands.ExportResourceReportCommand();
this.exportResourceReportPoolToolStripMenuItem.Name = "exportResourceReportPoolToolStripMenuItem";
resources.ApplyResources(this.exportResourceReportPoolToolStripMenuItem, "exportResourceReportPoolToolStripMenuItem");
//
// wlbReportsToolStripMenuItem
//
this.wlbReportsToolStripMenuItem.Command = new XenAdmin.Commands.ViewWorkloadReportsCommand();
this.wlbReportsToolStripMenuItem.Name = "wlbReportsToolStripMenuItem";
resources.ApplyResources(this.wlbReportsToolStripMenuItem, "wlbReportsToolStripMenuItem");
//
// wlbDisconnectToolStripMenuItem
//
this.wlbDisconnectToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectWlbServerCommand();
this.wlbDisconnectToolStripMenuItem.Name = "wlbDisconnectToolStripMenuItem";
resources.ApplyResources(this.wlbDisconnectToolStripMenuItem, "wlbDisconnectToolStripMenuItem");
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
resources.ApplyResources(this.toolStripSeparator9, "toolStripSeparator9");
//
// changePoolPasswordToolStripMenuItem
//
this.changePoolPasswordToolStripMenuItem.Command = new XenAdmin.Commands.ChangeHostPasswordCommand();
this.changePoolPasswordToolStripMenuItem.Name = "changePoolPasswordToolStripMenuItem";
resources.ApplyResources(this.changePoolPasswordToolStripMenuItem, "changePoolPasswordToolStripMenuItem");
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1");
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Command = new XenAdmin.Commands.DeletePoolCommand();
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
resources.ApplyResources(this.deleteToolStripMenuItem, "deleteToolStripMenuItem");
//
// toolStripSeparator26
//
this.toolStripSeparator26.Name = "toolStripSeparator26";
resources.ApplyResources(this.toolStripSeparator26, "toolStripSeparator26");
//
// pluginItemsPlaceHolderToolStripMenuItem2
//
this.pluginItemsPlaceHolderToolStripMenuItem2.Name = "pluginItemsPlaceHolderToolStripMenuItem2";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem2, "pluginItemsPlaceHolderToolStripMenuItem2");
//
// PoolPropertiesToolStripMenuItem
//
this.PoolPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.PoolPropertiesCommand();
this.PoolPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
this.PoolPropertiesToolStripMenuItem.Name = "PoolPropertiesToolStripMenuItem";
resources.ApplyResources(this.PoolPropertiesToolStripMenuItem, "PoolPropertiesToolStripMenuItem");
//
// HostMenuItem
//
this.HostMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AddHostToolStripMenuItem,
this.toolStripMenuItem11,
this.RebootHostToolStripMenuItem,
this.powerOnToolStripMenuItem,
this.ShutdownHostToolStripMenuItem,
this.restartToolstackToolStripMenuItem,
this.toolStripSeparator1,
this.connectDisconnectToolStripMenuItem,
this.addServerToPoolMenuItem,
this.toolStripSeparator3,
this.backupToolStripMenuItem,
this.restoreFromBackupToolStripMenuItem,
this.toolStripSeparator23,
this.maintenanceModeToolStripMenuItem1,
this.controlDomainMemoryToolStripMenuItem,
this.RemoveCrashdumpsToolStripMenuItem,
this.HostPasswordToolStripMenuItem,
this.toolStripSeparator25,
this.destroyServerToolStripMenuItem,
this.removeHostToolStripMenuItem,
this.toolStripSeparator15,
this.pluginItemsPlaceHolderToolStripMenuItem3,
this.ServerPropertiesToolStripMenuItem});
this.HostMenuItem.Name = "HostMenuItem";
resources.ApplyResources(this.HostMenuItem, "HostMenuItem");
//
// AddHostToolStripMenuItem
//
this.AddHostToolStripMenuItem.Command = new XenAdmin.Commands.AddHostCommand();
this.AddHostToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_AddApplicationServer_h32bit_16;
this.AddHostToolStripMenuItem.Name = "AddHostToolStripMenuItem";
resources.ApplyResources(this.AddHostToolStripMenuItem, "AddHostToolStripMenuItem");
//
// toolStripMenuItem11
//
this.toolStripMenuItem11.Name = "toolStripMenuItem11";
resources.ApplyResources(this.toolStripMenuItem11, "toolStripMenuItem11");
//
// RebootHostToolStripMenuItem
//
this.RebootHostToolStripMenuItem.Command = new XenAdmin.Commands.RebootHostCommand();
this.RebootHostToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_Reboot_h32bit_16;
this.RebootHostToolStripMenuItem.Name = "RebootHostToolStripMenuItem";
resources.ApplyResources(this.RebootHostToolStripMenuItem, "RebootHostToolStripMenuItem");
//
// powerOnToolStripMenuItem
//
this.powerOnToolStripMenuItem.Command = new XenAdmin.Commands.PowerOnHostCommand();
resources.ApplyResources(this.powerOnToolStripMenuItem, "powerOnToolStripMenuItem");
this.powerOnToolStripMenuItem.Name = "powerOnToolStripMenuItem";
//
// ShutdownHostToolStripMenuItem
//
this.ShutdownHostToolStripMenuItem.Command = new XenAdmin.Commands.ShutDownHostCommand();
resources.ApplyResources(this.ShutdownHostToolStripMenuItem, "ShutdownHostToolStripMenuItem");
this.ShutdownHostToolStripMenuItem.Name = "ShutdownHostToolStripMenuItem";
//
// restartToolstackToolStripMenuItem
//
this.restartToolstackToolStripMenuItem.Command = new XenAdmin.Commands.RestartToolstackCommand();
this.restartToolstackToolStripMenuItem.Name = "restartToolstackToolStripMenuItem";
resources.ApplyResources(this.restartToolstackToolStripMenuItem, "restartToolstackToolStripMenuItem");
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// connectDisconnectToolStripMenuItem
//
this.connectDisconnectToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ReconnectToolStripMenuItem1,
this.DisconnectToolStripMenuItem,
this.reconnectAsToolStripMenuItem,
this.toolStripSeparator4,
this.connectAllToolStripMenuItem,
this.disconnectAllToolStripMenuItem});
this.connectDisconnectToolStripMenuItem.Name = "connectDisconnectToolStripMenuItem";
resources.ApplyResources(this.connectDisconnectToolStripMenuItem, "connectDisconnectToolStripMenuItem");
//
// ReconnectToolStripMenuItem1
//
this.ReconnectToolStripMenuItem1.Command = new XenAdmin.Commands.ReconnectHostCommand();
this.ReconnectToolStripMenuItem1.Name = "ReconnectToolStripMenuItem1";
resources.ApplyResources(this.ReconnectToolStripMenuItem1, "ReconnectToolStripMenuItem1");
//
// DisconnectToolStripMenuItem
//
this.DisconnectToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectHostCommand();
this.DisconnectToolStripMenuItem.Name = "DisconnectToolStripMenuItem";
resources.ApplyResources(this.DisconnectToolStripMenuItem, "DisconnectToolStripMenuItem");
//
// reconnectAsToolStripMenuItem
//
this.reconnectAsToolStripMenuItem.Command = new XenAdmin.Commands.HostReconnectAsCommand();
this.reconnectAsToolStripMenuItem.Name = "reconnectAsToolStripMenuItem";
resources.ApplyResources(this.reconnectAsToolStripMenuItem, "reconnectAsToolStripMenuItem");
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// connectAllToolStripMenuItem
//
this.connectAllToolStripMenuItem.Command = new XenAdmin.Commands.ConnectAllHostsCommand();
this.connectAllToolStripMenuItem.Name = "connectAllToolStripMenuItem";
resources.ApplyResources(this.connectAllToolStripMenuItem, "connectAllToolStripMenuItem");
//
// disconnectAllToolStripMenuItem
//
this.disconnectAllToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectAllHostsCommand();
this.disconnectAllToolStripMenuItem.Name = "disconnectAllToolStripMenuItem";
resources.ApplyResources(this.disconnectAllToolStripMenuItem, "disconnectAllToolStripMenuItem");
//
// addServerToPoolMenuItem
//
this.addServerToPoolMenuItem.Name = "addServerToPoolMenuItem";
resources.ApplyResources(this.addServerToPoolMenuItem, "addServerToPoolMenuItem");
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// backupToolStripMenuItem
//
this.backupToolStripMenuItem.Command = new XenAdmin.Commands.BackupHostCommand();
this.backupToolStripMenuItem.Name = "backupToolStripMenuItem";
resources.ApplyResources(this.backupToolStripMenuItem, "backupToolStripMenuItem");
//
// restoreFromBackupToolStripMenuItem
//
this.restoreFromBackupToolStripMenuItem.Command = new XenAdmin.Commands.RestoreHostFromBackupCommand();
this.restoreFromBackupToolStripMenuItem.Name = "restoreFromBackupToolStripMenuItem";
resources.ApplyResources(this.restoreFromBackupToolStripMenuItem, "restoreFromBackupToolStripMenuItem");
//
// toolStripSeparator23
//
this.toolStripSeparator23.Name = "toolStripSeparator23";
resources.ApplyResources(this.toolStripSeparator23, "toolStripSeparator23");
//
// maintenanceModeToolStripMenuItem1
//
this.maintenanceModeToolStripMenuItem1.Command = new XenAdmin.Commands.HostMaintenanceModeCommand();
this.maintenanceModeToolStripMenuItem1.Name = "maintenanceModeToolStripMenuItem1";
resources.ApplyResources(this.maintenanceModeToolStripMenuItem1, "maintenanceModeToolStripMenuItem1");
//
// controlDomainMemoryToolStripMenuItem
//
this.controlDomainMemoryToolStripMenuItem.Command = new XenAdmin.Commands.ChangeControlDomainMemoryCommand();
this.controlDomainMemoryToolStripMenuItem.Name = "controlDomainMemoryToolStripMenuItem";
resources.ApplyResources(this.controlDomainMemoryToolStripMenuItem, "controlDomainMemoryToolStripMenuItem");
//
// RemoveCrashdumpsToolStripMenuItem
//
this.RemoveCrashdumpsToolStripMenuItem.Command = new XenAdmin.Commands.RemoveHostCrashDumpsCommand();
this.RemoveCrashdumpsToolStripMenuItem.Name = "RemoveCrashdumpsToolStripMenuItem";
resources.ApplyResources(this.RemoveCrashdumpsToolStripMenuItem, "RemoveCrashdumpsToolStripMenuItem");
//
// HostPasswordToolStripMenuItem
//
this.HostPasswordToolStripMenuItem.Command = new XenAdmin.Commands.HostPasswordCommand();
this.HostPasswordToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ChangeRootPasswordToolStripMenuItem,
this.forgetSavedPasswordToolStripMenuItem});
this.HostPasswordToolStripMenuItem.Name = "HostPasswordToolStripMenuItem";
resources.ApplyResources(this.HostPasswordToolStripMenuItem, "HostPasswordToolStripMenuItem");
//
// ChangeRootPasswordToolStripMenuItem
//
this.ChangeRootPasswordToolStripMenuItem.Command = new XenAdmin.Commands.ChangeHostPasswordCommand();
this.ChangeRootPasswordToolStripMenuItem.Name = "ChangeRootPasswordToolStripMenuItem";
resources.ApplyResources(this.ChangeRootPasswordToolStripMenuItem, "ChangeRootPasswordToolStripMenuItem");
//
// forgetSavedPasswordToolStripMenuItem
//
this.forgetSavedPasswordToolStripMenuItem.Command = new XenAdmin.Commands.ForgetSavedPasswordCommand();
this.forgetSavedPasswordToolStripMenuItem.Name = "forgetSavedPasswordToolStripMenuItem";
resources.ApplyResources(this.forgetSavedPasswordToolStripMenuItem, "forgetSavedPasswordToolStripMenuItem");
//
// toolStripSeparator25
//
this.toolStripSeparator25.Name = "toolStripSeparator25";
resources.ApplyResources(this.toolStripSeparator25, "toolStripSeparator25");
//
// destroyServerToolStripMenuItem
//
this.destroyServerToolStripMenuItem.Command = new XenAdmin.Commands.DestroyHostCommand();
this.destroyServerToolStripMenuItem.Name = "destroyServerToolStripMenuItem";
resources.ApplyResources(this.destroyServerToolStripMenuItem, "destroyServerToolStripMenuItem");
//
// removeHostToolStripMenuItem
//
this.removeHostToolStripMenuItem.Command = new XenAdmin.Commands.RemoveHostCommand();
this.removeHostToolStripMenuItem.Name = "removeHostToolStripMenuItem";
resources.ApplyResources(this.removeHostToolStripMenuItem, "removeHostToolStripMenuItem");
//
// toolStripSeparator15
//
this.toolStripSeparator15.Name = "toolStripSeparator15";
resources.ApplyResources(this.toolStripSeparator15, "toolStripSeparator15");
//
// pluginItemsPlaceHolderToolStripMenuItem3
//
this.pluginItemsPlaceHolderToolStripMenuItem3.Name = "pluginItemsPlaceHolderToolStripMenuItem3";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem3, "pluginItemsPlaceHolderToolStripMenuItem3");
//
// ServerPropertiesToolStripMenuItem
//
this.ServerPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.HostPropertiesCommand();
this.ServerPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
this.ServerPropertiesToolStripMenuItem.Name = "ServerPropertiesToolStripMenuItem";
resources.ApplyResources(this.ServerPropertiesToolStripMenuItem, "ServerPropertiesToolStripMenuItem");
//
// VMToolStripMenuItem
//
this.VMToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.NewVmToolStripMenuItem,
this.startShutdownToolStripMenuItem,
this.resumeOnToolStripMenuItem,
this.relocateToolStripMenuItem,
this.startOnHostToolStripMenuItem,
this.toolStripSeparator20,
this.assignSnapshotScheduleToolStripMenuItem,
this.assignToVirtualApplianceToolStripMenuItem,
this.toolStripMenuItem9,
this.copyVMtoSharedStorageMenuItem,
this.MoveVMToolStripMenuItem,
this.snapshotToolStripMenuItem,
this.convertToTemplateToolStripMenuItem,
this.exportToolStripMenuItem,
this.disableCbtToolStripMenuItem,
this.enablePVSReadcachingToolStripMenuItem,
this.disablePVSReadcachingToolStripMenuItem,
this.toolStripMenuItem12,
this.installToolsToolStripMenuItem,
this.sendCtrlAltDelToolStripMenuItem,
this.toolStripSeparator5,
this.uninstallToolStripMenuItem,
this.toolStripSeparator10,
this.pluginItemsPlaceHolderToolStripMenuItem4,
this.VMPropertiesToolStripMenuItem});
this.VMToolStripMenuItem.Name = "VMToolStripMenuItem";
resources.ApplyResources(this.VMToolStripMenuItem, "VMToolStripMenuItem");
//
// NewVmToolStripMenuItem
//
this.NewVmToolStripMenuItem.Command = new XenAdmin.Commands.NewVMCommand();
this.NewVmToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_CreateVM_h32bit_16;
this.NewVmToolStripMenuItem.Name = "NewVmToolStripMenuItem";
resources.ApplyResources(this.NewVmToolStripMenuItem, "NewVmToolStripMenuItem");
//
// startShutdownToolStripMenuItem
//
this.startShutdownToolStripMenuItem.Name = "startShutdownToolStripMenuItem";
resources.ApplyResources(this.startShutdownToolStripMenuItem, "startShutdownToolStripMenuItem");
//
// resumeOnToolStripMenuItem
//
this.resumeOnToolStripMenuItem.Name = "resumeOnToolStripMenuItem";
resources.ApplyResources(this.resumeOnToolStripMenuItem, "resumeOnToolStripMenuItem");
//
// relocateToolStripMenuItem
//
this.relocateToolStripMenuItem.Name = "relocateToolStripMenuItem";
resources.ApplyResources(this.relocateToolStripMenuItem, "relocateToolStripMenuItem");
//
// startOnHostToolStripMenuItem
//
this.startOnHostToolStripMenuItem.Name = "startOnHostToolStripMenuItem";
resources.ApplyResources(this.startOnHostToolStripMenuItem, "startOnHostToolStripMenuItem");
//
// toolStripSeparator20
//
this.toolStripSeparator20.Name = "toolStripSeparator20";
resources.ApplyResources(this.toolStripSeparator20, "toolStripSeparator20");
//
// assignSnapshotScheduleToolStripMenuItem
//
this.assignSnapshotScheduleToolStripMenuItem.Name = "assignSnapshotScheduleToolStripMenuItem";
resources.ApplyResources(this.assignSnapshotScheduleToolStripMenuItem, "assignSnapshotScheduleToolStripMenuItem");
//
// assignToVirtualApplianceToolStripMenuItem
//
this.assignToVirtualApplianceToolStripMenuItem.Name = "assignToVirtualApplianceToolStripMenuItem";
resources.ApplyResources(this.assignToVirtualApplianceToolStripMenuItem, "assignToVirtualApplianceToolStripMenuItem");
//
// toolStripMenuItem9
//
this.toolStripMenuItem9.Name = "toolStripMenuItem9";
resources.ApplyResources(this.toolStripMenuItem9, "toolStripMenuItem9");
//
// copyVMtoSharedStorageMenuItem
//
this.copyVMtoSharedStorageMenuItem.Command = new XenAdmin.Commands.CopyVMCommand();
this.copyVMtoSharedStorageMenuItem.Name = "copyVMtoSharedStorageMenuItem";
resources.ApplyResources(this.copyVMtoSharedStorageMenuItem, "copyVMtoSharedStorageMenuItem");
//
// MoveVMToolStripMenuItem
//
this.MoveVMToolStripMenuItem.Command = new XenAdmin.Commands.MoveVMCommand();
this.MoveVMToolStripMenuItem.Name = "MoveVMToolStripMenuItem";
resources.ApplyResources(this.MoveVMToolStripMenuItem, "MoveVMToolStripMenuItem");
//
// snapshotToolStripMenuItem
//
this.snapshotToolStripMenuItem.Command = new XenAdmin.Commands.TakeSnapshotCommand();
this.snapshotToolStripMenuItem.Name = "snapshotToolStripMenuItem";
resources.ApplyResources(this.snapshotToolStripMenuItem, "snapshotToolStripMenuItem");
//
// convertToTemplateToolStripMenuItem
//
this.convertToTemplateToolStripMenuItem.Command = new XenAdmin.Commands.ConvertVMToTemplateCommand();
this.convertToTemplateToolStripMenuItem.Name = "convertToTemplateToolStripMenuItem";
resources.ApplyResources(this.convertToTemplateToolStripMenuItem, "convertToTemplateToolStripMenuItem");
//
// exportToolStripMenuItem
//
this.exportToolStripMenuItem.Command = new XenAdmin.Commands.ExportCommand();
this.exportToolStripMenuItem.Name = "exportToolStripMenuItem";
resources.ApplyResources(this.exportToolStripMenuItem, "exportToolStripMenuItem");
//
// enablePVSReadcachingToolStripMenuItem
//
this.enablePVSReadcachingToolStripMenuItem.Command = new EnablePvsReadCachingCommand();
this.enablePVSReadcachingToolStripMenuItem.Name = "enablePVSReadcachingToolStripMenuItem";
resources.ApplyResources(this.enablePVSReadcachingToolStripMenuItem, "enablePVSReadcachingToolStripMenuItem");
//
// disablePVSReadcachingToolStripMenuItem
//
this.disablePVSReadcachingToolStripMenuItem.Command = new DisablePvsReadCachingCommand();
this.disablePVSReadcachingToolStripMenuItem.Name = "disablePVSReadcachingToolStripMenuItem";
resources.ApplyResources(this.disablePVSReadcachingToolStripMenuItem, "disablePVSReadcachingToolStripMenuItem");
//
// toolStripMenuItem12
//
this.toolStripMenuItem12.Name = "toolStripMenuItem12";
resources.ApplyResources(this.toolStripMenuItem12, "toolStripMenuItem12");
//
// installToolsToolStripMenuItem
//
this.installToolsToolStripMenuItem.Command = new XenAdmin.Commands.InstallToolsCommand();
this.installToolsToolStripMenuItem.Name = "installToolsToolStripMenuItem";
resources.ApplyResources(this.installToolsToolStripMenuItem, "installToolsToolStripMenuItem");
//
// sendCtrlAltDelToolStripMenuItem
//
this.sendCtrlAltDelToolStripMenuItem.Name = "sendCtrlAltDelToolStripMenuItem";
resources.ApplyResources(this.sendCtrlAltDelToolStripMenuItem, "sendCtrlAltDelToolStripMenuItem");
this.sendCtrlAltDelToolStripMenuItem.Click += new System.EventHandler(this.sendCtrlAltDelToolStripMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
//
// uninstallToolStripMenuItem
//
this.uninstallToolStripMenuItem.Command = new XenAdmin.Commands.DeleteVMCommand();
this.uninstallToolStripMenuItem.Name = "uninstallToolStripMenuItem";
resources.ApplyResources(this.uninstallToolStripMenuItem, "uninstallToolStripMenuItem");
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
resources.ApplyResources(this.toolStripSeparator10, "toolStripSeparator10");
//
// pluginItemsPlaceHolderToolStripMenuItem4
//
this.pluginItemsPlaceHolderToolStripMenuItem4.Name = "pluginItemsPlaceHolderToolStripMenuItem4";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem4, "pluginItemsPlaceHolderToolStripMenuItem4");
//
// VMPropertiesToolStripMenuItem
//
this.VMPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.VMPropertiesCommand();
this.VMPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
this.VMPropertiesToolStripMenuItem.Name = "VMPropertiesToolStripMenuItem";
resources.ApplyResources(this.VMPropertiesToolStripMenuItem, "VMPropertiesToolStripMenuItem");
//
// toolStripMenuItem8
//
this.toolStripMenuItem8.Name = "toolStripMenuItem8";
resources.ApplyResources(this.toolStripMenuItem8, "toolStripMenuItem8");
//
// StorageToolStripMenuItem
//
this.StorageToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AddStorageToolStripMenuItem,
this.toolStripSeparator22,
this.RepairStorageToolStripMenuItem,
this.DefaultSRToolStripMenuItem,
this.toolStripSeparator2,
this.virtualDisksToolStripMenuItem,
this.reclaimFreedSpacetripMenuItem,
this.toolStripSeparator19,
this.DetachStorageToolStripMenuItem,
this.ReattachStorageRepositoryToolStripMenuItem,
this.ForgetStorageRepositoryToolStripMenuItem,
this.DestroyStorageRepositoryToolStripMenuItem,
this.toolStripSeparator18,
this.pluginItemsPlaceHolderToolStripMenuItem5,
this.SRPropertiesToolStripMenuItem});
this.StorageToolStripMenuItem.Name = "StorageToolStripMenuItem";
resources.ApplyResources(this.StorageToolStripMenuItem, "StorageToolStripMenuItem");
//
// AddStorageToolStripMenuItem
//
this.AddStorageToolStripMenuItem.Command = new XenAdmin.Commands.NewSRCommand();
this.AddStorageToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_NewStorage_h32bit_16;
this.AddStorageToolStripMenuItem.Name = "AddStorageToolStripMenuItem";
resources.ApplyResources(this.AddStorageToolStripMenuItem, "AddStorageToolStripMenuItem");
//
// toolStripSeparator22
//
this.toolStripSeparator22.Name = "toolStripSeparator22";
resources.ApplyResources(this.toolStripSeparator22, "toolStripSeparator22");
//
// RepairStorageToolStripMenuItem
//
this.RepairStorageToolStripMenuItem.Command = new XenAdmin.Commands.RepairSRCommand();
this.RepairStorageToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_StorageBroken_h32bit_16;
this.RepairStorageToolStripMenuItem.Name = "RepairStorageToolStripMenuItem";
resources.ApplyResources(this.RepairStorageToolStripMenuItem, "RepairStorageToolStripMenuItem");
//
// DefaultSRToolStripMenuItem
//
this.DefaultSRToolStripMenuItem.Command = new XenAdmin.Commands.SetAsDefaultSRCommand();
this.DefaultSRToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_StorageDefault_h32bit_16;
this.DefaultSRToolStripMenuItem.Name = "DefaultSRToolStripMenuItem";
resources.ApplyResources(this.DefaultSRToolStripMenuItem, "DefaultSRToolStripMenuItem");
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// virtualDisksToolStripMenuItem
//
this.virtualDisksToolStripMenuItem.Command = new XenAdmin.Commands.VirtualDiskCommand();
this.virtualDisksToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addVirtualDiskToolStripMenuItem,
this.attachVirtualDiskToolStripMenuItem});
this.virtualDisksToolStripMenuItem.Name = "virtualDisksToolStripMenuItem";
resources.ApplyResources(this.virtualDisksToolStripMenuItem, "virtualDisksToolStripMenuItem");
//
// addVirtualDiskToolStripMenuItem
//
this.addVirtualDiskToolStripMenuItem.Command = new XenAdmin.Commands.AddVirtualDiskCommand();
this.addVirtualDiskToolStripMenuItem.Name = "addVirtualDiskToolStripMenuItem";
resources.ApplyResources(this.addVirtualDiskToolStripMenuItem, "addVirtualDiskToolStripMenuItem");
//
// attachVirtualDiskToolStripMenuItem
//
this.attachVirtualDiskToolStripMenuItem.Command = new XenAdmin.Commands.AttachVirtualDiskCommand();
this.attachVirtualDiskToolStripMenuItem.Name = "attachVirtualDiskToolStripMenuItem";
resources.ApplyResources(this.attachVirtualDiskToolStripMenuItem, "attachVirtualDiskToolStripMenuItem");
//
// reclaimFreedSpacetripMenuItem
//
this.reclaimFreedSpacetripMenuItem.Command = new XenAdmin.Commands.TrimSRCommand();
this.reclaimFreedSpacetripMenuItem.Name = "reclaimFreedSpacetripMenuItem";
resources.ApplyResources(this.reclaimFreedSpacetripMenuItem, "reclaimFreedSpacetripMenuItem");
//
// toolStripSeparator19
//
this.toolStripSeparator19.Name = "toolStripSeparator19";
resources.ApplyResources(this.toolStripSeparator19, "toolStripSeparator19");
//
// DetachStorageToolStripMenuItem
//
this.DetachStorageToolStripMenuItem.Command = new XenAdmin.Commands.DetachSRCommand();
this.DetachStorageToolStripMenuItem.Name = "DetachStorageToolStripMenuItem";
resources.ApplyResources(this.DetachStorageToolStripMenuItem, "DetachStorageToolStripMenuItem");
//
// ReattachStorageRepositoryToolStripMenuItem
//
this.ReattachStorageRepositoryToolStripMenuItem.Command = new XenAdmin.Commands.ReattachSRCommand();
this.ReattachStorageRepositoryToolStripMenuItem.Name = "ReattachStorageRepositoryToolStripMenuItem";
resources.ApplyResources(this.ReattachStorageRepositoryToolStripMenuItem, "ReattachStorageRepositoryToolStripMenuItem");
//
// ForgetStorageRepositoryToolStripMenuItem
//
this.ForgetStorageRepositoryToolStripMenuItem.Command = new XenAdmin.Commands.ForgetSRCommand();
this.ForgetStorageRepositoryToolStripMenuItem.Name = "ForgetStorageRepositoryToolStripMenuItem";
resources.ApplyResources(this.ForgetStorageRepositoryToolStripMenuItem, "ForgetStorageRepositoryToolStripMenuItem");
//
// DestroyStorageRepositoryToolStripMenuItem
//
this.DestroyStorageRepositoryToolStripMenuItem.Command = new XenAdmin.Commands.DestroySRCommand();
this.DestroyStorageRepositoryToolStripMenuItem.Name = "DestroyStorageRepositoryToolStripMenuItem";
resources.ApplyResources(this.DestroyStorageRepositoryToolStripMenuItem, "DestroyStorageRepositoryToolStripMenuItem");
//
// toolStripSeparator18
//
this.toolStripSeparator18.Name = "toolStripSeparator18";
resources.ApplyResources(this.toolStripSeparator18, "toolStripSeparator18");
//
// pluginItemsPlaceHolderToolStripMenuItem5
//
this.pluginItemsPlaceHolderToolStripMenuItem5.Name = "pluginItemsPlaceHolderToolStripMenuItem5";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem5, "pluginItemsPlaceHolderToolStripMenuItem5");
//
// SRPropertiesToolStripMenuItem
//
this.SRPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.SRPropertiesCommand();
this.SRPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
this.SRPropertiesToolStripMenuItem.Name = "SRPropertiesToolStripMenuItem";
resources.ApplyResources(this.SRPropertiesToolStripMenuItem, "SRPropertiesToolStripMenuItem");
//
// templatesToolStripMenuItem
//
this.templatesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.CreateVmFromTemplateToolStripMenuItem,
this.toolStripSeparator29,
this.exportTemplateToolStripMenuItem,
this.duplicateTemplateToolStripMenuItem,
this.toolStripSeparator16,
this.uninstallTemplateToolStripMenuItem,
this.toolStripSeparator28,
this.pluginItemsPlaceHolderToolStripMenuItem6,
this.templatePropertiesToolStripMenuItem});
this.templatesToolStripMenuItem.Name = "templatesToolStripMenuItem";
resources.ApplyResources(this.templatesToolStripMenuItem, "templatesToolStripMenuItem");
//
// CreateVmFromTemplateToolStripMenuItem
//
this.CreateVmFromTemplateToolStripMenuItem.Command = new XenAdmin.Commands.CreateVMFromTemplateCommand();
this.CreateVmFromTemplateToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newVMFromTemplateToolStripMenuItem,
this.InstantVmToolStripMenuItem});
this.CreateVmFromTemplateToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_CreateVM_h32bit_16;
this.CreateVmFromTemplateToolStripMenuItem.Name = "CreateVmFromTemplateToolStripMenuItem";
resources.ApplyResources(this.CreateVmFromTemplateToolStripMenuItem, "CreateVmFromTemplateToolStripMenuItem");
//
// newVMFromTemplateToolStripMenuItem
//
this.newVMFromTemplateToolStripMenuItem.Command = new XenAdmin.Commands.NewVMFromTemplateCommand();
this.newVMFromTemplateToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_CreateVM_h32bit_16;
this.newVMFromTemplateToolStripMenuItem.Name = "newVMFromTemplateToolStripMenuItem";
resources.ApplyResources(this.newVMFromTemplateToolStripMenuItem, "newVMFromTemplateToolStripMenuItem");
//
// InstantVmToolStripMenuItem
//
this.InstantVmToolStripMenuItem.Command = new XenAdmin.Commands.InstantVMFromTemplateCommand();
this.InstantVmToolStripMenuItem.Name = "InstantVmToolStripMenuItem";
resources.ApplyResources(this.InstantVmToolStripMenuItem, "InstantVmToolStripMenuItem");
//
// toolStripSeparator29
//
this.toolStripSeparator29.Name = "toolStripSeparator29";
resources.ApplyResources(this.toolStripSeparator29, "toolStripSeparator29");
//
// exportTemplateToolStripMenuItem
//
this.exportTemplateToolStripMenuItem.Command = new XenAdmin.Commands.ExportTemplateCommand();
this.exportTemplateToolStripMenuItem.Name = "exportTemplateToolStripMenuItem";
resources.ApplyResources(this.exportTemplateToolStripMenuItem, "exportTemplateToolStripMenuItem");
//
// duplicateTemplateToolStripMenuItem
//
this.duplicateTemplateToolStripMenuItem.Command = new XenAdmin.Commands.CopyTemplateCommand();
this.duplicateTemplateToolStripMenuItem.Name = "duplicateTemplateToolStripMenuItem";
resources.ApplyResources(this.duplicateTemplateToolStripMenuItem, "duplicateTemplateToolStripMenuItem");
//
// toolStripSeparator16
//
this.toolStripSeparator16.Name = "toolStripSeparator16";
resources.ApplyResources(this.toolStripSeparator16, "toolStripSeparator16");
//
// uninstallTemplateToolStripMenuItem
//
this.uninstallTemplateToolStripMenuItem.Command = new XenAdmin.Commands.DeleteTemplateCommand();
this.uninstallTemplateToolStripMenuItem.Name = "uninstallTemplateToolStripMenuItem";
resources.ApplyResources(this.uninstallTemplateToolStripMenuItem, "uninstallTemplateToolStripMenuItem");
//
// toolStripSeparator28
//
this.toolStripSeparator28.Name = "toolStripSeparator28";
resources.ApplyResources(this.toolStripSeparator28, "toolStripSeparator28");
//
// pluginItemsPlaceHolderToolStripMenuItem6
//
this.pluginItemsPlaceHolderToolStripMenuItem6.Name = "pluginItemsPlaceHolderToolStripMenuItem6";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem6, "pluginItemsPlaceHolderToolStripMenuItem6");
//
// templatePropertiesToolStripMenuItem
//
this.templatePropertiesToolStripMenuItem.Command = new XenAdmin.Commands.TemplatePropertiesCommand();
this.templatePropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
this.templatePropertiesToolStripMenuItem.Name = "templatePropertiesToolStripMenuItem";
resources.ApplyResources(this.templatePropertiesToolStripMenuItem, "templatePropertiesToolStripMenuItem");
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.bugToolToolStripMenuItem,
this.healthCheckToolStripMenuItem1,
this.toolStripSeparator14,
this.LicenseManagerMenuItem,
this.toolStripSeparator13,
this.installNewUpdateToolStripMenuItem,
this.rollingUpgradeToolStripMenuItem,
this.toolStripSeparator6,
this.pluginItemsPlaceHolderToolStripMenuItem7,
this.preferencesToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
resources.ApplyResources(this.toolsToolStripMenuItem, "toolsToolStripMenuItem");
//
// bugToolToolStripMenuItem
//
this.bugToolToolStripMenuItem.Command = new XenAdmin.Commands.BugToolCommand();
this.bugToolToolStripMenuItem.Name = "bugToolToolStripMenuItem";
resources.ApplyResources(this.bugToolToolStripMenuItem, "bugToolToolStripMenuItem");
//
// healthCheckToolStripMenuItem1
//
this.healthCheckToolStripMenuItem1.Command = new XenAdmin.Commands.HealthCheckCommand();
this.healthCheckToolStripMenuItem1.Name = "healthCheckToolStripMenuItem1";
resources.ApplyResources(this.healthCheckToolStripMenuItem1, "healthCheckToolStripMenuItem1");
//
// toolStripSeparator14
//
this.toolStripSeparator14.Name = "toolStripSeparator14";
resources.ApplyResources(this.toolStripSeparator14, "toolStripSeparator14");
//
// LicenseManagerMenuItem
//
this.LicenseManagerMenuItem.Name = "LicenseManagerMenuItem";
resources.ApplyResources(this.LicenseManagerMenuItem, "LicenseManagerMenuItem");
this.LicenseManagerMenuItem.Click += new System.EventHandler(this.LicenseManagerMenuItem_Click);
//
// toolStripSeparator13
//
this.toolStripSeparator13.Name = "toolStripSeparator13";
resources.ApplyResources(this.toolStripSeparator13, "toolStripSeparator13");
//
// installNewUpdateToolStripMenuItem
//
this.installNewUpdateToolStripMenuItem.Command = new XenAdmin.Commands.InstallNewUpdateCommand();
this.installNewUpdateToolStripMenuItem.Name = "installNewUpdateToolStripMenuItem";
resources.ApplyResources(this.installNewUpdateToolStripMenuItem, "installNewUpdateToolStripMenuItem");
//
// rollingUpgradeToolStripMenuItem
//
this.rollingUpgradeToolStripMenuItem.Command = new XenAdmin.Commands.RollingUpgradeCommand();
this.rollingUpgradeToolStripMenuItem.Name = "rollingUpgradeToolStripMenuItem";
resources.ApplyResources(this.rollingUpgradeToolStripMenuItem, "rollingUpgradeToolStripMenuItem");
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
//
// pluginItemsPlaceHolderToolStripMenuItem7
//
this.pluginItemsPlaceHolderToolStripMenuItem7.Name = "pluginItemsPlaceHolderToolStripMenuItem7";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem7, "pluginItemsPlaceHolderToolStripMenuItem7");
//
// preferencesToolStripMenuItem
//
this.preferencesToolStripMenuItem.Name = "preferencesToolStripMenuItem";
resources.ApplyResources(this.preferencesToolStripMenuItem, "preferencesToolStripMenuItem");
this.preferencesToolStripMenuItem.Click += new System.EventHandler(this.preferencesToolStripMenuItem_Click);
//
// windowToolStripMenuItem
//
this.windowToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.pluginItemsPlaceHolderToolStripMenuItem9});
this.windowToolStripMenuItem.Name = "windowToolStripMenuItem";
resources.ApplyResources(this.windowToolStripMenuItem, "windowToolStripMenuItem");
//
// pluginItemsPlaceHolderToolStripMenuItem9
//
this.pluginItemsPlaceHolderToolStripMenuItem9.Name = "pluginItemsPlaceHolderToolStripMenuItem9";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem9, "pluginItemsPlaceHolderToolStripMenuItem9");
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.helpTopicsToolStripMenuItem,
this.helpContextMenuItem,
this.toolStripMenuItem15,
this.viewApplicationLogToolStripMenuItem,
this.toolStripMenuItem17,
this.xenSourceOnTheWebToolStripMenuItem,
this.xenCenterPluginsOnlineToolStripMenuItem,
this.toolStripSeparator7,
this.pluginItemsPlaceHolderToolStripMenuItem8,
this.aboutXenSourceAdminToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
resources.ApplyResources(this.helpToolStripMenuItem, "helpToolStripMenuItem");
//
// helpTopicsToolStripMenuItem
//
this.helpTopicsToolStripMenuItem.Name = "helpTopicsToolStripMenuItem";
resources.ApplyResources(this.helpTopicsToolStripMenuItem, "helpTopicsToolStripMenuItem");
this.helpTopicsToolStripMenuItem.Click += new System.EventHandler(this.helpTopicsToolStripMenuItem_Click);
//
// helpContextMenuItem
//
this.helpContextMenuItem.Image = global::XenAdmin.Properties.Resources._000_HelpIM_h32bit_16;
this.helpContextMenuItem.Name = "helpContextMenuItem";
resources.ApplyResources(this.helpContextMenuItem, "helpContextMenuItem");
this.helpContextMenuItem.Click += new System.EventHandler(this.helpContextMenuItem_Click);
//
// toolStripMenuItem15
//
this.toolStripMenuItem15.Name = "toolStripMenuItem15";
resources.ApplyResources(this.toolStripMenuItem15, "toolStripMenuItem15");
//
// viewApplicationLogToolStripMenuItem
//
this.viewApplicationLogToolStripMenuItem.Name = "viewApplicationLogToolStripMenuItem";
resources.ApplyResources(this.viewApplicationLogToolStripMenuItem, "viewApplicationLogToolStripMenuItem");
this.viewApplicationLogToolStripMenuItem.Click += new System.EventHandler(this.viewApplicationLogToolStripMenuItem_Click);
//
// toolStripMenuItem17
//
this.toolStripMenuItem17.Name = "toolStripMenuItem17";
resources.ApplyResources(this.toolStripMenuItem17, "toolStripMenuItem17");
//
// xenSourceOnTheWebToolStripMenuItem
//
this.xenSourceOnTheWebToolStripMenuItem.Name = "xenSourceOnTheWebToolStripMenuItem";
resources.ApplyResources(this.xenSourceOnTheWebToolStripMenuItem, "xenSourceOnTheWebToolStripMenuItem");
this.xenSourceOnTheWebToolStripMenuItem.Click += new System.EventHandler(this.xenSourceOnTheWebToolStripMenuItem_Click);
//
// xenCenterPluginsOnlineToolStripMenuItem
//
this.xenCenterPluginsOnlineToolStripMenuItem.Name = "xenCenterPluginsOnlineToolStripMenuItem";
resources.ApplyResources(this.xenCenterPluginsOnlineToolStripMenuItem, "xenCenterPluginsOnlineToolStripMenuItem");
this.xenCenterPluginsOnlineToolStripMenuItem.Click += new System.EventHandler(this.xenCenterPluginsOnTheWebToolStripMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7");
//
// pluginItemsPlaceHolderToolStripMenuItem8
//
this.pluginItemsPlaceHolderToolStripMenuItem8.Name = "pluginItemsPlaceHolderToolStripMenuItem8";
resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem8, "pluginItemsPlaceHolderToolStripMenuItem8");
//
// aboutXenSourceAdminToolStripMenuItem
//
this.aboutXenSourceAdminToolStripMenuItem.Name = "aboutXenSourceAdminToolStripMenuItem";
resources.ApplyResources(this.aboutXenSourceAdminToolStripMenuItem, "aboutXenSourceAdminToolStripMenuItem");
this.aboutXenSourceAdminToolStripMenuItem.Click += new System.EventHandler(this.aboutXenSourceAdminToolStripMenuItem_Click);
//
// MainMenuBar
//
resources.ApplyResources(this.MainMenuBar, "MainMenuBar");
this.MainMenuBar.ClickThrough = true;
this.MainMenuBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.viewToolStripMenuItem,
this.poolToolStripMenuItem,
this.HostMenuItem,
this.VMToolStripMenuItem,
this.StorageToolStripMenuItem,
this.templatesToolStripMenuItem,
this.toolsToolStripMenuItem,
this.windowToolStripMenuItem,
this.helpToolStripMenuItem});
this.MainMenuBar.Name = "MainMenuBar";
this.MainMenuBar.MenuActivate += new System.EventHandler(this.MainMenuBar_MenuActivate);
this.MainMenuBar.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MainMenuBar_MouseClick);
//
// securityGroupsToolStripMenuItem
//
this.securityGroupsToolStripMenuItem.Name = "securityGroupsToolStripMenuItem";
resources.ApplyResources(this.securityGroupsToolStripMenuItem, "securityGroupsToolStripMenuItem");
//
// MenuPanel
//
this.MenuPanel.Controls.Add(this.MainMenuBar);
resources.ApplyResources(this.MenuPanel, "MenuPanel");
this.MenuPanel.Name = "MenuPanel";
//
// StatusStrip
//
resources.ApplyResources(this.StatusStrip, "StatusStrip");
this.StatusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusLabel,
this.statusProgressBar});
this.StatusStrip.Name = "StatusStrip";
this.StatusStrip.ShowItemToolTips = true;
//
// statusLabel
//
this.statusLabel.AutoToolTip = true;
resources.ApplyResources(this.statusLabel, "statusLabel");
this.statusLabel.Name = "statusLabel";
this.statusLabel.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
this.statusLabel.Spring = true;
//
// statusProgressBar
//
resources.ApplyResources(this.statusProgressBar, "statusProgressBar");
this.statusProgressBar.Margin = new System.Windows.Forms.Padding(5);
this.statusProgressBar.Name = "statusProgressBar";
this.statusProgressBar.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
//
// TabPageUSB
//
resources.ApplyResources(this.TabPageUSB, "TabPageUSB");
this.TabPageUSB.Name = "TabPageUSB";
this.TabPageUSB.UseVisualStyleBackColor = true;
// disableCbtToolStripMenuItem
//
this.disableCbtToolStripMenuItem.Command = new XenAdmin.Commands.DisableChangedBlockTrackingCommand();
this.disableCbtToolStripMenuItem.Name = "disableCbtToolStripMenuItem";
resources.ApplyResources(this.disableCbtToolStripMenuItem, "disableCbtToolStripMenuItem");
//
// MainWindow
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.ToolStrip);
this.Controls.Add(this.MenuPanel);
this.Controls.Add(this.StatusStrip);
this.DoubleBuffered = true;
this.KeyPreview = true;
this.MainMenuStrip = this.MainMenuBar;
this.Name = "MainWindow";
this.Load += new System.EventHandler(this.MainWindow_Load);
this.Shown += new System.EventHandler(this.MainWindow_Shown);
this.ResizeEnd += new System.EventHandler(this.MainWindow_ResizeEnd);
this.HelpRequested += new System.Windows.Forms.HelpEventHandler(this.MainWindow_HelpRequested);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainWindow_KeyDown);
this.Resize += new System.EventHandler(this.MainWindow_Resize);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.TheTabControl.ResumeLayout(false);
this.TabPageSnapshots.ResumeLayout(false);
this.TitleBackPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.TitleIcon)).EndInit();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.toolTipContainer1.ResumeLayout(false);
this.toolTipContainer1.PerformLayout();
this.ToolStrip.ResumeLayout(false);
this.ToolStrip.PerformLayout();
this.ToolBarContextMenu.ResumeLayout(false);
this.MainMenuBar.ResumeLayout(false);
this.MainMenuBar.PerformLayout();
this.MenuPanel.ResumeLayout(false);
this.StatusStrip.ResumeLayout(false);
this.StatusStrip.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private XenAdmin.Controls.ToolStripEx ToolStrip;
private CommandToolStripButton NewVmToolbarButton;
private CommandToolStripButton AddServerToolbarButton;
private CommandToolStripButton RebootToolbarButton;
private CommandToolStripButton SuspendToolbarButton;
private CommandToolStripButton ForceRebootToolbarButton;
private CommandToolStripButton ForceShutdownToolbarButton;
private System.Windows.Forms.ToolTip statusToolTip;
private CommandToolStripButton AddPoolToolbarButton;
private CommandToolStripButton newStorageToolbarButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator11;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator12;
private System.Windows.Forms.Label TitleLabel;
private System.Windows.Forms.PictureBox TitleIcon;
private XenAdmin.Controls.GradientPanel.GradientPanel TitleBackPanel;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator17;
internal System.Windows.Forms.ToolStripSplitButton backButton;
internal System.Windows.Forms.ToolStripSplitButton forwardButton;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.ContextMenuStrip ToolBarContextMenu;
private System.Windows.Forms.ToolStripMenuItem ShowToolbarMenuItem;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private CommandToolStripMenuItem FileImportVMToolStripMenuItem;
private CommandToolStripMenuItem importSearchToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator21;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem poolToolStripMenuItem;
private CommandToolStripMenuItem AddPoolToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private CommandToolStripMenuItem PoolPropertiesToolStripMenuItem;
private CommandToolStripMenuItem highAvailabilityToolStripMenuItem;
private CommandToolStripMenuItem wlbReportsToolStripMenuItem;
private CommandToolStripMenuItem wlbDisconnectToolStripMenuItem;
private AddHostToSelectedPoolToolStripMenuItem addServerToolStripMenuItem;
private CommandToolStripMenuItem removeServerToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private CommandToolStripMenuItem deleteToolStripMenuItem;
private CommandToolStripMenuItem disconnectPoolToolStripMenuItem;
private CommandToolStripMenuItem exportResourceReportPoolToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem HostMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem11;
private CommandToolStripMenuItem ServerPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator15;
private CommandToolStripMenuItem RebootHostToolStripMenuItem;
private CommandToolStripMenuItem ShutdownHostToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private CommandToolStripMenuItem AddHostToolStripMenuItem;
private CommandToolStripMenuItem removeHostToolStripMenuItem;
private AddSelectedHostToPoolToolStripMenuItem addServerToPoolMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private CommandToolStripMenuItem RemoveCrashdumpsToolStripMenuItem;
private CommandToolStripMenuItem maintenanceModeToolStripMenuItem1;
private CommandToolStripMenuItem backupToolStripMenuItem;
private CommandToolStripMenuItem restoreFromBackupToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem VMToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
private CommandToolStripMenuItem VMPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator20;
private CommandToolStripMenuItem snapshotToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9;
private CommandToolStripMenuItem copyVMtoSharedStorageMenuItem;
private CommandToolStripMenuItem exportToolStripMenuItem;
private CommandToolStripMenuItem convertToTemplateToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem12;
private CommandToolStripMenuItem installToolsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private CommandToolStripMenuItem uninstallToolStripMenuItem;
internal System.Windows.Forms.ToolStripMenuItem StorageToolStripMenuItem;
private CommandToolStripMenuItem AddStorageToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator18;
private CommandToolStripMenuItem SRPropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator22;
private CommandToolStripMenuItem RepairStorageToolStripMenuItem;
private CommandToolStripMenuItem DefaultSRToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator19;
private CommandToolStripMenuItem DetachStorageToolStripMenuItem;
private CommandToolStripMenuItem ReattachStorageRepositoryToolStripMenuItem;
private CommandToolStripMenuItem ForgetStorageRepositoryToolStripMenuItem;
private CommandToolStripMenuItem DestroyStorageRepositoryToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem templatesToolStripMenuItem;
private CommandToolStripMenuItem exportTemplateToolStripMenuItem;
private CommandToolStripMenuItem duplicateTemplateToolStripMenuItem;
private CommandToolStripMenuItem uninstallTemplateToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private CommandToolStripMenuItem bugToolToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator14;
private System.Windows.Forms.ToolStripMenuItem LicenseManagerMenuItem;
private CommandToolStripMenuItem installNewUpdateToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem preferencesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem windowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpTopicsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpContextMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem15;
private System.Windows.Forms.ToolStripMenuItem viewApplicationLogToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem17;
private System.Windows.Forms.ToolStripMenuItem xenSourceOnTheWebToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripMenuItem aboutXenSourceAdminToolStripMenuItem;
private XenAdmin.Controls.MenuStripEx MainMenuBar;
private System.Windows.Forms.Panel MenuPanel;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator13;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator24;
private System.Windows.Forms.ToolStripMenuItem toolbarToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem ShowHiddenObjectsToolStripMenuItem;
internal System.Windows.Forms.TabControl TheTabControl;
private System.Windows.Forms.TabPage TabPageHome;
internal System.Windows.Forms.TabPage TabPageSearch;
internal System.Windows.Forms.TabPage TabPageGeneral;
private System.Windows.Forms.TabPage TabPageBallooning;
internal System.Windows.Forms.TabPage TabPageConsole;
private System.Windows.Forms.TabPage TabPageStorage;
private System.Windows.Forms.TabPage TabPagePhysicalStorage;
private System.Windows.Forms.TabPage TabPageSR;
private System.Windows.Forms.TabPage TabPageNetwork;
private System.Windows.Forms.TabPage TabPageNICs;
private System.Windows.Forms.TabPage TabPagePeformance;
private System.Windows.Forms.TabPage TabPageHA;
private System.Windows.Forms.TabPage TabPageHAUpsell;
internal System.Windows.Forms.TabPage TabPageWLB;
private System.Windows.Forms.TabPage TabPageWLBUpsell;
private System.Windows.Forms.TabPage TabPageSnapshots;
private System.Windows.Forms.TabPage TabPageDockerProcess;
internal System.Windows.Forms.TabPage TabPageDockerDetails;
private XenAdmin.TabPages.SnapshotsPage snapshotPage;
private System.Windows.Forms.ToolStripMenuItem connectDisconnectToolStripMenuItem;
private CommandToolStripMenuItem connectAllToolStripMenuItem;
private CommandToolStripMenuItem DisconnectToolStripMenuItem;
private CommandToolStripMenuItem disconnectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sendCtrlAltDelToolStripMenuItem;
private CommandToolStripMenuItem virtualDisksToolStripMenuItem;
private CommandToolStripMenuItem addVirtualDiskToolStripMenuItem;
private CommandToolStripMenuItem attachVirtualDiskToolStripMenuItem;
private CommandToolStripMenuItem NewVmToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator26;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator27;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator23;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator25;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator28;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator16;
private CommandToolStripMenuItem templatePropertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator29;
private VMLifeCycleToolStripMenuItem startShutdownToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem8;
private CommandToolStripMenuItem ReconnectToolStripMenuItem1;
private XenAdmin.Controls.ToolTipContainer toolTipContainer1;
private XenAdmin.Controls.LoggedInLabel loggedInLabel1;
private CommandToolStripMenuItem reconnectAsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private CommandToolStripMenuItem poolReconnectAsToolStripMenuItem;
internal System.Windows.Forms.TabPage TabPageAD;
private System.Windows.Forms.TabPage TabPageGPU;
private CommandToolStripMenuItem powerOnToolStripMenuItem;
private CommandToolStripButton shutDownToolStripButton;
private CommandToolStripButton startVMToolStripButton;
private CommandToolStripButton powerOnHostToolStripButton;
private CommandToolStripButton resumeToolStripButton;
private MigrateVMToolStripMenuItem relocateToolStripMenuItem;
private StartVMOnHostToolStripMenuItem startOnHostToolStripMenuItem;
private ResumeVMOnHostToolStripMenuItem resumeOnToolStripMenuItem;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem1;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem2;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem3;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem4;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem5;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem6;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem7;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem9;
private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem8;
private TabPage TabPageBallooningUpsell;
private ToolStripMenuItem xenCenterPluginsOnlineToolStripMenuItem;
private CommandToolStripMenuItem MoveVMToolStripMenuItem;
private CommandToolStripMenuItem rollingUpgradeToolStripMenuItem;
private CommandToolStripMenuItem changePoolPasswordToolStripMenuItem;
private ToolStripSeparator toolStripSeparator30;
private CommandToolStripMenuItem virtualAppliancesToolStripMenuItem;
private AssignGroupToolStripMenuItemVM_appliance assignToVirtualApplianceToolStripMenuItem;
private CommandToolStripMenuItem disasterRecoveryToolStripMenuItem;
private CommandToolStripMenuItem DrWizardToolStripMenuItem;
private CommandToolStripMenuItem drConfigureToolStripMenuItem;
private CommandToolStripMenuItem securityGroupsToolStripMenuItem;
private ToolStripSeparator toolStripMenuItem1;
private CommandToolStripMenuItem HostPasswordToolStripMenuItem;
private CommandToolStripMenuItem ChangeRootPasswordToolStripMenuItem;
private CommandToolStripMenuItem forgetSavedPasswordToolStripMenuItem;
private CommandToolStripMenuItem CreateVmFromTemplateToolStripMenuItem;
private CommandToolStripMenuItem newVMFromTemplateToolStripMenuItem;
private CommandToolStripMenuItem InstantVmToolStripMenuItem;
private ToolStripMenuItem importSettingsToolStripMenuItem;
private ToolStripMenuItem exportSettingsToolStripMenuItem;
private ToolStripSeparator toolStripSeparator31;
private CommandToolStripMenuItem destroyServerToolStripMenuItem;
private CommandToolStripMenuItem restartToolstackToolStripMenuItem;
private XenAdmin.Controls.MainWindowControls.NavigationPane navigationPane;
private XenAdmin.TabPages.AlertSummaryPage alertPage;
private XenAdmin.TabPages.ManageUpdatesPage updatesPage;
private XenAdmin.TabPages.HistoryPage eventsPage;
private ToolStripMenuItem customTemplatesToolStripMenuItem;
private ToolStripMenuItem templatesToolStripMenuItem1;
private ToolStripMenuItem localStorageToolStripMenuItem;
private StatusStrip StatusStrip;
private ToolStripStatusLabel statusLabel;
private ToolStripProgressBar statusProgressBar;
private CommandToolStripMenuItem reclaimFreedSpacetripMenuItem;
private CommandToolStripButton startContainerToolStripButton;
private CommandToolStripButton stopContainerToolStripButton;
private CommandToolStripButton pauseContainerToolStripButton;
private CommandToolStripButton resumeContainerToolStripButton;
private CommandToolStripButton restartContainerToolStripButton;
private CommandToolStripMenuItem healthCheckToolStripMenuItem1;
private AssignGroupToolStripMenuItemVMSS assignSnapshotScheduleToolStripMenuItem;
private CommandToolStripMenuItem VMSnapshotScheduleToolStripMenuItem;
private TabPage TabPageADUpsell;
private TabPage TabPageCvmConsole;
private TabPage TabPagePvs;
private CommandToolStripMenuItem controlDomainMemoryToolStripMenuItem;
private CommandToolStripMenuItem enablePVSReadcachingToolStripMenuItem;
private CommandToolStripMenuItem disablePVSReadcachingToolStripMenuItem;
private TabPage TabPageUSB;
private CommandToolStripMenuItem disableCbtToolStripMenuItem;
private Label LicenseStatusTitleLabel;
}
}
| |
// Copyright 2007 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
//
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections;
using System.IO;
using System.Windows.Forms;
using System.Xml;
// Sample of persisted xml
//<GoogleEmailUploader>
// <User EmailId="foo@bar.com" ArchiveEverything="False" UploadSpeed="0.0022068824276766" FolderToLabelMapping="True">
// <Client Name="Microsoft Outlook" SelectionState="False">
// <Store DisplayName="Insight Server Folders" Persist="0000000038A1BB1005E5101AA1BB08002B2A56C20000436F6E6E6563746F722E646C6C00433A5C446F63756D656E747320616E642053657474696E67735C706172616D5C4170706C69636174696F6E20446174615C42796E6172695C42796E61726920496E736967687420436F6E6E6563746F7220332E305C4163636F756E74735C706172616D2D62795C666F6F40746573742E636F6D315C4C6F63616C43616368652E646200" SelectionState="False">
// <Contact SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// </Store>
// </Client>
// <Client Name="Outlook Express" SelectionState="False">
// <Store DisplayName="OE Store" Persist="OE Store" SelectionState="False">
// <Contact SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// <Folder Name="Deleted Items" SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// <Folder Name="Drafts" SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// <Folder Name="Inbox" SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// <Folder Name="Outbox" SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// <Folder Name="Sent Items" SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// </Store>
// </Client>
// <Client Name="Thunderbird" SelectionState="False">
// <Store DisplayName="Local Folders" Persist="Local Folders" SelectionState="False">
// <Contact SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// <Folder Name="Temp" SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// <Folder Name="Trash" SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// <Folder Name="Unsent Messages" SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// </Store>
// <Store DisplayName="pop.gmail.com" Persist="pop.gmail.com" SelectionState="False">
// <Contact SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// <Folder Name="Inbox" SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// <Folder Name="Trash" SelectionState="False" UploadedItemCount="0" FailedItemCount="0" LastUploadedItemId="" />
// </Store>
// </Client>
// </User>
//</GoogleEmailUploader>
namespace GoogleEmailUploader {
/// <summary>
/// This class is responsible for persisting and restoring the LKG state.
/// The LKG state is persisted by walking the Model tree and storing the
/// state of each model. For all models we store/restore selection state.
/// For clients, we also store/restore all the loaded stores.
/// For folders, we store/restore failed mail count, uplaoded mail count and
/// last uploaded mailid.
/// The persistence is done as XML. The expected size of this will be at most
/// in tens of KB's, so we are storing this as XML DOM rather tan using more
/// efficent but hard to use XML reader/writer.
/// </summary>
class LKGStatePersistor {
const string GoogleEmailUploaderElementName = "GoogleEmailUploader";
const string UserElementName = "User";
const string ClientElementName = "Client";
const string LoadedStoreElementName = "LoadedStore";
const string StoreElementName = "Store";
const string ContactsElementName = "Contacts";
const string FolderElementName = "Folder";
const string MailElementName = "Mail";
const string MailIdAttrName = "MailId";
const string ContactElementName = "Contact";
const string ContactIdAttrName = "ContactId";
const string FailureReasonAttrName = "FailureReason";
const string ArchiveEverythingAttrName = "ArchiveEverything";
const string FolderToLabelMappingAttrName = "FolderToLabelMapping";
const string UploadSpeedAttrName = "UploadSpeed";
const string NameAttrName = "Name";
const string SelectionStateAttrName = "SelectionState";
const string DisplayNameAttrName = "DisplayName";
const string PathAttrName = "Path";
const string PersistNameAttrName = "Persist";
readonly string lkgStateFilePath;
readonly string emailId;
readonly XmlDocument xmlDocument;
readonly XmlElement googleEmailUploaderXmlElement;
readonly XmlElement userXmlElement;
internal LKGStatePersistor(string emailId) {
this.lkgStateFilePath =
Path.Combine(Application.LocalUserAppDataPath,
"UserData.xml");
this.emailId = emailId;
if (!File.Exists(this.lkgStateFilePath)) {
this.xmlDocument =
this.CreateEmptyDocument(out this.googleEmailUploaderXmlElement);
} else {
try {
this.xmlDocument = new XmlDocument();
this.xmlDocument.Load(this.lkgStateFilePath);
if (this.xmlDocument.ChildNodes.Count == 1) {
this.googleEmailUploaderXmlElement =
this.xmlDocument.ChildNodes[0] as XmlElement;
if (this.googleEmailUploaderXmlElement == null ||
this.googleEmailUploaderXmlElement.Name
!= LKGStatePersistor.GoogleEmailUploaderElementName
) {
this.xmlDocument =
this.CreateEmptyDocument(
out this.googleEmailUploaderXmlElement);
}
} else {
this.xmlDocument =
this.CreateEmptyDocument(
out this.googleEmailUploaderXmlElement);
}
} catch (XmlException) {
this.xmlDocument =
this.CreateEmptyDocument(out this.googleEmailUploaderXmlElement);
}
}
this.userXmlElement = this.GetUserXmlElement();
this.xmlDocument.Save(this.lkgStateFilePath);
}
XmlDocument CreateEmptyDocument(
out XmlElement googleEmailClientXmlElement) {
XmlDocument xmlDocument = new XmlDocument();
googleEmailClientXmlElement =
xmlDocument.CreateElement(
LKGStatePersistor.GoogleEmailUploaderElementName);
xmlDocument.AppendChild(googleEmailClientXmlElement);
return xmlDocument;
}
XmlElement GetUserXmlElement() {
foreach (XmlElement xmlElement in
this.googleEmailUploaderXmlElement.ChildNodes) {
if (xmlElement.Name == LKGStatePersistor.UserElementName) {
string emailId =
xmlElement.GetAttribute(LKGStatePersistor.MailIdAttrName);
if (emailId == this.emailId) {
return xmlElement;
}
}
}
XmlElement newXmlElement =
this.xmlDocument.CreateElement(LKGStatePersistor.UserElementName);
newXmlElement.SetAttribute(
LKGStatePersistor.MailIdAttrName,
this.emailId);
this.googleEmailUploaderXmlElement.AppendChild(newXmlElement);
return newXmlElement;
}
static void LoadSelectedState(
XmlElement xmlElement,
TreeNodeModel treeNodeModel) {
if (xmlElement.GetAttribute(LKGStatePersistor.SelectionStateAttrName)
== bool.FalseString) {
treeNodeModel.IsSelected = false;
} else {
treeNodeModel.IsSelected = true;
}
}
/// <summary>
/// Loads the folder state i.e. SelectionState, UploadedMailCount,
/// FailedMailCount, LastUploadedMailId. Then it recurses on the
/// sub folders.
/// </summary>
void LoadFolderModelState(XmlElement folderXmlElement,
FolderModel folderModel) {
LKGStatePersistor.LoadSelectedState(
folderXmlElement,
folderModel);
foreach (XmlNode childXmlNode in folderXmlElement.ChildNodes) {
XmlElement childXmlElement = childXmlNode as XmlElement;
if (childXmlElement == null) {
continue;
}
if (childXmlElement.Name != LKGStatePersistor.MailElementName) {
continue;
}
string mailId =
childXmlElement.GetAttribute(LKGStatePersistor.MailIdAttrName);
if (mailId == null || mailId.Length == 0) {
continue;
}
string failureReason =
childXmlElement.GetAttribute(
LKGStatePersistor.FailureReasonAttrName);
if (failureReason == null || failureReason.Length == 0) {
folderModel.SuccessfullyUploaded(mailId);
} else {
FailedMailDatum failedMailDatum =
new FailedMailDatum(childXmlElement.InnerText, failureReason);
folderModel.FailedToUpload(mailId, failedMailDatum);
}
}
this.LoadFolderModelsState(
folderXmlElement.ChildNodes,
folderModel.Children);
}
/// <summary>
/// Loads the state of list of folders. This is done by walking the xml and
/// finding corresponding folder model and loading it.
/// </summary>
void LoadFolderModelsState(XmlNodeList folderXmlElements,
IEnumerable folders) {
foreach (XmlNode childXmlNode in folderXmlElements) {
XmlElement childXmlElement = childXmlNode as XmlElement;
if (childXmlElement == null) {
continue;
}
if (childXmlElement.Name != LKGStatePersistor.FolderElementName) {
continue;
}
string folderName =
childXmlElement.GetAttribute(LKGStatePersistor.NameAttrName);
foreach (FolderModel folderModel in folders) {
if (folderName != folderModel.Folder.Name) {
continue;
}
this.LoadFolderModelState(
childXmlElement,
folderModel);
}
}
}
/// <summary>
/// Loads the selection state of the contacts in the given store.
/// </summary>
void LoadContactsState(XmlElement contactsXmlElement,
StoreModel storeModel) {
if (contactsXmlElement.GetAttribute(
LKGStatePersistor.SelectionStateAttrName) == bool.FalseString) {
storeModel.IsContactSelected = false;
} else {
storeModel.IsContactSelected = true;
}
foreach (XmlNode childXmlNode in contactsXmlElement.ChildNodes) {
XmlElement childXmlElement = childXmlNode as XmlElement;
if (childXmlElement == null) {
continue;
}
if (childXmlElement.Name != LKGStatePersistor.ContactElementName) {
continue;
}
string contactId =
childXmlElement.GetAttribute(LKGStatePersistor.ContactIdAttrName);
if (contactId == null || contactId.Length == 0) {
continue;
}
string failureReason =
childXmlElement.GetAttribute(
LKGStatePersistor.FailureReasonAttrName);
if (failureReason == null || failureReason.Length == 0) {
storeModel.SuccessfullyUploaded(contactId);
} else {
FailedContactDatum failedContactDatum =
new FailedContactDatum(childXmlElement.InnerText, failureReason);
storeModel.FailedToUpload(contactId, failedContactDatum);
}
}
}
/// <summary>
/// Loads the selection state of the store, and then loads all the
/// state of all the subfolders.
/// </summary>
void LoadStoreModelState(XmlElement storeXmlElement,
StoreModel storeModel) {
LKGStatePersistor.LoadSelectedState(
storeXmlElement,
storeModel);
foreach (XmlNode childXmlNode in storeXmlElement.ChildNodes) {
XmlElement childXmlElement = childXmlNode as XmlElement;
if (childXmlElement == null) {
continue;
}
if (childXmlElement.Name != LKGStatePersistor.ContactsElementName) {
continue;
}
this.LoadContactsState(childXmlElement, storeModel);
break;
}
this.LoadFolderModelsState(
storeXmlElement.ChildNodes,
storeModel.Children);
}
/// <summary>
/// Restores the selection state of the given client model, and then
/// walks the xml and loads all the loaded stores. Then it goes on to load
/// the state of each store.
/// </summary>
void LoadClientModelState(XmlElement clientXmlElement,
ClientModel clientModel) {
LKGStatePersistor.LoadSelectedState(
clientXmlElement,
clientModel);
foreach (XmlNode childXmlNode in clientXmlElement.ChildNodes) {
XmlElement childXmlElement = childXmlNode as XmlElement;
if (childXmlElement == null) {
continue;
}
if (childXmlElement.Name != LKGStatePersistor.LoadedStoreElementName) {
continue;
}
string filePath =
childXmlElement.GetAttribute(LKGStatePersistor.PathAttrName);
if (filePath == null || filePath.Length == 0) {
continue;
}
if (!File.Exists(filePath)) {
continue;
}
clientModel.OpenStore(filePath);
}
foreach (XmlNode childXmlNode in clientXmlElement.ChildNodes) {
XmlElement childXmlElement = childXmlNode as XmlElement;
if (childXmlElement == null) {
continue;
}
if (childXmlElement.Name != LKGStatePersistor.StoreElementName) {
continue;
}
string storeDisplayName =
childXmlElement.GetAttribute(LKGStatePersistor.DisplayNameAttrName);
string storePersistName =
childXmlElement.GetAttribute(LKGStatePersistor.PersistNameAttrName);
foreach (StoreModel storeModel in clientModel.Children) {
if (storeDisplayName != storeModel.Store.DisplayName ||
storePersistName != storeModel.Store.PersistName) {
continue;
}
this.LoadStoreModelState(
childXmlElement,
storeModel);
}
}
}
/// <summary>
/// Loads the LKG state of the list of clients using the information
/// persisted.
/// This is done by walking the xml tree and finding the client model
/// corresponding to the tree node and restoring its state.
/// </summary>
internal void LoadLKGState(GoogleEmailUploaderModel uploaderModel) {
string archiveEverythingString =
this.userXmlElement.GetAttribute(
LKGStatePersistor.ArchiveEverythingAttrName);
bool archiveEverything = false;
try {
archiveEverything = bool.Parse(archiveEverythingString);
} catch {
// If we get an exception we assume by default we do not archive
// everything
}
uploaderModel.SetArchiving(archiveEverything);
string labelMappingString =
this.userXmlElement.GetAttribute(
LKGStatePersistor.FolderToLabelMappingAttrName);
bool labelMapping = true;
try {
labelMapping = bool.Parse(labelMappingString);
} catch {
// If we get an exception we assume by default we do label mapping
}
uploaderModel.SetFolderToLabelMapping(labelMapping);
string uploadSpeedString =
this.userXmlElement.GetAttribute(
LKGStatePersistor.UploadSpeedAttrName);
double uploadSpeed;
try {
uploadSpeed = double.Parse(uploadSpeedString);
if (uploadSpeed <= 0.0) {
uploadSpeed = 0.00005;
}
uploaderModel.SetUploadSpeed(uploadSpeed);
} catch {
// If we get an exception we dont update the speed. Let the speed
// be whatever is the speed for the test upload.
}
foreach (XmlNode childXmlNode in this.userXmlElement.ChildNodes) {
XmlElement childXmlElement = childXmlNode as XmlElement;
if (childXmlElement == null) {
continue;
}
if (childXmlElement.Name != LKGStatePersistor.ClientElementName) {
continue;
}
string clientName =
childXmlElement.GetAttribute(LKGStatePersistor.NameAttrName);
foreach (ClientModel clientModel in uploaderModel.ClientModels) {
if (clientName != clientModel.Client.Name) {
continue;
}
this.LoadClientModelState(
childXmlElement,
clientModel);
}
}
}
/// <summary>
/// Persists the selection state, uploaded mail count, failed mail count and
/// last uplaoded mail id. Ten recurses to persist all the sub folders.
/// </summary>
void SaveFolderModelState(XmlElement parentXmlElement,
FolderModel folderModel) {
XmlElement folderXmlElement =
this.xmlDocument.CreateElement(LKGStatePersistor.FolderElementName);
parentXmlElement.AppendChild(folderXmlElement);
folderXmlElement.SetAttribute(
LKGStatePersistor.NameAttrName,
folderModel.Folder.Name);
folderXmlElement.SetAttribute(
LKGStatePersistor.SelectionStateAttrName,
folderModel.IsSelected.ToString());
foreach (string mailId in folderModel.MailUploadData.Keys) {
XmlElement uploadedEmailXmlElement =
this.xmlDocument.CreateElement(
LKGStatePersistor.MailElementName);
folderXmlElement.AppendChild(uploadedEmailXmlElement);
uploadedEmailXmlElement.SetAttribute(
LKGStatePersistor.MailIdAttrName,
mailId);
FailedMailDatum failedMailDatum =
(FailedMailDatum)folderModel.MailUploadData[mailId];
if (failedMailDatum != null) {
// In case of failure to upload we set the reason, otherwise not.
uploadedEmailXmlElement.SetAttribute(
LKGStatePersistor.FailureReasonAttrName,
failedMailDatum.FailureReason);
uploadedEmailXmlElement.InnerText = failedMailDatum.MailHead;
}
}
foreach (FolderModel childFolderModel in folderModel.Children) {
this.SaveFolderModelState(
folderXmlElement,
childFolderModel);
}
}
/// <summary>
/// Saves the contact state within the given store.
/// </summary>
void SaveContactsState(XmlElement storeXmlElement,
StoreModel storeModel) {
XmlElement contactsXmlElement =
this.xmlDocument.CreateElement(LKGStatePersistor.ContactsElementName);
storeXmlElement.AppendChild(contactsXmlElement);
contactsXmlElement.SetAttribute(
LKGStatePersistor.SelectionStateAttrName,
storeModel.IsContactSelected.ToString());
foreach (string contactId in storeModel.ContactUploadData.Keys) {
XmlElement uploadedContactXmlElement =
this.xmlDocument.CreateElement(
LKGStatePersistor.ContactElementName);
contactsXmlElement.AppendChild(uploadedContactXmlElement);
uploadedContactXmlElement.SetAttribute(
LKGStatePersistor.ContactIdAttrName,
contactId);
FailedContactDatum failedContactDatum =
(FailedContactDatum)storeModel.ContactUploadData[contactId];
if (failedContactDatum != null) {
// In case of failure to upload we set the reason, otherwise not.
uploadedContactXmlElement.SetAttribute(
LKGStatePersistor.FailureReasonAttrName,
failedContactDatum.FailureReason);
uploadedContactXmlElement.InnerText = failedContactDatum.ContactName;
}
}
}
/// <summary>
/// Persists the store selection state, and state of all the subfolders.
/// </summary>
void SaveStoreModelState(XmlElement clientXmlElement,
StoreModel storeModel) {
XmlElement storeXmlElement =
this.xmlDocument.CreateElement(LKGStatePersistor.StoreElementName);
clientXmlElement.AppendChild(storeXmlElement);
storeXmlElement.SetAttribute(
LKGStatePersistor.DisplayNameAttrName,
storeModel.Store.DisplayName);
storeXmlElement.SetAttribute(
LKGStatePersistor.PersistNameAttrName,
storeModel.Store.PersistName);
storeXmlElement.SetAttribute(
LKGStatePersistor.SelectionStateAttrName,
storeModel.IsSelected.ToString());
this.SaveContactsState(storeXmlElement, storeModel);
foreach (FolderModel folderModel in storeModel.Children) {
this.SaveFolderModelState(
storeXmlElement,
folderModel);
}
}
/// <summary>
/// Persists the selection state of the client, file names of all the stores
/// loaded into the client and all the stores in the client.
/// </summary>
void SaveClientModelState(XmlElement userXmlElement,
ClientModel clientModel) {
XmlElement clientXmlElement =
this.xmlDocument.CreateElement(LKGStatePersistor.ClientElementName);
userXmlElement.AppendChild(clientXmlElement);
clientXmlElement.SetAttribute(
LKGStatePersistor.NameAttrName,
clientModel.Client.Name);
clientXmlElement.SetAttribute(
LKGStatePersistor.SelectionStateAttrName,
clientModel.IsSelected.ToString());
foreach (
string storeFileName in
clientModel.Client.LoadedStoreFileNames) {
XmlElement loadedStoreXmlElement =
this.xmlDocument.CreateElement(
LKGStatePersistor.LoadedStoreElementName);
clientXmlElement.AppendChild(loadedStoreXmlElement);
loadedStoreXmlElement.SetAttribute(
LKGStatePersistor.PathAttrName,
storeFileName);
}
foreach (StoreModel storeModel in clientModel.Children) {
this.SaveStoreModelState(
clientXmlElement,
storeModel);
}
}
/// <summary>
/// Saves the LKG state of all the clients in model.
/// </summary>
internal void SaveLKGState(GoogleEmailUploaderModel uploaderModel) {
this.userXmlElement.RemoveAll();
this.userXmlElement.SetAttribute(
LKGStatePersistor.MailIdAttrName,
this.emailId);
this.userXmlElement.SetAttribute(
LKGStatePersistor.ArchiveEverythingAttrName,
uploaderModel.IsArchiveEverything.ToString());
this.userXmlElement.SetAttribute(
LKGStatePersistor.UploadSpeedAttrName,
uploaderModel.UploadSpeed.ToString());
this.userXmlElement.SetAttribute(
LKGStatePersistor.FolderToLabelMappingAttrName,
uploaderModel.IsFolderToLabelMappingEnabled.ToString());
foreach (ClientModel clientModel in uploaderModel.ClientModels) {
this.SaveClientModelState(
this.userXmlElement,
clientModel);
}
this.xmlDocument.Save(this.lkgStateFilePath);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Castle.DynamicProxy;
using Castle.MicroKernel;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;
using Castle.Windsor.Proxy;
namespace Abp.Dependency
{
/// <summary>
/// This class is used to directly perform dependency injection tasks.
/// </summary>
public class IocManager : IIocManager
{
/// <summary>
/// The Singleton instance.
/// </summary>
public static IocManager Instance { get; private set; }
/// <summary>
/// Singletone instance for Castle ProxyGenerator.
/// From Castle.Core documentation it is highly recomended to use single instance of ProxyGenerator to avoid memoryleaks and performance issues
/// Follow next links for more details:
/// <a href="https://github.com/castleproject/Core/blob/master/docs/dynamicproxy.md">Castle.Core documentation</a>,
/// <a href="http://kozmic.net/2009/07/05/castle-dynamic-proxy-tutorial-part-xii-caching/">Article</a>
/// </summary>
private static readonly ProxyGenerator ProxyGeneratorInstance = new ProxyGenerator();
/// <summary>
/// Reference to the Castle Windsor Container.
/// </summary>
public IWindsorContainer IocContainer { get; private set; }
/// <summary>
/// List of all registered conventional registrars.
/// </summary>
private readonly List<IConventionalDependencyRegistrar> _conventionalRegistrars;
static IocManager()
{
Instance = new IocManager();
}
/// <summary>
/// Creates a new <see cref="IocManager"/> object.
/// Normally, you don't directly instantiate an <see cref="IocManager"/>.
/// This may be useful for test purposes.
/// </summary>
public IocManager()
{
IocContainer = CreateContainer();
_conventionalRegistrars = new List<IConventionalDependencyRegistrar>();
//Register self!
IocContainer.Register(
Component
.For<IocManager, IIocManager, IIocRegistrar, IIocResolver>()
.Instance(this)
);
}
protected virtual IWindsorContainer CreateContainer()
{
return new WindsorContainer(new DefaultProxyFactory(ProxyGeneratorInstance));
}
/// <summary>
/// Adds a dependency registrar for conventional registration.
/// </summary>
/// <param name="registrar">dependency registrar</param>
public void AddConventionalRegistrar(IConventionalDependencyRegistrar registrar)
{
_conventionalRegistrars.Add(registrar);
}
/// <summary>
/// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method.
/// </summary>
/// <param name="assembly">Assembly to register</param>
public void RegisterAssemblyByConvention(Assembly assembly)
{
RegisterAssemblyByConvention(assembly, new ConventionalRegistrationConfig());
}
/// <summary>
/// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method.
/// </summary>
/// <param name="assembly">Assembly to register</param>
/// <param name="config">Additional configuration</param>
public void RegisterAssemblyByConvention(Assembly assembly, ConventionalRegistrationConfig config)
{
var context = new ConventionalRegistrationContext(assembly, this, config);
foreach (var registerer in _conventionalRegistrars)
{
registerer.RegisterAssembly(context);
}
if (config.InstallInstallers)
{
IocContainer.Install(FromAssembly.Instance(assembly));
}
}
/// <summary>
/// Registers a type as self registration.
/// </summary>
/// <typeparam name="TType">Type of the class</typeparam>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register<TType>(DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) where TType : class
{
IocContainer.Register(ApplyLifestyle(Component.For<TType>(), lifeStyle));
}
/// <summary>
/// Registers a type as self registration.
/// </summary>
/// <param name="type">Type of the class</param>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register(Type type, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
{
IocContainer.Register(ApplyLifestyle(Component.For(type), lifeStyle));
}
/// <summary>
/// Registers a type with it's implementation.
/// </summary>
/// <typeparam name="TType">Registering type</typeparam>
/// <typeparam name="TImpl">The type that implements <see cref="TType"/></typeparam>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register<TType, TImpl>(DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
where TType : class
where TImpl : class, TType
{
IocContainer.Register(ApplyLifestyle(Component.For<TType, TImpl>().ImplementedBy<TImpl>(), lifeStyle));
}
/// <summary>
/// Registers a type with it's implementation.
/// </summary>
/// <param name="type">Type of the class</param>
/// <param name="impl">The type that implements <paramref name="type"/></param>
/// <param name="lifeStyle">Lifestyle of the objects of this type</param>
public void Register(Type type, Type impl, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
{
IocContainer.Register(ApplyLifestyle(Component.For(type, impl).ImplementedBy(impl), lifeStyle));
}
/// <summary>
/// Checks whether given type is registered before.
/// </summary>
/// <param name="type">Type to check</param>
public bool IsRegistered(Type type)
{
return IocContainer.Kernel.HasComponent(type);
}
/// <summary>
/// Checks whether given type is registered before.
/// </summary>
/// <typeparam name="TType">Type to check</typeparam>
public bool IsRegistered<TType>()
{
return IocContainer.Kernel.HasComponent(typeof(TType));
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage.
/// </summary>
/// <typeparam name="T">Type of the object to get</typeparam>
/// <returns>The instance object</returns>
public T Resolve<T>()
{
return IocContainer.Resolve<T>();
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="Release"/>) after usage.
/// </summary>
/// <typeparam name="T">Type of the object to cast</typeparam>
/// <param name="type">Type of the object to resolve</param>
/// <returns>The object instance</returns>
public T Resolve<T>(Type type)
{
return (T)IocContainer.Resolve(type);
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage.
/// </summary>
/// <typeparam name="T">Type of the object to get</typeparam>
/// <param name="argumentsAsAnonymousType">Constructor arguments</param>
/// <returns>The instance object</returns>
public T Resolve<T>(object argumentsAsAnonymousType)
{
return IocContainer.Resolve<T>(argumentsAsAnonymousType);
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage.
/// </summary>
/// <param name="type">Type of the object to get</param>
/// <returns>The instance object</returns>
public object Resolve(Type type)
{
return IocContainer.Resolve(type);
}
/// <summary>
/// Gets an object from IOC container.
/// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage.
/// </summary>
/// <param name="type">Type of the object to get</param>
/// <param name="argumentsAsAnonymousType">Constructor arguments</param>
/// <returns>The instance object</returns>
public object Resolve(Type type, object argumentsAsAnonymousType)
{
return IocContainer.Resolve(type, argumentsAsAnonymousType);
}
///<inheritdoc/>
public T[] ResolveAll<T>()
{
return IocContainer.ResolveAll<T>();
}
///<inheritdoc/>
public T[] ResolveAll<T>(object argumentsAsAnonymousType)
{
return IocContainer.ResolveAll<T>(argumentsAsAnonymousType);
}
///<inheritdoc/>
public object[] ResolveAll(Type type)
{
return IocContainer.ResolveAll(type).Cast<object>().ToArray();
}
///<inheritdoc/>
public object[] ResolveAll(Type type, object argumentsAsAnonymousType)
{
return IocContainer.ResolveAll(type, argumentsAsAnonymousType).Cast<object>().ToArray();
}
/// <summary>
/// Releases a pre-resolved object. See Resolve methods.
/// </summary>
/// <param name="obj">Object to be released</param>
public void Release(object obj)
{
IocContainer.Release(obj);
}
/// <inheritdoc/>
public void Dispose()
{
IocContainer.Dispose();
}
private static ComponentRegistration<T> ApplyLifestyle<T>(ComponentRegistration<T> registration, DependencyLifeStyle lifeStyle)
where T : class
{
switch (lifeStyle)
{
case DependencyLifeStyle.Transient:
return registration.LifestyleTransient();
case DependencyLifeStyle.Singleton:
return registration.LifestyleSingleton();
default:
return registration;
}
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Tests
{
public partial class EnumTests
{
[Theory]
[MemberData(nameof(Parse_TestData))]
public static void Parse_NetCoreApp11<T>(string value, bool ignoreCase, T expected) where T : struct
{
object result;
if (!ignoreCase)
{
Assert.True(Enum.TryParse(expected.GetType(), value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, Enum.Parse<T>(value));
}
Assert.True(Enum.TryParse(expected.GetType(), value, ignoreCase, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, Enum.Parse<T>(value, ignoreCase));
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid_NetCoreApp11(Type enumType, string value, bool ignoreCase, Type exceptionType)
{
Type typeArgument = enumType == null || !enumType.IsValueType ? typeof(SimpleEnum) : enumType;
MethodInfo parseMethod = typeof(EnumTests).GetTypeInfo().GetMethod(nameof(Parse_Generic_Invalid_NetCoreApp11), BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(typeArgument);
parseMethod.Invoke(null, new object[] { enumType, value, ignoreCase, exceptionType });
}
private static void Parse_Generic_Invalid_NetCoreApp11<T>(Type enumType, string value, bool ignoreCase, Type exceptionType) where T : struct
{
object result = null;
if (!ignoreCase)
{
if (enumType != null && enumType.IsEnum)
{
Assert.False(Enum.TryParse(enumType, value, out result));
Assert.Equal(default(object), result);
Assert.Throws(exceptionType, () => Enum.Parse<T>(value));
}
else
{
Assert.Throws(exceptionType, () => Enum.TryParse(enumType, value, out result));
Assert.Equal(default(object), result);
}
}
if (enumType != null && enumType.IsEnum)
{
Assert.False(Enum.TryParse(enumType, value, ignoreCase, out result));
Assert.Equal(default(object), result);
Assert.Throws(exceptionType, () => Enum.Parse<T>(value, ignoreCase));
}
else
{
Assert.Throws(exceptionType, () => Enum.TryParse(enumType, value, ignoreCase, out result));
Assert.Equal(default(object), result);
}
}
public static IEnumerable<object[]> UnsupportedEnumType_TestData()
{
#if netcoreapp
yield return new object[] { s_floatEnumType, 1.0f };
yield return new object[] { s_doubleEnumType, 1.0 };
yield return new object[] { s_intPtrEnumType, (IntPtr)1 };
yield return new object[] { s_uintPtrEnumType, (UIntPtr)1 };
#else
return Array.Empty<object[]>();
#endif //netcoreapp
}
[Theory]
[MemberData(nameof(UnsupportedEnumType_TestData))]
public static void GetName_Unsupported_ThrowsArgumentException(Type enumType, object value)
{
AssertExtensions.Throws<ArgumentException>("value", () => Enum.GetName(enumType, value));
}
[Theory]
[MemberData(nameof(UnsupportedEnumType_TestData))]
public static void IsDefined_UnsupportedEnumType_ThrowsInvalidOperationException(Type enumType, object value)
{
Exception ex = Assert.ThrowsAny<Exception>(() => Enum.IsDefined(enumType, value));
string exName = ex.GetType().Name;
Assert.True(exName == nameof(InvalidOperationException) || exName == "ContractException");
}
public static IEnumerable<object[]> UnsupportedEnum_TestData()
{
#if netcoreapp
yield return new object[] { Enum.ToObject(s_floatEnumType, 1) };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 2) };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1) };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 2) };
#else
return Array.Empty<object[]>();
#endif //netcoreapp
}
[Theory]
[MemberData(nameof(UnsupportedEnum_TestData))]
public static void ToString_UnsupportedEnumType_ThrowsArgumentException(Enum e)
{
Exception formatXException = Assert.ThrowsAny<Exception>(() => e.ToString("X"));
string formatXExceptionName = formatXException.GetType().Name;
Assert.True(formatXExceptionName == nameof(InvalidOperationException) || formatXExceptionName == "ContractException");
}
[Theory]
[MemberData(nameof(UnsupportedEnumType_TestData))]
public static void Format_UnsupportedEnumType_ThrowsArgumentException(Type enumType, object value)
{
Exception formatGException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "G"));
string formatGExceptionName = formatGException.GetType().Name;
Assert.True(formatGExceptionName == nameof(InvalidOperationException) || formatGExceptionName == "ContractException");
Exception formatXException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "X"));
string formatXExceptionName = formatXException.GetType().Name;
Assert.True(formatXExceptionName == nameof(InvalidOperationException) || formatXExceptionName == "ContractException");
Exception formatFException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "F"));
string formatFExceptionName = formatFException.GetType().Name;
Assert.True(formatFExceptionName == nameof(InvalidOperationException) || formatFExceptionName == "ContractException");
}
private static EnumBuilder GetNonRuntimeEnumTypeBuilder(Type underlyingType)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
return module.DefineEnum("TestName_" + underlyingType.Name, TypeAttributes.Public, underlyingType);
}
private static Type s_boolEnumType = GetBoolEnumType();
private static Type GetBoolEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(bool));
enumBuilder.DefineLiteral("Value1", true);
enumBuilder.DefineLiteral("Value2", false);
return enumBuilder.CreateTypeInfo().AsType();
}
private static Type s_charEnumType = GetCharEnumType();
private static Type GetCharEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(char));
enumBuilder.DefineLiteral("Value1", (char)1);
enumBuilder.DefineLiteral("Value2", (char)2);
enumBuilder.DefineLiteral("Value0x3f06", (char)0x3f06);
enumBuilder.DefineLiteral("Value0x3000", (char)0x3000);
enumBuilder.DefineLiteral("Value0x0f06", (char)0x0f06);
enumBuilder.DefineLiteral("Value0x1000", (char)0x1000);
enumBuilder.DefineLiteral("Value0x0000", (char)0x0000);
enumBuilder.DefineLiteral("Value0x0010", (char)0x0010);
enumBuilder.DefineLiteral("Value0x3f16", (char)0x3f16);
return enumBuilder.CreateTypeInfo().AsType();
}
private static Type s_floatEnumType = GetFloatEnumType();
private static Type GetFloatEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(float));
enumBuilder.DefineLiteral("Value1", 1.0f);
enumBuilder.DefineLiteral("Value2", 2.0f);
enumBuilder.DefineLiteral("Value0x3f06", (float)0x3f06);
enumBuilder.DefineLiteral("Value0x3000", (float)0x3000);
enumBuilder.DefineLiteral("Value0x0f06", (float)0x0f06);
enumBuilder.DefineLiteral("Value0x1000", (float)0x1000);
enumBuilder.DefineLiteral("Value0x0000", (float)0x0000);
enumBuilder.DefineLiteral("Value0x0010", (float)0x0010);
enumBuilder.DefineLiteral("Value0x3f16", (float)0x3f16);
return enumBuilder.CreateTypeInfo().AsType();
}
private static Type s_doubleEnumType = GetDoubleEnumType();
private static Type GetDoubleEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(double));
enumBuilder.DefineLiteral("Value1", 1.0);
enumBuilder.DefineLiteral("Value2", 2.0);
enumBuilder.DefineLiteral("Value0x3f06", (double)0x3f06);
enumBuilder.DefineLiteral("Value0x3000", (double)0x3000);
enumBuilder.DefineLiteral("Value0x0f06", (double)0x0f06);
enumBuilder.DefineLiteral("Value0x1000", (double)0x1000);
enumBuilder.DefineLiteral("Value0x0000", (double)0x0000);
enumBuilder.DefineLiteral("Value0x0010", (double)0x0010);
enumBuilder.DefineLiteral("Value0x3f16", (double)0x3f16);
return enumBuilder.CreateTypeInfo().AsType();
}
private static Type s_intPtrEnumType = GetIntPtrEnumType();
private static Type GetIntPtrEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(IntPtr));
return enumBuilder.CreateTypeInfo().AsType();
}
private static Type s_uintPtrEnumType = GetUIntPtrEnumType();
private static Type GetUIntPtrEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(UIntPtr));
return enumBuilder.CreateTypeInfo().AsType();
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Orleans.Runtime
{
internal class GrainTimer : IDisposable
{
private Func<object, Task> asyncCallback;
private AsyncTaskSafeTimer timer;
private readonly TimeSpan dueTime;
private readonly TimeSpan timerFrequency;
private DateTime previousTickTime;
private int totalNumTicks;
private static readonly TraceLogger logger = TraceLogger.GetLogger("GrainTimer", TraceLogger.LoggerType.Runtime);
private Task currentlyExecutingTickTask;
private readonly ActivationData activationData;
internal string Name { get; private set; }
private bool TimerAlreadyStopped { get { return timer == null || asyncCallback == null; } }
private GrainTimer(Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period, string name)
{
var ctxt = RuntimeContext.Current.ActivationContext;
activationData = (ActivationData) RuntimeClient.Current.CurrentActivationData;
this.Name = name;
this.asyncCallback = asyncCallback;
timer = new AsyncTaskSafeTimer(
stateObj => TimerTick(stateObj, ctxt),
state);
this.dueTime = dueTime;
timerFrequency = period;
previousTickTime = DateTime.UtcNow;
totalNumTicks = 0;
}
internal static GrainTimer FromTimerCallback(
TimerCallback callback,
object state,
TimeSpan dueTime,
TimeSpan period,
string name = null)
{
return new GrainTimer(
ob =>
{
if (callback != null)
callback(ob);
return TaskDone.Done;
},
state,
dueTime,
period,
name);
}
internal static GrainTimer FromTaskCallback(
Func<object, Task> asyncCallback,
object state,
TimeSpan dueTime,
TimeSpan period,
string name = null)
{
return new GrainTimer(asyncCallback, state, dueTime, period, name);
}
public void Start()
{
if (TimerAlreadyStopped)
throw new ObjectDisposedException(String.Format("The timer {0} was already disposed.", GetFullName()));
timer.Start(dueTime, timerFrequency);
}
public void Stop()
{
asyncCallback = null;
}
private async Task TimerTick(object state, ISchedulingContext context)
{
if (TimerAlreadyStopped)
return;
try
{
await RuntimeClient.Current.ExecAsync(() => ForwardToAsyncCallback(state), context, Name);
}
catch (InvalidSchedulingContextException exc)
{
logger.Error(ErrorCode.Timer_InvalidContext,
string.Format("Caught an InvalidSchedulingContextException on timer {0}, context is {1}. Going to dispose this timer!",
GetFullName(), context), exc);
DisposeTimer();
}
}
private async Task ForwardToAsyncCallback(object state)
{
// AsyncSafeTimer ensures that calls to this method are serialized.
if (TimerAlreadyStopped) return;
totalNumTicks++;
if (logger.IsVerbose3)
logger.Verbose3(ErrorCode.TimerBeforeCallback, "About to make timer callback for timer {0}", GetFullName());
try
{
RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake.
currentlyExecutingTickTask = asyncCallback(state);
await currentlyExecutingTickTask;
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerAfterCallback, "Completed timer callback for timer {0}", GetFullName());
}
catch (Exception exc)
{
logger.Error(
ErrorCode.Timer_GrainTimerCallbackError,
string.Format( "Caught and ignored exception: {0} with mesagge: {1} thrown from timer callback {2}",
exc.GetType(),
exc.Message,
GetFullName()),
exc);
}
finally
{
previousTickTime = DateTime.UtcNow;
currentlyExecutingTickTask = null;
// if this is not a repeating timer, then we can
// dispose of the timer.
if (timerFrequency == Constants.INFINITE_TIMESPAN)
DisposeTimer();
}
}
internal Task GetCurrentlyExecutingTickTask()
{
return currentlyExecutingTickTask ?? TaskDone.Done;
}
private string GetFullName()
{
return String.Format("GrainTimer.{0} TimerCallbackHandler:{1}->{2}",
Name == null ? "" : Name + ".",
(asyncCallback != null && asyncCallback.Target != null) ? asyncCallback.Target.ToString() : "",
(asyncCallback != null && asyncCallback.Method != null) ? asyncCallback.Method.ToString() : "");
}
internal int GetNumTicks()
{
return totalNumTicks;
}
// The reason we need to check CheckTimerFreeze on both the SafeTimer and this GrainTimer
// is that SafeTimer may tick OK (no starvation by .NET thread pool), but then scheduler.QueueWorkItem
// may not execute and starve this GrainTimer callback.
internal bool CheckTimerFreeze(DateTime lastCheckTime)
{
if (TimerAlreadyStopped) return true;
// check underlying SafeTimer (checking that .NET thread pool does not starve this timer)
if (!timer.CheckTimerFreeze(lastCheckTime, () => Name)) return false;
// if SafeTimer failed the check, no need to check GrainTimer too, since it will fail as well.
// check myself (checking that scheduler.QueueWorkItem does not starve this timer)
return SafeTimerBase.CheckTimerDelay(previousTickTime, totalNumTicks,
dueTime, timerFrequency, logger, GetFullName, ErrorCode.Timer_TimerInsideGrainIsNotTicking, true);
}
internal bool CheckTimerDelay()
{
return SafeTimerBase.CheckTimerDelay(previousTickTime, totalNumTicks,
dueTime, timerFrequency, logger, GetFullName, ErrorCode.Timer_TimerInsideGrainIsNotTicking, false);
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Maybe called by finalizer thread with disposing=false. As per guidelines, in such a case do not touch other objects.
// Dispose() may be called multiple times
protected virtual void Dispose(bool disposing)
{
if (disposing)
DisposeTimer();
asyncCallback = null;
}
private void DisposeTimer()
{
var tmp = timer;
if (tmp == null) return;
Utils.SafeExecute(tmp.Dispose);
timer = null;
asyncCallback = null;
if (activationData != null)
activationData.OnTimerDisposed(this);
}
#endregion
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
[CustomEditor(typeof(AndroidNativeSettings))]
public class AndroidNativeSettingsEditor : Editor {
GUIContent GamesApiLabel = new GUIContent("Enable Games API [?]:", "API used for achivements and leaderboards");
GUIContent AppSateApiLabel = new GUIContent("Enable App State API [?]:", "API used for cloud data save");
GUIContent Base64KeyLabel = new GUIContent("Base64 Key[?]:", "Base64 Key app key.");
GUIContent SdkVersion = new GUIContent("Plugin Version [?]", "This is Plugin version. If you have problems or compliments please include this so we know exactly what version to look out for.");
GUIContent SupportEmail = new GUIContent("Support [?]", "If you have any technical quastion, feel free to drop an e-mail");
private AndroidNativeSettings settings;
private const string version_info_file = "Plugins/StansAssets/Versions/AN_VersionInfo.txt";
public override void OnInspectorGUI() {
settings = target as AndroidNativeSettings;
GUI.changed = false;
GeneralOptions();
PlayServiceSettings();
EditorGUILayout.Space();
BillingSettings();
EditorGUILayout.Space();
SocialPlatfromSettingsEditor.FacebookSettings();
EditorGUILayout.Space();
SocialPlatfromSettingsEditor.TwitterSettings();
EditorGUILayout.Space();
AboutGUI();
if(GUI.changed) {
DirtyEditor();
}
}
public static bool IsInstalled {
get {
if(FileStaticAPI.IsFileExists(PluginsInstalationUtil.ANDROID_DESTANATION_PATH + "androidnative.jar")) {
return true;
} else {
return false;
}
}
}
public static bool IsUpToDate {
get {
if(AndroidNativeSettings.VERSION_NUMBER.Equals(DataVersion)) {
return true;
} else {
return false;
}
}
}
public static string DataVersion {
get {
if(FileStaticAPI.IsFileExists(version_info_file)) {
return FileStaticAPI.Read(version_info_file);
} else {
return "Unknown";
}
}
}
public static void UpdateVersionInfo() {
FileStaticAPI.Write(version_info_file, AndroidNativeSettings.VERSION_NUMBER);
}
private void GeneralOptions() {
if(!IsInstalled) {
EditorGUILayout.HelpBox("Install Required ", MessageType.Error);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Space();
Color c = GUI.color;
GUI.color = Color.cyan;
if(GUILayout.Button("Install Plugin", GUILayout.Width(120))) {
PluginsInstalationUtil.Android_InstallPlugin();
UpdateVersionInfo();
}
GUI.color = c;
EditorGUILayout.EndHorizontal();
}
if(IsInstalled) {
if(!IsUpToDate) {
EditorGUILayout.HelpBox("Update Required \nResources version: " + DataVersion + " Plugin version: " + AndroidNativeSettings.VERSION_NUMBER, MessageType.Warning);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Space();
Color c = GUI.color;
GUI.color = Color.cyan;
if(GUILayout.Button("Update to " + AndroidNativeSettings.VERSION_NUMBER, GUILayout.Width(250))) {
PluginsInstalationUtil.Android_UpdatePlugin();
UpdateVersionInfo();
}
GUI.color = c;
EditorGUILayout.Space();
EditorGUILayout.EndHorizontal();
} else {
EditorGUILayout.HelpBox("Android Native Plugin v" + AndroidNativeSettings.VERSION_NUMBER + " is installed", MessageType.Info);
Actions();
}
}
EditorGUILayout.Space();
}
private void Actions() {
EditorGUILayout.Space();
AndroidNativeSettings.Instance.ShowActions = EditorGUILayout.Foldout(AndroidNativeSettings.Instance.ShowActions, "More Actions");
if(AndroidNativeSettings.Instance.ShowActions) {
if(!FileStaticAPI.IsFolderExists("Facebook")) {
GUI.enabled = false;
}
if(GUILayout.Button("Remove Facebook SDK", GUILayout.Width(160))) {
bool result = EditorUtility.DisplayDialog(
"Removing Facebook SDK",
"Warning action can not be undone without reimporting the plugin",
"Remove",
"Cansel");
if(result) {
FileStaticAPI.DeleteFolder(PluginsInstalationUtil.ANDROID_DESTANATION_PATH + "facebook");
FileStaticAPI.DeleteFolder("Facebook");
FileStaticAPI.DeleteFolder("Extensions/GooglePlayCommon/Social/Facebook");
FileStaticAPI.DeleteFile("Extensions/AndroidNative/xExample/Scripts/Social/FacebookAndroidUseExample.cs");
}
}
GUI.enabled = true;
}
}
private void PlayServiceSettings() {
EditorGUILayout.HelpBox("(Optional) PlayService Parameters", MessageType.None);
AndroidNativeSettings.Instance.ShowPSSettings = EditorGUILayout.Foldout(AndroidNativeSettings.Instance.ShowPSSettings, "PlayService Settings");
if(AndroidNativeSettings.Instance.ShowPSSettings) {
EditorGUILayout.LabelField("API:");
EditorGUI.indentLevel++;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(GamesApiLabel);
settings.EnableGamesAPI = EditorGUILayout.Toggle(settings.EnableGamesAPI);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(AppSateApiLabel);
settings.EnableAppStateAPI = EditorGUILayout.Toggle(settings.EnableAppStateAPI);
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel--;
EditorGUILayout.LabelField("Auto Image Loading:");
EditorGUI.indentLevel++;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Profile Icons");
settings.LoadProfileIcons = EditorGUILayout.Toggle(settings.LoadProfileIcons);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Profile Hi-res Images");
settings.LoadProfileImages = EditorGUILayout.Toggle(settings.LoadProfileImages);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Event Icons");
settings.LoadEventsIcons = EditorGUILayout.Toggle(settings.LoadEventsIcons);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Quest Icons");
settings.LoadQuestsIcons = EditorGUILayout.Toggle(settings.LoadQuestsIcons);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Quest Banners");
settings.LoadQuestsImages = EditorGUILayout.Toggle(settings.LoadQuestsImages);
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel--;
}
}
private void BillingSettings() {
EditorGUILayout.HelpBox("(Optional) In-app Billing Parameters", MessageType.None);
AndroidNativeSettings.Instance.ShowStoreKitParams = EditorGUILayout.Foldout(AndroidNativeSettings.Instance.ShowStoreKitParams, "Billing Settings");
if(AndroidNativeSettings.Instance.ShowStoreKitParams) {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(Base64KeyLabel);
settings.base64EncodedPublicKey = EditorGUILayout.TextField(settings.base64EncodedPublicKey);
EditorGUILayout.EndHorizontal();
if(settings.InAppProducts.Count == 0) {
EditorGUILayout.HelpBox("No products added", MessageType.Warning);
}
int i = 0;
foreach(string str in settings.InAppProducts) {
EditorGUILayout.BeginHorizontal();
settings.InAppProducts[i] = EditorGUILayout.TextField(settings.InAppProducts[i]);
if(GUILayout.Button("Remove", GUILayout.Width(80))) {
settings.InAppProducts.Remove(str);
break;
}
EditorGUILayout.EndHorizontal();
i++;
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Space();
if(GUILayout.Button("Add", GUILayout.Width(80))) {
settings.InAppProducts.Add("");
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
}
}
private void AboutGUI() {
EditorGUILayout.HelpBox("About the Plugin", MessageType.None);
SelectableLabelField(SdkVersion, AndroidNativeSettings.VERSION_NUMBER);
SelectableLabelField(SupportEmail, "stans.assets@gmail.com");
}
private void SelectableLabelField(GUIContent label, string value) {
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(label, GUILayout.Width(180), GUILayout.Height(16));
EditorGUILayout.SelectableLabel(value, GUILayout.Height(16));
EditorGUILayout.EndHorizontal();
}
private static void DirtyEditor() {
#if UNITY_EDITOR
EditorUtility.SetDirty(AndroidNativeSettings.Instance);
#endif
}
}
| |
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class Uni2DEditorSmoothBindingUtils
{
///// Enums /////
public enum BoneEditMode
{
None,
Posing,
Anim
}
// Describes the various bone handles
public enum BoneHandle
{
None,
OuterDisc,
InnerDisc,
Link
};
// The bone editor tools
public enum BoneEditorTool
{
Select,
Move,
Create
};
// Pick search radius
public const float bonePosingPickRadius = 20.0f;
public const float boneAnimPickRadius = 5.0f;
public const float boneLinkAnimPickRadius = 5.0f;
public const float boneLinkPosingPickRadius = 5.0f;
public static float BoneInfluenceDistanceFunc( float a_fDistance, float a_fAlpha )
{
return 1.0f / Mathf.Pow( a_fDistance, a_fAlpha );
}
// Adds a bone to a sprite from a given mouse GUI position
public static Uni2DSmoothBindingBone AddBoneToSprite( Uni2DSprite a_rSprite, Vector2 a_f2MouseGUIPos, Uni2DSmoothBindingBone a_rBoneRoot )
{
Transform rSpriteTransform = a_rSprite.transform;
Ray oWorldRay = HandleUtility.GUIPointToWorldRay( a_f2MouseGUIPos );
Plane oSpritePlane = new Plane( rSpriteTransform.forward, rSpriteTransform.position ); // INFO: normal specific to Uni2D's planes
float fDistance;
if( oSpritePlane.Raycast( oWorldRay, out fDistance ) )
{
Uni2DSmoothBindingBone oBone;
if( a_rBoneRoot == null )
{
oBone = Uni2DEditorSmoothBindingUtils.CreateNewBone( a_rSprite );
}
else
{
switch( a_rBoneRoot.ChildCount )
{
case 0:
{
// Add child
oBone = Uni2DEditorSmoothBindingUtils.CreateNewBone(a_rSprite, a_rBoneRoot);
}
break;
case 1:
{
// Create branch for existing child + add another one
Uni2DSmoothBindingBone oFakeParent1 = Uni2DEditorSmoothBindingUtils.CreateNewBone(a_rSprite, a_rBoneRoot, true);
Uni2DSmoothBindingBone oFakeParent2 = Uni2DEditorSmoothBindingUtils.CreateNewBone(a_rSprite, a_rBoneRoot, true);
a_rBoneRoot.Children[ 0 ].Parent = oFakeParent1;
oBone = Uni2DEditorSmoothBindingUtils.CreateNewBone(a_rSprite, oFakeParent2);
}
break;
default:
{
// Add branch
Uni2DSmoothBindingBone oFakeParent = Uni2DEditorSmoothBindingUtils.CreateNewBone(a_rSprite, a_rBoneRoot, true );
oBone = Uni2DEditorSmoothBindingUtils.CreateNewBone(a_rSprite, oFakeParent);
}
break;
}
}
oBone.transform.position = oWorldRay.GetPoint( fDistance );
return oBone;
}
return null;
}
public static void DeleteBone( Uni2DSprite a_rSprite, Uni2DSmoothBindingBone a_rBoneToDelete )
{
if( a_rBoneToDelete != null )
{
a_rSprite.RemoveBone(a_rBoneToDelete);
Uni2DSmoothBindingBone rBoneParent = a_rBoneToDelete.Parent;
// Need to pack bone hierarchy
if( rBoneParent != null && rBoneParent.IsFakeRootBone )
{
Uni2DSmoothBindingBone rBoneGrandParent = rBoneParent.Parent;
Object.DestroyImmediate( rBoneParent.gameObject );
// We broke the branch => flatten bone hierarchy
if( rBoneGrandParent != null && rBoneGrandParent.IsBranchBone == false )
{
Uni2DSmoothBindingBone rFakeParent = rBoneGrandParent.Children[ 0 ];
rFakeParent.Children[ 0 ].Parent = rBoneGrandParent;
Object.DestroyImmediate( rFakeParent.gameObject );
}
}
else
{
Object.DestroyImmediate( a_rBoneToDelete.gameObject );
}
}
}
///// Bone creation /////
private static Uni2DSmoothBindingBone CreateNewBone(Uni2DSprite a_rSprite, Transform a_rTransform, bool a_bCreateFakeBone = false )
{
GameObject oBoneGameObject = new GameObject( );
Transform oBoneTransform = oBoneGameObject.transform;
Uni2DSmoothBindingBone oBone = oBoneGameObject.AddComponent<Uni2DSmoothBindingBone>( );
oBoneGameObject.name = ( a_bCreateFakeBone ? "Uni2DFakeBone_" : "Uni2DBone_" ) + Mathf.Abs( oBoneGameObject.GetInstanceID( ) );
oBoneTransform.parent = a_rTransform;
oBoneTransform.localPosition = Vector3.zero;
oBoneTransform.localRotation = Quaternion.identity;
oBoneTransform.localScale = Vector3.one;
a_rSprite.AddBone(oBone);
return oBone;
}
public static Uni2DSmoothBindingBone CreateNewBone(Uni2DSprite a_rSprite, Uni2DSmoothBindingBone a_rBoneParent, bool a_bCreateFakeBone = false)
{
return Uni2DEditorSmoothBindingUtils.CreateNewBone(a_rSprite, a_rBoneParent.transform, a_bCreateFakeBone);
}
public static Uni2DSmoothBindingBone CreateNewBone(Uni2DSprite a_rSprite)
{
Uni2DSmoothBindingBone rBone = Uni2DEditorSmoothBindingUtils.CreateNewBone(a_rSprite, a_rSprite.transform, false);
return rBone;
}
///// Picking /////
private static Uni2DSmoothBindingBone PickNearestBone( Uni2DSprite a_rSprite,
Vector2 a_f2MouseGUIPos,
out BoneHandle a_ePickedHandle,
Uni2DSmoothBindingBone a_rExclude = null,
bool a_bAlsoPickBoneLink = false,
float a_fBonePickRadius = Uni2DEditorSmoothBindingUtils.bonePosingPickRadius,
float a_fBoneLinkPickRadius = Uni2DEditorSmoothBindingUtils.boneLinkAnimPickRadius )
{
Uni2DSmoothBindingBone rNearestBone = null;
Uni2DSmoothBindingBone rNearestBoneLink = null;
// Squarred pick radius
float fMinSqrBoneDistance = a_fBonePickRadius * a_fBonePickRadius;
float fMinBoneLinkDistance = a_fBoneLinkPickRadius;
List<Uni2DSmoothBindingBone> rBones = a_rSprite.Bones; //rSpriteTransform.GetComponentsInChildren<Transform>( false ).Except( oBonesToExclude ).ToArray( );
// Look for nearest bone
for( int iBoneIndex = 0, iBoneCount = rBones.Count; iBoneIndex < iBoneCount; ++iBoneIndex )
{
Uni2DSmoothBindingBone rBone = rBones[ iBoneIndex ];
if( a_rExclude != rBone && rBone.IsFakeRootBone == false )
{
Vector2 f2BoneGUIPos = HandleUtility.WorldToGUIPoint( rBone.transform.position );
Vector2 f2BoneToMouseGUI = a_f2MouseGUIPos - f2BoneGUIPos;
float fSqrDistance = f2BoneToMouseGUI.sqrMagnitude;
// New min/nearest
if( fSqrDistance < fMinSqrBoneDistance )
{
rNearestBone = rBone;
fMinSqrBoneDistance = fSqrDistance;
}
// Look for nearest bone link
Uni2DSmoothBindingBone rBoneParent = rBone.Parent;
if( a_bAlsoPickBoneLink && rBoneParent != null )
{
float fLinkDistance = HandleUtility.DistancePointToLineSegment( a_f2MouseGUIPos,
f2BoneGUIPos,
HandleUtility.WorldToGUIPoint( rBoneParent.transform.position ) );
if( fLinkDistance < fMinBoneLinkDistance )
{
fMinBoneLinkDistance = fLinkDistance;
rNearestBoneLink = rBone;
}
}
}
}
// Picking result
if( rNearestBone == null && rNearestBoneLink == null )
{
a_ePickedHandle = BoneHandle.None;
}
else if( rNearestBone != null )
{
if( fMinSqrBoneDistance <= a_fBonePickRadius * a_fBonePickRadius * 0.25f )
{
a_ePickedHandle = /*invertActionAreas == false ?*/ BoneHandle.InnerDisc; //: BoneHandle.OuterDisc;
}
else
{
a_ePickedHandle = /*invertActionAreas == false ?*/ BoneHandle.OuterDisc; //: BoneHandle.InnerDisc;
}
}
else
{
rNearestBone = rNearestBoneLink;
a_ePickedHandle = BoneHandle.Link;
}
return rNearestBone;
}
// Specialized picking call used in anim mode
public static Uni2DSmoothBindingBone PickNearestBoneInAnimMode( Uni2DSprite a_rSprite,
Vector2 a_f2MouseGUIPos,
out BoneHandle a_ePickedHandle,
Uni2DSmoothBindingBone a_rExclude = null )
{
return Uni2DEditorSmoothBindingUtils.PickNearestBone( a_rSprite,
a_f2MouseGUIPos,
out a_ePickedHandle,
a_rExclude,
true,
Uni2DEditorSmoothBindingUtils.boneAnimPickRadius,
Uni2DEditorSmoothBindingUtils.boneLinkAnimPickRadius );
}
// Specialized picking call used in posing mode
public static Uni2DSmoothBindingBone PickNearestBoneInPosingMode( Uni2DSprite a_rSprite,
Vector2 a_f2MouseGUIPos,
out BoneHandle a_ePickedHandle,
Uni2DSmoothBindingBone a_rExclude = null )
{
return Uni2DEditorSmoothBindingUtils.PickNearestBone( a_rSprite,
a_f2MouseGUIPos,
out a_ePickedHandle,
a_rExclude,
true,
Uni2DEditorSmoothBindingUtils.bonePosingPickRadius,
Uni2DEditorSmoothBindingUtils.boneLinkPosingPickRadius );
}
// Specialized picking call used in posing mode and when drawing disc handles
public static Uni2DSmoothBindingBone PickNearestBoneArticulationInPosingMode( Uni2DSprite a_rSprite,
Vector2 a_f2MouseGUIPos,
out BoneHandle a_ePickedHandle,
Uni2DSmoothBindingBone a_rExclude = null )
{
return Uni2DEditorSmoothBindingUtils.PickNearestBone( a_rSprite,
a_f2MouseGUIPos,
out a_ePickedHandle,
a_rExclude,
false,
Uni2DEditorSmoothBindingUtils.bonePosingPickRadius,
Uni2DEditorSmoothBindingUtils.boneLinkPosingPickRadius );
}
/*
public static void DumpHeatMap( string a_rFilename )
{
const int c_iTextureWidth = 1024;
const int c_iTextureHeight = 1024;
// WARNING: hardcoded min/max values. Edit them for each texture you want to dump
const float c_fMinWidth = 0.0f;
const float c_fMaxWidth = 512.0f;
const float c_fMinHeight = 0.0f;
const float c_fMaxHeight = 512.0f;
const float c_fWidthRange = c_fMaxWidth - c_fMinWidth;
const float c_fHeigthRange = c_fMaxHeight - c_fMinHeight;
Dictionary<Transform, Color[ ]> oHeatMapsDict = new Dictionary<Transform, Color[ ]>( );
for( int iY = 0; iY < c_iTextureHeight; ++iY )
{
for( int iX = 0; iX < c_iTextureWidth; ++iX )
{
Vector3 f3VertexCoords = new Vector3( c_fMinWidth + ( ( iX * c_fWidthRange ) / (float) c_iTextureWidth ),
c_fMinHeight + ( ( iY * c_fHeigthRange ) / (float) c_iTextureHeight ),
0.0f );
Dictionary<Transform,float> rBoneInfluenceDict = this.GetBonesInfluences( f3VertexCoords );
float fInvDistanceSum = 1.0f / rBoneInfluenceDict.Sum( x => x.Value );
foreach( KeyValuePair<Transform, float> rBoneInfluencePair in rBoneInfluenceDict )
{
Color[ ] oHeatMapPixels32;
if( oHeatMapsDict.TryGetValue( rBoneInfluencePair.Key, out oHeatMapPixels32 ) == false )
{
oHeatMapPixels32 = new Color[ c_iTextureWidth * c_iTextureHeight ];
}
float fBoneInfluence = rBoneInfluencePair.Value * fInvDistanceSum;
oHeatMapPixels32[ iX + iY * c_iTextureWidth ] = Color.white * fBoneInfluence;
oHeatMapsDict[ rBoneInfluencePair.Key ] = oHeatMapPixels32;
}
}
}
foreach( KeyValuePair<Transform, Color[ ]> rBoneHeatMapPair in oHeatMapsDict )
{
Texture2D oHeatMap = new Texture2D( c_iTextureWidth, c_iTextureHeight, TextureFormat.RGB24, false );
oHeatMap.SetPixels( rBoneHeatMapPair.Value );
oHeatMap.Apply( );
FileStream oFileStream = new FileStream( Application.dataPath + "/" + a_rFilename + "_" + rBoneHeatMapPair.Key.name + rBoneHeatMapPair.Key.GetInstanceID( ).ToString( ) + ".png", FileMode.OpenOrCreate );
BinaryWriter oBinaryWriter = new BinaryWriter( oFileStream );
oBinaryWriter.Write( oHeatMap.EncodeToPNG( ) );
oBinaryWriter.Close( );
oFileStream.Close( );
AssetDatabase.ImportAsset( "Assets/" + a_rFilename + "_" + rBoneHeatMapPair.Key.name + rBoneHeatMapPair.Key.GetInstanceID( ).ToString( ) + ".png" );
}
}
*/
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace System.Linq.Expressions
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal sealed class DebugViewWriter : ExpressionVisitor
{
[Flags]
private enum Flow
{
None,
Space,
NewLine,
Break = 0x8000 // newline if column > MaxColumn
};
private const int Tab = 4;
private const int MaxColumn = 120;
private readonly TextWriter _out;
private int _column;
private readonly Stack<int> _stack = new Stack<int>();
private int _delta;
private Flow _flow;
// All the unique lambda expressions in the ET, will be used for displaying all
// the lambda definitions.
private Queue<LambdaExpression> _lambdas;
// Associate every unique anonymous LambdaExpression in the tree with an integer.
// The id is used to create a name for the anonymous lambda.
//
private Dictionary<LambdaExpression, int> _lambdaIds;
// Associate every unique anonymous parameter or variable in the tree with an integer.
// The id is used to create a name for the anonymous parameter or variable.
//
private Dictionary<ParameterExpression, int> _paramIds;
// Associate every unique anonymous LabelTarget in the tree with an integer.
// The id is used to create a name for the anonymous LabelTarget.
//
private Dictionary<LabelTarget, int> _labelIds;
private DebugViewWriter(TextWriter file)
{
_out = file;
}
private int Base => _stack.Count > 0 ? _stack.Peek() : 0;
private int Delta => _delta;
private int Depth => Base + Delta;
private void Indent()
{
_delta += Tab;
}
private void Dedent()
{
_delta -= Tab;
}
private void NewLine()
{
_flow = Flow.NewLine;
}
private static int GetId<T>(T e, ref Dictionary<T, int> ids)
{
if (ids == null)
{
ids = new Dictionary<T, int>();
ids.Add(e, 1);
return 1;
}
else
{
int id;
if (!ids.TryGetValue(e, out id))
{
// e is met the first time
id = ids.Count + 1;
ids.Add(e, id);
}
return id;
}
}
private int GetLambdaId(LambdaExpression le)
{
Debug.Assert(string.IsNullOrEmpty(le.Name));
return GetId(le, ref _lambdaIds);
}
private int GetParamId(ParameterExpression p)
{
Debug.Assert(string.IsNullOrEmpty(p.Name));
return GetId(p, ref _paramIds);
}
private int GetLabelTargetId(LabelTarget target)
{
Debug.Assert(string.IsNullOrEmpty(target.Name));
return GetId(target, ref _labelIds);
}
/// <summary>
/// Write out the given AST
/// </summary>
internal static void WriteTo(Expression node, TextWriter writer)
{
Debug.Assert(node != null);
Debug.Assert(writer != null);
new DebugViewWriter(writer).WriteTo(node);
}
private void WriteTo(Expression node)
{
var lambda = node as LambdaExpression;
if (lambda != null)
{
WriteLambda(lambda);
}
else
{
Visit(node);
Debug.Assert(_stack.Count == 0);
}
//
// Output all lambda expression definitions.
// in the order of their appearances in the tree.
//
while (_lambdas != null && _lambdas.Count > 0)
{
WriteLine();
WriteLine();
WriteLambda(_lambdas.Dequeue());
}
}
#region The printing code
private void Out(string s)
{
Out(Flow.None, s, Flow.None);
}
private void Out(Flow before, string s)
{
Out(before, s, Flow.None);
}
private void Out(string s, Flow after)
{
Out(Flow.None, s, after);
}
private void Out(Flow before, string s, Flow after)
{
switch (GetFlow(before))
{
case Flow.None:
break;
case Flow.Space:
Write(" ");
break;
case Flow.NewLine:
WriteLine();
Write(new string(' ', Depth));
break;
}
Write(s);
_flow = after;
}
private void WriteLine()
{
_out.WriteLine();
_column = 0;
}
private void Write(string s)
{
_out.Write(s);
_column += s.Length;
}
private Flow GetFlow(Flow flow)
{
Flow last = CheckBreak(_flow);
flow = CheckBreak(flow);
// Get the biggest flow that is requested None < Space < NewLine
return (Flow)System.Math.Max((int)last, (int)flow);
}
private Flow CheckBreak(Flow flow)
{
if ((flow & Flow.Break) != 0)
{
if (_column > (MaxColumn + Depth))
{
flow = Flow.NewLine;
}
else
{
flow &= ~Flow.Break;
}
}
return flow;
}
#endregion
#region The AST Output
private void VisitExpressions<T>(char open, IReadOnlyList<T> expressions) where T : Expression
{
VisitExpressions<T>(open, ',', expressions);
}
private void VisitExpressions<T>(char open, char separator, IReadOnlyList<T> expressions) where T : Expression
{
VisitExpressions(open, separator, expressions, e => Visit(e));
}
private void VisitDeclarations(IReadOnlyList<ParameterExpression> expressions)
{
VisitExpressions('(', ',', expressions, variable =>
{
Out(variable.Type.ToString());
if (variable.IsByRef)
{
Out("&");
}
Out(" ");
VisitParameter(variable);
});
}
private void VisitExpressions<T>(char open, char separator, IReadOnlyList<T> expressions, Action<T> visit)
{
Out(open.ToString());
if (expressions != null)
{
Indent();
bool isFirst = true;
foreach (T e in expressions)
{
if (isFirst)
{
if (open == '{' || expressions.Count > 1)
{
NewLine();
}
isFirst = false;
}
else
{
Out(separator.ToString(), Flow.NewLine);
}
visit(e);
}
Dedent();
}
char close;
switch (open)
{
case '(': close = ')'; break;
case '{': close = '}'; break;
case '[': close = ']'; break;
default: throw ContractUtils.Unreachable;
}
if (open == '{')
{
NewLine();
}
Out(close.ToString(), Flow.Break);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected internal override Expression VisitBinary(BinaryExpression node)
{
if (node.NodeType == ExpressionType.ArrayIndex)
{
ParenthesizedVisit(node, node.Left);
Out("[");
Visit(node.Right);
Out("]");
}
else
{
bool parenthesizeLeft = NeedsParentheses(node, node.Left);
bool parenthesizeRight = NeedsParentheses(node, node.Right);
string op;
Flow beforeOp = Flow.Space;
switch (node.NodeType)
{
case ExpressionType.Assign: op = "="; break;
case ExpressionType.Equal: op = "=="; break;
case ExpressionType.NotEqual: op = "!="; break;
case ExpressionType.AndAlso: op = "&&"; beforeOp = Flow.Break | Flow.Space; break;
case ExpressionType.OrElse: op = "||"; beforeOp = Flow.Break | Flow.Space; break;
case ExpressionType.GreaterThan: op = ">"; break;
case ExpressionType.LessThan: op = "<"; break;
case ExpressionType.GreaterThanOrEqual: op = ">="; break;
case ExpressionType.LessThanOrEqual: op = "<="; break;
case ExpressionType.Add: op = "+"; break;
case ExpressionType.AddAssign: op = "+="; break;
case ExpressionType.AddAssignChecked: op = "#+="; break;
case ExpressionType.AddChecked: op = "#+"; break;
case ExpressionType.Subtract: op = "-"; break;
case ExpressionType.SubtractAssign: op = "-="; break;
case ExpressionType.SubtractAssignChecked: op = "#-="; break;
case ExpressionType.SubtractChecked: op = "#-"; break;
case ExpressionType.Divide: op = "/"; break;
case ExpressionType.DivideAssign: op = "/="; break;
case ExpressionType.Modulo: op = "%"; break;
case ExpressionType.ModuloAssign: op = "%="; break;
case ExpressionType.Multiply: op = "*"; break;
case ExpressionType.MultiplyAssign: op = "*="; break;
case ExpressionType.MultiplyAssignChecked: op = "#*="; break;
case ExpressionType.MultiplyChecked: op = "#*"; break;
case ExpressionType.LeftShift: op = "<<"; break;
case ExpressionType.LeftShiftAssign: op = "<<="; break;
case ExpressionType.RightShift: op = ">>"; break;
case ExpressionType.RightShiftAssign: op = ">>="; break;
case ExpressionType.And: op = "&"; break;
case ExpressionType.AndAssign: op = "&="; break;
case ExpressionType.Or: op = "|"; break;
case ExpressionType.OrAssign: op = "|="; break;
case ExpressionType.ExclusiveOr: op = "^"; break;
case ExpressionType.ExclusiveOrAssign: op = "^="; break;
case ExpressionType.Power: op = "**"; break;
case ExpressionType.PowerAssign: op = "**="; break;
case ExpressionType.Coalesce: op = "??"; break;
default:
throw new InvalidOperationException();
}
if (parenthesizeLeft)
{
Out("(", Flow.None);
}
Visit(node.Left);
if (parenthesizeLeft)
{
Out(Flow.None, ")", Flow.Break);
}
Out(beforeOp, op, Flow.Space | Flow.Break);
if (parenthesizeRight)
{
Out("(", Flow.None);
}
Visit(node.Right);
if (parenthesizeRight)
{
Out(Flow.None, ")", Flow.Break);
}
}
return node;
}
protected internal override Expression VisitParameter(ParameterExpression node)
{
// Have '$' for the DebugView of ParameterExpressions
Out("$");
if (string.IsNullOrEmpty(node.Name))
{
// If no name if provided, generate a name as $var1, $var2.
// No guarantee for not having name conflicts with user provided variable names.
//
int id = GetParamId(node);
Out("var" + id);
}
else
{
Out(GetDisplayName(node.Name));
}
return node;
}
protected internal override Expression VisitLambda<T>(Expression<T> node)
{
Out(
string.Format(CultureInfo.CurrentCulture,
".Lambda {0}<{1}>",
GetLambdaName(node),
node.Type.ToString()
)
);
if (_lambdas == null)
{
_lambdas = new Queue<LambdaExpression>();
}
// N^2 performance, for keeping the order of the lambdas.
if (!_lambdas.Contains(node))
{
_lambdas.Enqueue(node);
}
return node;
}
private static bool IsSimpleExpression(Expression node)
{
var binary = node as BinaryExpression;
if (binary != null)
{
return !(binary.Left is BinaryExpression || binary.Right is BinaryExpression);
}
return false;
}
protected internal override Expression VisitConditional(ConditionalExpression node)
{
if (IsSimpleExpression(node.Test))
{
Out(".If (");
Visit(node.Test);
Out(") {", Flow.NewLine);
}
else
{
Out(".If (", Flow.NewLine);
Indent();
Visit(node.Test);
Dedent();
Out(Flow.NewLine, ") {", Flow.NewLine);
}
Indent();
Visit(node.IfTrue);
Dedent();
Out(Flow.NewLine, "} .Else {", Flow.NewLine);
Indent();
Visit(node.IfFalse);
Dedent();
Out(Flow.NewLine, "}");
return node;
}
protected internal override Expression VisitConstant(ConstantExpression node)
{
object value = node.Value;
if (value == null)
{
Out("null");
}
else if ((value is string) && node.Type == typeof(string))
{
Out(string.Format(
CultureInfo.CurrentCulture,
"\"{0}\"",
value));
}
else if ((value is char) && node.Type == typeof(char))
{
Out(string.Format(
CultureInfo.CurrentCulture,
"'{0}'",
value));
}
else if ((value is int) && node.Type == typeof(int)
|| (value is bool) && node.Type == typeof(bool))
{
Out(value.ToString());
}
else
{
string suffix = GetConstantValueSuffix(node.Type);
if (suffix != null)
{
Out(value.ToString());
Out(suffix);
}
else
{
Out(string.Format(
CultureInfo.CurrentCulture,
".Constant<{0}>({1})",
node.Type.ToString(),
value));
}
}
return node;
}
private static string GetConstantValueSuffix(Type type)
{
if (type == typeof(uint))
{
return "U";
}
if (type == typeof(long))
{
return "L";
}
if (type == typeof(ulong))
{
return "UL";
}
if (type == typeof(double))
{
return "D";
}
if (type == typeof(float))
{
return "F";
}
if (type == typeof(decimal))
{
return "M";
}
return null;
}
protected internal override Expression VisitRuntimeVariables(RuntimeVariablesExpression node)
{
Out(".RuntimeVariables");
VisitExpressions('(', node.Variables);
return node;
}
// Prints ".instanceField" or "declaringType.staticField"
private void OutMember(Expression node, Expression instance, MemberInfo member)
{
if (instance != null)
{
ParenthesizedVisit(node, instance);
Out("." + member.Name);
}
else
{
// For static members, include the type name
Out(member.DeclaringType.ToString() + "." + member.Name);
}
}
protected internal override Expression VisitMember(MemberExpression node)
{
OutMember(node, node.Expression, node.Member);
return node;
}
protected internal override Expression VisitInvocation(InvocationExpression node)
{
Out(".Invoke ");
ParenthesizedVisit(node, node.Expression);
VisitExpressions('(', node.Arguments);
return node;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static bool NeedsParentheses(Expression parent, Expression child)
{
Debug.Assert(parent != null);
if (child == null)
{
return false;
}
// Some nodes always have parentheses because of how they are
// displayed, for example: ".Unbox(obj.Foo)"
switch (parent.NodeType)
{
case ExpressionType.Increment:
case ExpressionType.Decrement:
case ExpressionType.IsTrue:
case ExpressionType.IsFalse:
case ExpressionType.Unbox:
return true;
}
int childOpPrec = GetOperatorPrecedence(child);
int parentOpPrec = GetOperatorPrecedence(parent);
if (childOpPrec == parentOpPrec)
{
// When parent op and child op has the same precedence,
// we want to be a little conservative to have more clarity.
// Parentheses are not needed if
// 1) Both ops are &&, ||, &, |, or ^, all of them are the only
// op that has the precedence.
// 2) Parent op is + or *, e.g. x + (y - z) can be simplified to
// x + y - z.
// 3) Parent op is -, / or %, and the child is the left operand.
// In this case, if left and right operand are the same, we don't
// remove parenthesis, e.g. (x + y) - (x + y)
//
switch (parent.NodeType)
{
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
case ExpressionType.And:
case ExpressionType.Or:
case ExpressionType.ExclusiveOr:
// Since these ops are the only ones on their precedence,
// the child op must be the same.
Debug.Assert(child.NodeType == parent.NodeType);
// We remove the parenthesis, e.g. x && y && z
return false;
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return false;
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
BinaryExpression binary = parent as BinaryExpression;
Debug.Assert(binary != null);
// Need to have parenthesis for the right operand.
return child == binary.Right;
}
return true;
}
// Special case: negate of a constant needs parentheses, to
// disambiguate it from a negative constant.
if (child != null && child.NodeType == ExpressionType.Constant &&
(parent.NodeType == ExpressionType.Negate || parent.NodeType == ExpressionType.NegateChecked))
{
return true;
}
// If the parent op has higher precedence, need parentheses for the child.
return childOpPrec < parentOpPrec;
}
// the greater the higher
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static int GetOperatorPrecedence(Expression node)
{
// Roughly matches C# operator precedence, with some additional
// operators. Also things which are not binary/unary expressions,
// such as conditional and type testing, don't use this mechanism.
switch (node.NodeType)
{
// Assignment
case ExpressionType.Assign:
case ExpressionType.ExclusiveOrAssign:
case ExpressionType.AddAssign:
case ExpressionType.AddAssignChecked:
case ExpressionType.SubtractAssign:
case ExpressionType.SubtractAssignChecked:
case ExpressionType.DivideAssign:
case ExpressionType.ModuloAssign:
case ExpressionType.MultiplyAssign:
case ExpressionType.MultiplyAssignChecked:
case ExpressionType.LeftShiftAssign:
case ExpressionType.RightShiftAssign:
case ExpressionType.AndAssign:
case ExpressionType.OrAssign:
case ExpressionType.PowerAssign:
case ExpressionType.Coalesce:
return 1;
// Conditional (?:) would go here
// Conditional OR
case ExpressionType.OrElse:
return 2;
// Conditional AND
case ExpressionType.AndAlso:
return 3;
// Logical OR
case ExpressionType.Or:
return 4;
// Logical XOR
case ExpressionType.ExclusiveOr:
return 5;
// Logical AND
case ExpressionType.And:
return 6;
// Equality
case ExpressionType.Equal:
case ExpressionType.NotEqual:
return 7;
// Relational, type testing
case ExpressionType.GreaterThan:
case ExpressionType.LessThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThanOrEqual:
case ExpressionType.TypeAs:
case ExpressionType.TypeIs:
case ExpressionType.TypeEqual:
return 8;
// Shift
case ExpressionType.LeftShift:
case ExpressionType.RightShift:
return 9;
// Additive
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
return 10;
// Multiplicative
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return 11;
// Unary
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.UnaryPlus:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.PreIncrementAssign:
case ExpressionType.PreDecrementAssign:
case ExpressionType.OnesComplement:
case ExpressionType.Increment:
case ExpressionType.Decrement:
case ExpressionType.IsTrue:
case ExpressionType.IsFalse:
case ExpressionType.Unbox:
case ExpressionType.Throw:
return 12;
// Power, which is not in C#
// But VB/Python/Ruby put it here, above unary.
case ExpressionType.Power:
return 13;
// Primary, which includes all other node types:
// member access, calls, indexing, new.
case ExpressionType.PostIncrementAssign:
case ExpressionType.PostDecrementAssign:
default:
return 14;
// These aren't expressions, so never need parentheses:
// constants, variables
case ExpressionType.Constant:
case ExpressionType.Parameter:
return 15;
}
}
private void ParenthesizedVisit(Expression parent, Expression nodeToVisit)
{
if (NeedsParentheses(parent, nodeToVisit))
{
Out("(");
Visit(nodeToVisit);
Out(")");
}
else
{
Visit(nodeToVisit);
}
}
protected internal override Expression VisitMethodCall(MethodCallExpression node)
{
Out(".Call ");
if (node.Object != null)
{
ParenthesizedVisit(node, node.Object);
}
else if (node.Method.DeclaringType != null)
{
Out(node.Method.DeclaringType.ToString());
}
else
{
Out("<UnknownType>");
}
Out(".");
Out(node.Method.Name);
VisitExpressions('(', node.Arguments);
return node;
}
protected internal override Expression VisitNewArray(NewArrayExpression node)
{
if (node.NodeType == ExpressionType.NewArrayBounds)
{
// .NewArray MyType[expr1, expr2]
Out(".NewArray " + node.Type.GetElementType().ToString());
VisitExpressions('[', node.Expressions);
}
else
{
// .NewArray MyType {expr1, expr2}
Out(".NewArray " + node.Type.ToString(), Flow.Space);
VisitExpressions('{', node.Expressions);
}
return node;
}
protected internal override Expression VisitNew(NewExpression node)
{
Out(".New " + node.Type.ToString());
VisitExpressions('(', node.Arguments);
return node;
}
protected override ElementInit VisitElementInit(ElementInit node)
{
if (node.Arguments.Count == 1)
{
Visit(node.Arguments[0]);
}
else
{
VisitExpressions('{', node.Arguments);
}
return node;
}
protected internal override Expression VisitListInit(ListInitExpression node)
{
Visit(node.NewExpression);
VisitExpressions('{', ',', node.Initializers, e => VisitElementInit(e));
return node;
}
protected override MemberAssignment VisitMemberAssignment(MemberAssignment assignment)
{
Out(assignment.Member.Name);
Out(Flow.Space, "=", Flow.Space);
Visit(assignment.Expression);
return assignment;
}
protected override MemberListBinding VisitMemberListBinding(MemberListBinding binding)
{
Out(binding.Member.Name);
Out(Flow.Space, "=", Flow.Space);
VisitExpressions('{', ',', binding.Initializers, e => VisitElementInit(e));
return binding;
}
protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding)
{
Out(binding.Member.Name);
Out(Flow.Space, "=", Flow.Space);
VisitExpressions('{', ',', binding.Bindings, e => VisitMemberBinding(e));
return binding;
}
protected internal override Expression VisitMemberInit(MemberInitExpression node)
{
Visit(node.NewExpression);
VisitExpressions('{', ',', node.Bindings, e => VisitMemberBinding(e));
return node;
}
protected internal override Expression VisitTypeBinary(TypeBinaryExpression node)
{
ParenthesizedVisit(node, node.Expression);
switch (node.NodeType)
{
case ExpressionType.TypeIs:
Out(Flow.Space, ".Is", Flow.Space);
break;
case ExpressionType.TypeEqual:
Out(Flow.Space, ".TypeEqual", Flow.Space);
break;
}
Out(node.TypeOperand.ToString());
return node;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected internal override Expression VisitUnary(UnaryExpression node)
{
switch (node.NodeType)
{
case ExpressionType.Convert:
Out("(" + node.Type.ToString() + ")");
break;
case ExpressionType.ConvertChecked:
Out("#(" + node.Type.ToString() + ")");
break;
case ExpressionType.TypeAs:
break;
case ExpressionType.Not:
Out(node.Type == typeof(bool) ? "!" : "~");
break;
case ExpressionType.OnesComplement:
Out("~");
break;
case ExpressionType.Negate:
Out("-");
break;
case ExpressionType.NegateChecked:
Out("#-");
break;
case ExpressionType.UnaryPlus:
Out("+");
break;
case ExpressionType.ArrayLength:
break;
case ExpressionType.Quote:
Out("'");
break;
case ExpressionType.Throw:
if (node.Operand == null)
{
Out(".Rethrow");
}
else
{
Out(".Throw", Flow.Space);
}
break;
case ExpressionType.IsFalse:
Out(".IsFalse");
break;
case ExpressionType.IsTrue:
Out(".IsTrue");
break;
case ExpressionType.Decrement:
Out(".Decrement");
break;
case ExpressionType.Increment:
Out(".Increment");
break;
case ExpressionType.PreDecrementAssign:
Out("--");
break;
case ExpressionType.PreIncrementAssign:
Out("++");
break;
case ExpressionType.Unbox:
Out(".Unbox");
break;
}
ParenthesizedVisit(node, node.Operand);
switch (node.NodeType)
{
case ExpressionType.TypeAs:
Out(Flow.Space, ".As", Flow.Space | Flow.Break);
Out(node.Type.ToString());
break;
case ExpressionType.ArrayLength:
Out(".Length");
break;
case ExpressionType.PostDecrementAssign:
Out("--");
break;
case ExpressionType.PostIncrementAssign:
Out("++");
break;
}
return node;
}
protected internal override Expression VisitBlock(BlockExpression node)
{
Out(".Block");
// Display <type> if the type of the BlockExpression is different from the
// last expression's type in the block.
if (node.Type != node.GetExpression(node.ExpressionCount - 1).Type)
{
Out(string.Format(CultureInfo.CurrentCulture, "<{0}>", node.Type.ToString()));
}
VisitDeclarations(node.Variables);
Out(" ");
// Use ; to separate expressions in the block
VisitExpressions('{', ';', node.Expressions);
return node;
}
protected internal override Expression VisitDefault(DefaultExpression node)
{
Out(".Default(" + node.Type.ToString() + ")");
return node;
}
protected internal override Expression VisitLabel(LabelExpression node)
{
Out(".Label", Flow.NewLine);
Indent();
Visit(node.DefaultValue);
Dedent();
NewLine();
DumpLabel(node.Target);
return node;
}
protected internal override Expression VisitGoto(GotoExpression node)
{
Out("." + node.Kind.ToString(), Flow.Space);
Out(GetLabelTargetName(node.Target), Flow.Space);
Out("{", Flow.Space);
Visit(node.Value);
Out(Flow.Space, "}");
return node;
}
protected internal override Expression VisitLoop(LoopExpression node)
{
Out(".Loop", Flow.Space);
if (node.ContinueLabel != null)
{
DumpLabel(node.ContinueLabel);
}
Out(" {", Flow.NewLine);
Indent();
Visit(node.Body);
Dedent();
Out(Flow.NewLine, "}");
if (node.BreakLabel != null)
{
Out("", Flow.NewLine);
DumpLabel(node.BreakLabel);
}
return node;
}
protected override SwitchCase VisitSwitchCase(SwitchCase node)
{
foreach (Expression test in node.TestValues)
{
Out(".Case (");
Visit(test);
Out("):", Flow.NewLine);
}
Indent(); Indent();
Visit(node.Body);
Dedent(); Dedent();
NewLine();
return node;
}
protected internal override Expression VisitSwitch(SwitchExpression node)
{
Out(".Switch ");
Out("(");
Visit(node.SwitchValue);
Out(") {", Flow.NewLine);
Visit(node.Cases, VisitSwitchCase);
if (node.DefaultBody != null)
{
Out(".Default:", Flow.NewLine);
Indent(); Indent();
Visit(node.DefaultBody);
Dedent(); Dedent();
NewLine();
}
Out("}");
return node;
}
protected override CatchBlock VisitCatchBlock(CatchBlock node)
{
Out(Flow.NewLine, "} .Catch (" + node.Test.ToString());
if (node.Variable != null)
{
Out(Flow.Space, "");
VisitParameter(node.Variable);
}
if (node.Filter != null)
{
Out(") .If (", Flow.Break);
Visit(node.Filter);
}
Out(") {", Flow.NewLine);
Indent();
Visit(node.Body);
Dedent();
return node;
}
protected internal override Expression VisitTry(TryExpression node)
{
Out(".Try {", Flow.NewLine);
Indent();
Visit(node.Body);
Dedent();
Visit(node.Handlers, VisitCatchBlock);
if (node.Finally != null)
{
Out(Flow.NewLine, "} .Finally {", Flow.NewLine);
Indent();
Visit(node.Finally);
Dedent();
}
else if (node.Fault != null)
{
Out(Flow.NewLine, "} .Fault {", Flow.NewLine);
Indent();
Visit(node.Fault);
Dedent();
}
Out(Flow.NewLine, "}");
return node;
}
protected internal override Expression VisitIndex(IndexExpression node)
{
if (node.Indexer != null)
{
OutMember(node, node.Object, node.Indexer);
}
else
{
ParenthesizedVisit(node, node.Object);
}
VisitExpressions('[', node.Arguments);
return node;
}
protected internal override Expression VisitExtension(Expression node)
{
Out(string.Format(CultureInfo.CurrentCulture, ".Extension<{0}>", node.GetType().ToString()));
if (node.CanReduce)
{
Out(Flow.Space, "{", Flow.NewLine);
Indent();
Visit(node.Reduce());
Dedent();
Out(Flow.NewLine, "}");
}
return node;
}
protected internal override Expression VisitDebugInfo(DebugInfoExpression node)
{
Out(string.Format(
CultureInfo.CurrentCulture,
".DebugInfo({0}: {1}, {2} - {3}, {4})",
node.Document.FileName,
node.StartLine,
node.StartColumn,
node.EndLine,
node.EndColumn)
);
return node;
}
private void DumpLabel(LabelTarget target)
{
Out(string.Format(CultureInfo.CurrentCulture, ".LabelTarget {0}:", GetLabelTargetName(target)));
}
private string GetLabelTargetName(LabelTarget target)
{
if (string.IsNullOrEmpty(target.Name))
{
// Create the label target name as #Label1, #Label2, etc.
return "#Label" + GetLabelTargetId(target);
}
else
{
return GetDisplayName(target.Name);
}
}
private void WriteLambda(LambdaExpression lambda)
{
Out(
string.Format(
CultureInfo.CurrentCulture,
".Lambda {0}<{1}>",
GetLambdaName(lambda),
lambda.Type.ToString())
);
VisitDeclarations(lambda.Parameters);
Out(Flow.Space, "{", Flow.NewLine);
Indent();
Visit(lambda.Body);
Dedent();
Out(Flow.NewLine, "}");
Debug.Assert(_stack.Count == 0);
}
private string GetLambdaName(LambdaExpression lambda)
{
if (string.IsNullOrEmpty(lambda.Name))
{
return "#Lambda" + GetLambdaId(lambda);
}
return GetDisplayName(lambda.Name);
}
/// <summary>
/// Return true if the input string contains any whitespace character.
/// Otherwise false.
/// </summary>
private static bool ContainsWhiteSpace(string name)
{
foreach (char c in name)
{
if (char.IsWhiteSpace(c))
{
return true;
}
}
return false;
}
private static string QuoteName(string name)
{
return string.Format(CultureInfo.CurrentCulture, "'{0}'", name);
}
private static string GetDisplayName(string name)
{
if (ContainsWhiteSpace(name))
{
// if name has whitespace in it, quote it
return QuoteName(name);
}
else
{
return name;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using ReMi.Common.Constants.ProductRequests;
using ReMi.Common.Utils;
using ReMi.Common.Utils.Repository;
using ReMi.DataAccess.Exceptions;
using ReMi.DataEntities.ProductRequests;
using ProductRequestRegistration = ReMi.BusinessEntities.ProductRequests.ProductRequestRegistration;
using ProductRequestRegistrationTask = ReMi.BusinessEntities.ProductRequests.ProductRequestRegistrationTask;
namespace ReMi.DataAccess.BusinessEntityGateways.ProductRequests
{
public class ProductRequestRegistrationGateway : BaseGateway, IProductRequestRegistrationGateway
{
public IRepository<DataEntities.ProductRequests.ProductRequestRegistration> ProductRequestRegistrationRepository { get; set; }
public IRepository<DataEntities.ProductRequests.ProductRequestRegistrationTask> ProductRequestRegistrationTaskRepository { get; set; }
public IRepository<ProductRequestType> ProductRequestTypeRepository { get; set; }
public IRepository<DataEntities.Auth.Account> AccountRepository { get; set; }
public IMappingEngine MappingEngine { get; set; }
private Guid _productRequestTypeId = Guid.Empty;
private IEnumerable<ProductRequestTask> _tasksByType;
public ProductRequestRegistration GetRegistration(Guid externalId)
{
var existingRegistration = ProductRequestRegistrationRepository.GetSatisfiedBy(o => o.ExternalId == externalId);
if (existingRegistration == null)
throw new EntityNotFoundException(typeof(DataEntities.ProductRequests.ProductRequestRegistration), externalId);
return MappingEngine.Map
<DataEntities.ProductRequests.ProductRequestRegistration, ProductRequestRegistration>(existingRegistration);
}
public IEnumerable<ProductRequestRegistration> GetRegistrations()
{
var items =
ProductRequestRegistrationRepository.GetAllSatisfiedBy(x => !(x.Deleted.HasValue && x.Deleted.Value));
return
MappingEngine
.Map
<IEnumerable<DataEntities.ProductRequests.ProductRequestRegistration>,
IEnumerable<ProductRequestRegistration>>(items);
}
public void CreateProductRequestRegistration(ProductRequestRegistration registration)
{
var existingRegistration = ProductRequestRegistrationRepository.GetSatisfiedBy(o => o.ExternalId == registration.ExternalId);
if (existingRegistration != null)
throw new EntityAlreadyExistsException(typeof(DataEntities.ProductRequests.ProductRequestRegistration), registration.ExternalId);
var existingRequestType =
ProductRequestTypeRepository.GetSatisfiedBy(o => o.ExternalId == registration.ProductRequestTypeId);
if (existingRequestType == null)
throw new EntityNotFoundException(typeof(ProductRequestType), registration.ProductRequestTypeId);
var createdByAccount =
AccountRepository.GetSatisfiedBy(o => o.ExternalId == registration.CreatedByAccountId);
if (createdByAccount == null)
throw new AccountNotFoundException(registration.CreatedByAccountId);
var newEntity =
MappingEngine.Map<ProductRequestRegistration, DataEntities.ProductRequests.ProductRequestRegistration>(
registration);
newEntity.ProductRequestTypeId = existingRequestType.ProductRequestTypeId;
newEntity.CreatedOn = SystemTime.Now;
newEntity.CreatedByAccountId = createdByAccount.AccountId;
ProductRequestRegistrationRepository.Insert(newEntity);
UpdateRegistrationTasks(registration, newEntity.ProductRequestRegistrationId, createdByAccount);
}
public void UpdateProductRequestRegistration(ProductRequestRegistration registration)
{
var existingRegistration = ProductRequestRegistrationRepository.GetSatisfiedBy(o => o.ExternalId == registration.ExternalId);
if (existingRegistration == null)
throw new EntityNotFoundException(typeof(DataEntities.ProductRequests.ProductRequestRegistration), registration.ExternalId);
var existingRequestType =
ProductRequestTypeRepository.GetSatisfiedBy(o => o.ExternalId == registration.ProductRequestTypeId);
if (existingRequestType == null)
throw new EntityNotFoundException(typeof(ProductRequestType), registration.ProductRequestTypeId);
var createdByAccount =
AccountRepository.GetSatisfiedBy(o => o.ExternalId == registration.CreatedByAccountId);
if (createdByAccount == null)
throw new AccountNotFoundException(registration.CreatedByAccountId);
if (!string.Equals(existingRegistration.Description, registration.Description, StringComparison.CurrentCulture))
{
existingRegistration.Description = registration.Description;
ProductRequestRegistrationRepository.Update(existingRegistration);
}
UpdateRegistrationTasks(registration, existingRegistration.ProductRequestRegistrationId, createdByAccount);
}
public void DeleteProductRequestRegistration(Guid productRequestRegistrationId, RemovingReason removingReason, string comment)
{
var existingRegistration = ProductRequestRegistrationRepository.GetSatisfiedBy(o => o.ExternalId == productRequestRegistrationId);
if (existingRegistration == null)
throw new EntityNotFoundException(typeof(DataEntities.ProductRequests.ProductRequestRegistration), productRequestRegistrationId);
existingRegistration.RemovingReason = new ProductRequestRegistrationRemovingReason
{
ProductRequestRegistrationId = existingRegistration.ProductRequestRegistrationId,
RemovingReason = removingReason,
Comment = comment
};
existingRegistration.Deleted = true;
ProductRequestRegistrationRepository.Update(existingRegistration);
}
private void UpdateRegistrationTasks(ProductRequestRegistration registration, int parentRegistrationId, DataEntities.Auth.Account currentDataAccount)
{
var existingTasks =
ProductRequestRegistrationTaskRepository
.GetAllSatisfiedBy(o => o.ProductRequestRegistration.ExternalId == registration.ExternalId)
.ToList();
if (registration.Tasks != null)
foreach (var task in registration.Tasks)
{
var existingTask =
existingTasks.FirstOrDefault(o => o.ProductRequestTask.ExternalId == task.ProductRequestTaskId);
if (existingTask != null)
{
UpdateExistingTask(existingTask, task, currentDataAccount);
}
else
{
CreateNewTask(registration, parentRegistrationId, task, currentDataAccount);
}
}
}
private void UpdateExistingTask(DataEntities.ProductRequests.ProductRequestRegistrationTask existingTask, ProductRequestRegistrationTask task, DataEntities.Auth.Account dataAccount)
{
SetTaskData(existingTask, task, dataAccount.AccountId);
ProductRequestRegistrationTaskRepository.Update(existingTask);
}
private void CreateNewTask(ProductRequestRegistration registration, int registrationId, ProductRequestRegistrationTask task, DataEntities.Auth.Account dataAccount)
{
var taskForType = GetTasksByType(registration.ProductRequestTypeId).FirstOrDefault(o => o.ExternalId == task.ProductRequestTaskId);
if (taskForType == null)
throw new EntityNotFoundException(typeof(ProductRequestRegistrationTask), task.ProductRequestTaskId);
var newEntity =
new DataEntities.ProductRequests.ProductRequestRegistrationTask
{
ProductRequestTaskId = taskForType.ProductRequestTaskId,
ProductRequestRegistrationId = registrationId,
};
SetTaskData(newEntity, task, dataAccount.AccountId);
ProductRequestRegistrationTaskRepository.Insert(newEntity);
}
private void SetTaskData(DataEntities.ProductRequests.ProductRequestRegistrationTask dataTask, ProductRequestRegistrationTask businessTask, int accountId)
{
if ((dataTask.ProductRequestRegistrationTaskId == 0 &&
(businessTask.IsCompleted || !string.IsNullOrWhiteSpace(businessTask.Comment))
)
||
(dataTask.ProductRequestRegistrationTaskId > 0 &&
(businessTask.IsCompleted != dataTask.IsCompleted || !string.Equals(businessTask.Comment, dataTask.Comment, StringComparison.CurrentCulture))
))
{
dataTask.LastChangedByAccountId = accountId;
dataTask.LastChangedOn = SystemTime.Now;
dataTask.IsCompleted = businessTask.IsCompleted;
dataTask.Comment = businessTask.Comment;
}
}
private IEnumerable<ProductRequestTask> GetTasksByType(Guid productRequestTypeId)
{
if (_tasksByType == null || _productRequestTypeId != productRequestTypeId)
{
_productRequestTypeId = productRequestTypeId;
_tasksByType = ProductRequestTypeRepository.GetAllSatisfiedBy(o => o.ExternalId == productRequestTypeId)
.SelectMany(o => o.RequestGroups)
.SelectMany(o => o.RequestTasks)
.ToList();
}
return _tasksByType;
}
public override void OnDisposing()
{
ProductRequestRegistrationRepository.Dispose();
ProductRequestTypeRepository.Dispose();
ProductRequestRegistrationTaskRepository.Dispose();
AccountRepository.Dispose();
MappingEngine.Dispose();
base.OnDisposing();
}
}
}
| |
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace ToolGood.Algorithm.LitJson
{
enum JsonToken
{
None,
ObjectStart,
PropertyName,
ObjectEnd,
ArrayStart,
ArrayEnd,
Double,
String,
Boolean,
Null
}
class JsonReader
{
#region Fields
private static readonly 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 readonly Lexer lexer;
private bool parser_in_string;
private bool parser_return;
private bool read_started;
private object token_value;
private JsonToken token;
#endregion
#region Public Properties
public JsonToken Token { get { return token; } }
public object Value { get { return token_value; } }
#endregion
#region Constructors
static JsonReader()
{
parse_table = PopulateParseTable();
}
public JsonReader(string json_text)
{
var reader = new StringReader(json_text);
parser_in_string = false;
parser_return = false;
read_started = false;
automaton_stack = new Stack<int>();
automaton_stack.Push((int)ParserToken.End);
automaton_stack.Push((int)ParserToken.Text);
lexer = new Lexer(reader);
end_of_input = false;
end_of_json = false;
}
#endregion
#region Static Methods
private static IDictionary<int, IDictionary<int, int[]>> PopulateParseTable()
{
// See section A.2. of the manual for details
IDictionary<int, IDictionary<int, int[]>> parse_table = new Dictionary<int, IDictionary<int, int[]>>();
TableAddRow(parse_table, ParserToken.Array);
TableAddCol(parse_table, ParserToken.Array, '[', '[', (int)ParserToken.ArrayPrime);
TableAddRow(parse_table, ParserToken.ArrayPrime);
TableAddCol(parse_table, ParserToken.ArrayPrime, '"', (int)ParserToken.Value, (int)ParserToken.ValueRest, ']');
TableAddCol(parse_table, ParserToken.ArrayPrime, '[', (int)ParserToken.Value, (int)ParserToken.ValueRest, ']');
TableAddCol(parse_table, ParserToken.ArrayPrime, ']', ']');
TableAddCol(parse_table, ParserToken.ArrayPrime, '{', (int)ParserToken.Value, (int)ParserToken.ValueRest, ']');
TableAddCol(parse_table, ParserToken.ArrayPrime, (int)ParserToken.Number, (int)ParserToken.Value, (int)ParserToken.ValueRest, ']');
TableAddCol(parse_table, ParserToken.ArrayPrime, (int)ParserToken.True, (int)ParserToken.Value, (int)ParserToken.ValueRest, ']');
TableAddCol(parse_table, ParserToken.ArrayPrime, (int)ParserToken.False, (int)ParserToken.Value, (int)ParserToken.ValueRest, ']');
TableAddCol(parse_table, ParserToken.ArrayPrime, (int)ParserToken.Null, (int)ParserToken.Value, (int)ParserToken.ValueRest, ']');
TableAddRow(parse_table, ParserToken.Object);
TableAddCol(parse_table, ParserToken.Object, '{', '{', (int)ParserToken.ObjectPrime);
TableAddRow(parse_table, ParserToken.ObjectPrime);
TableAddCol(parse_table, ParserToken.ObjectPrime, '"', (int)ParserToken.Pair, (int)ParserToken.PairRest, '}');
TableAddCol(parse_table, ParserToken.ObjectPrime, '}', '}');
TableAddRow(parse_table, ParserToken.Pair);
TableAddCol(parse_table, ParserToken.Pair, '"', (int)ParserToken.String, ':', (int)ParserToken.Value);
TableAddRow(parse_table, ParserToken.PairRest);
TableAddCol(parse_table, ParserToken.PairRest, ',', ',', (int)ParserToken.Pair, (int)ParserToken.PairRest);
TableAddCol(parse_table, ParserToken.PairRest, '}', (int)ParserToken.Epsilon);
TableAddRow(parse_table, ParserToken.String);
TableAddCol(parse_table, ParserToken.String, '"', '"', (int)ParserToken.CharSeq, '"');
TableAddRow(parse_table, ParserToken.Text);
TableAddCol(parse_table, ParserToken.Text, '[', (int)ParserToken.Array);
TableAddCol(parse_table, ParserToken.Text, '{', (int)ParserToken.Object);
TableAddRow(parse_table, ParserToken.Value);
TableAddCol(parse_table, ParserToken.Value, '"', (int)ParserToken.String);
TableAddCol(parse_table, ParserToken.Value, '[', (int)ParserToken.Array);
TableAddCol(parse_table, ParserToken.Value, '{', (int)ParserToken.Object);
TableAddCol(parse_table, ParserToken.Value, (int)ParserToken.Number, (int)ParserToken.Number);
TableAddCol(parse_table, ParserToken.Value, (int)ParserToken.True, (int)ParserToken.True);
TableAddCol(parse_table, ParserToken.Value, (int)ParserToken.False, (int)ParserToken.False);
TableAddCol(parse_table, ParserToken.Value, (int)ParserToken.Null, (int)ParserToken.Null);
TableAddRow(parse_table, ParserToken.ValueRest);
TableAddCol(parse_table, ParserToken.ValueRest, ',', ',', (int)ParserToken.Value, (int)ParserToken.ValueRest);
TableAddCol(parse_table, ParserToken.ValueRest, ']', (int)ParserToken.Epsilon);
return parse_table;
}
private static void TableAddCol(IDictionary<int, IDictionary<int, int[]>> parse_table, ParserToken row, int col, params int[] symbols)
{
parse_table[(int)row].Add(col, symbols);
}
private static void TableAddRow(IDictionary<int, IDictionary<int, int[]>> parse_table, ParserToken rule)
{
parse_table.Add((int)rule, new Dictionary<int, int[]>());
}
#endregion
#region Private Methods
private void ProcessNumber(string number)
{
if (number.IndexOf('.') != -1 || number.IndexOf('e') != -1 || number.IndexOf('E') != -1) {
if (double.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out double n_double)) {
token_value = n_double;
return;
}
}
if (int.TryParse(number, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n_int32)) {
token_value = (double)n_int32;
return;
}
if (long.TryParse(number, NumberStyles.Integer, CultureInfo.InvariantCulture, out long n_int64)) {
token_value = (double)n_int64;
return;
}
if (ulong.TryParse(number, NumberStyles.Integer, CultureInfo.InvariantCulture, out ulong n_uint64)) {
token_value = (double)n_uint64;
return;
}
// Shouldn't happen, but just in case, return something
token_value = 0;
}
private void ProcessSymbol()
{
if (current_symbol == '[') {
token = JsonToken.ArrayStart;
parser_return = true;
} else if (current_symbol == ']') {
token = JsonToken.ArrayEnd;
parser_return = true;
} else if (current_symbol == '{') {
token = JsonToken.ObjectStart;
parser_return = true;
} else if (current_symbol == '}') {
token = JsonToken.ObjectEnd;
parser_return = true;
} else if (current_symbol == '"') {
if (parser_in_string) {
parser_in_string = false;
parser_return = true;
} else {
if (token == JsonToken.None) token = JsonToken.String;
parser_in_string = true;
}
} else if (current_symbol == (int)ParserToken.CharSeq) {
token_value = lexer.StringValue;
} else if (current_symbol == (int)ParserToken.False) {
token = JsonToken.Boolean;
token_value = false;
parser_return = true;
} else if (current_symbol == (int)ParserToken.Null) {
token = JsonToken.Null;
parser_return = true;
} else if (current_symbol == (int)ParserToken.Number) {
ProcessNumber(lexer.StringValue);
token = JsonToken.Double;
//if (double.TryParse(lexer.StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out double n_double))
//{
// token_value = n_double;
//}
//else
//{
// token_value = 0;
//}
parser_return = true;
} else if (current_symbol == (int)ParserToken.Pair) {
token = JsonToken.PropertyName;
} else if (current_symbol == (int)ParserToken.True) {
token = JsonToken.Boolean;
token_value = true;
parser_return = true;
}
}
private bool ReadToken()
{
if (end_of_input) return false;
lexer.NextToken();
if (lexer.EndOfInput) {
Close();
return false;
}
current_input = lexer.Token;
return true;
}
#endregion
public void Close()
{
if (end_of_input)
return;
end_of_input = true;
end_of_json = true;
}
public bool Read()
{
if (end_of_input)
return false;
if (end_of_json) {
end_of_json = false;
automaton_stack.Clear();
automaton_stack.Push((int)ParserToken.End);
automaton_stack.Push((int)ParserToken.Text);
}
parser_in_string = false;
parser_return = false;
token = JsonToken.None;
token_value = null;
if (!read_started) {
read_started = true;
if (!ReadToken())
return false;
}
int[] entry_symbols;
while (true) {
if (parser_return) {
if (automaton_stack.Peek() == (int)ParserToken.End) end_of_json = true;
return true;
}
current_symbol = automaton_stack.Pop();
ProcessSymbol();
if (current_symbol == current_input) {
if (!ReadToken()) {
if (automaton_stack.Peek() != (int)ParserToken.End) throw new JsonException("Input doesn't evaluate to proper JSON text");
if (parser_return) return true;
return false;
}
continue;
}
try {
entry_symbols = parse_table[current_symbol][current_input];
} catch (KeyNotFoundException e) {
throw new JsonException((ParserToken)current_input, e);
}
if (entry_symbols[0] == (int)ParserToken.Epsilon) continue;
for (int i = entry_symbols.Length - 1; i >= 0; i--)
automaton_stack.Push(entry_symbols[i]);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Rynchodon.Autopilot.Data;
using Sandbox.Game.Entities;
using Sandbox.ModAPI;
using VRageMath;
namespace Rynchodon.Autopilot.Movement
{
/// <summary>
/// Performs the movement calculations and the movements.
/// </summary>
public class Mover
{
#region S.E. Constants
private const float pixelsForMaxRotation = 20;
private const float RollControlMultiplier = 0.2f;
#endregion
/// <summary>Controlling block for the grid.</summary>
public readonly ShipControllerBlock Block;
private readonly Logger myLogger;
private readonly AllNavigationSettings NavSet;
private IMyCubeGrid myGrid;
private ThrustProfiler myThrust;
private GyroProfiler myGyro;
private Vector3 moveForceRatio = Vector3.Zero;
private Vector3 value_rotateForceRatio = Vector3.Zero;
private Vector3 rotateForceRatio = Vector3.Zero;
private ulong updated_prevAngleVel = 0;
private Vector3 prevAngleVel = Vector3.Zero;
private Vector3 prevAngleDisp = Vector3.Zero;
private bool m_stopped;
public Pathfinder.Pathfinder myPathfinder { get; private set; }
/// <summary>
/// Creates a Mover for a given ShipControllerBlock and AllNavigationSettings
/// </summary>
/// <param name="block">Controlling block for the grid</param>
/// <param name="NavSet">Navigation settings to use.</param>
public Mover(ShipControllerBlock block, AllNavigationSettings NavSet)
{
this.myLogger = new Logger("Mover", block.Controller);
//this.myLogger.MinimumLevel = Logger.severity.DEBUG;
this.Block = block;
this.NavSet = NavSet;
}
/// <summary>
/// Sets moveForceRatio to zero, optionally enables damping.
/// </summary>
public void StopMove(bool enableDampeners = true)
{
moveForceRatio = Vector3.Zero;
Block.SetDamping(enableDampeners);
}
/// <summary>
/// Sets rotateForceRatio to zero.
/// </summary>
public void StopRotate()
{
rotateForceRatio = Vector3.Zero;
}
public void MoveAndRotateStop()
{
if (m_stopped)
return;
moveForceRatio = Vector3.Zero;
rotateForceRatio = Vector3.Zero;
Block.SetDamping(true);
MyAPIGateway.Utilities.TryInvokeOnGameThread(() => Block.Controller.MoveAndRotateStopped());
m_stopped = true;
}
public bool CanMoveForward(PseudoBlock block)
{
CheckGrid();
return myThrust.CanMoveAnyDirection();
}
/// <summary>
/// Calculates the force necessary to move the grid.
/// </summary>
/// <param name="block">To get world position from.</param>
/// <param name="destPoint">The world position of the destination</param>
/// <param name="destVelocity">The speed of the destination</param>
/// <param name="landing">Puts an emphasis on not overshooting the target.</param>
public void CalcMove(PseudoBlock block, Vector3 destPoint, Vector3 destVelocity, bool landing = false)
{
CheckGrid();
// using world vectors
if (NavSet.Settings_Current.CollisionAvoidance)
{
myPathfinder.TestPath(destPoint, landing);
if (!myPathfinder.CanMove)
{
myLogger.debugLog("Pathfinder not allowing movement", "CalcMove()");
return;
}
}
myThrust.UpdateGravity();
Vector3 destDisp = destPoint - block.WorldPosition;
Vector3 velocity = Block.CubeGrid.Physics.LinearVelocity;
// switch to using local vectors
Matrix positionToLocal = Block.CubeBlock.WorldMatrixNormalizedInv;
Matrix directionToLocal = positionToLocal.GetOrientation();
destDisp = Vector3.Transform(destDisp, directionToLocal);
destVelocity = Vector3.Transform(destVelocity, directionToLocal);
velocity = Vector3.Transform(velocity, directionToLocal);
float distance = destDisp.Length();
NavSet.Settings_Task_NavWay.Distance = distance;
Vector3 targetVelocity = MaximumVelocity(destDisp) * 0.5f;
// project targetVelocity onto destination direction (take shortest path)
Vector3 destDir = destDisp / distance;
targetVelocity = Vector3.Dot(targetVelocity, destDir) * destDir;
// apply relative speed limit
float relSpeedLimit = NavSet.Settings_Current.SpeedMaxRelative;
if (landing)
{
float landingSpeed = distance * 0.5f;
if (relSpeedLimit > landingSpeed)
relSpeedLimit = landingSpeed;
}
if (relSpeedLimit < float.MaxValue)
{
float tarSpeedSq_1 = targetVelocity.LengthSquared();
if (tarSpeedSq_1 > relSpeedLimit * relSpeedLimit)
{
targetVelocity *= relSpeedLimit / (float)Math.Sqrt(tarSpeedSq_1);
myLogger.debugLog("imposing relative speed limit: " + relSpeedLimit + ", targetVelocity: " + targetVelocity, "CalcMove()");
}
}
targetVelocity += destVelocity;
// apply speed limit
float tarSpeedSq = targetVelocity.LengthSquared();
float speedRequest = NavSet.Settings_Current.SpeedTarget;
if (tarSpeedSq > speedRequest * speedRequest)
targetVelocity *= speedRequest / (float)Math.Sqrt(tarSpeedSq);
Vector3 accel = targetVelocity - velocity;
moveForceRatio = ToForceRatio(accel);
// dampeners
bool enableDampeners = false;
for (int i = 0; i < 3; i++)
{
// if target velocity is close to 0, use dampeners
float targetDim = targetVelocity.GetDim(i);
if (targetDim < 0.1f && targetDim > -0.1f)
{
//myLogger.debugLog("close to 0, i: " + i + ", targetDim: " + targetDim, "CalcMove()");
moveForceRatio.SetDim(i, 0);
enableDampeners = true;
continue;
}
// if there is not enough force available for braking, use dampeners
float forceRatio = moveForceRatio.GetDim(i);
if (forceRatio < 1f && forceRatio > -1f)
continue;
float velDim = velocity.GetDim(i);
if (velDim < 1f && velDim > -1f)
continue;
if (Math.Sign(forceRatio) * Math.Sign(velDim) < 0)
{
myLogger.debugLog("damping, i: " + i + ", force ratio: " + forceRatio + ", velocity: " + velDim + ", sign of forceRatio: " + Math.Sign(forceRatio) + ", sign of velocity: " + Math.Sign(velDim), "CalcMove()");
moveForceRatio.SetDim(i, 0);
enableDampeners = true;
}
else
myLogger.debugLog("not damping, i: " + i + ", force ratio: " + forceRatio + ", velocity: " + velDim + ", sign of forceRatio: " + Math.Sign(forceRatio) + ", sign of velocity: " + Math.Sign(velDim), "CalcMove()");
}
//if (enableDampeners)
// Logger.debugNotify("Damping", 16);
Block.SetDamping(enableDampeners);
myLogger.debugLog("destDisp: " + destDisp
+ ", destDir: " + destDir
+ ", destVelocity: " + destVelocity
//+ ", relaVelocity: " + relaVelocity
+ ", targetVelocity: " + targetVelocity
//+ ", diffVel: " + diffVel
+ ", accel: " + accel
+ ", moveForceRatio: " + moveForceRatio, "CalcMove()");
}
/// <summary>
/// Calculates the maximum velocity that will allow the grid to stop at the destination.
/// </summary>
/// <param name="localDisp">The displacement to the destination.</param>
/// <returns>The maximum velocity that will allow the grid to stop at the destination.</returns>
private Vector3 MaximumVelocity(Vector3 localDisp)
{
Vector3 result = Vector3.Zero;
if (localDisp.X > 0)
result.X = MaximumSpeed(localDisp.X, Base6Directions.Direction.Right);
else if (localDisp.X < 0)
result.X = -MaximumSpeed(-localDisp.X, Base6Directions.Direction.Left);
if (localDisp.Y > 0)
result.Y = MaximumSpeed(localDisp.Y, Base6Directions.Direction.Up);
else if (localDisp.Y < 0)
result.Y = -MaximumSpeed(-localDisp.Y, Base6Directions.Direction.Down);
if (localDisp.Z > 0)
result.Z = MaximumSpeed(localDisp.Z, Base6Directions.Direction.Backward);
else if (localDisp.Z < 0)
result.Z = -MaximumSpeed(-localDisp.Z, Base6Directions.Direction.Forward);
myLogger.debugLog("local: " + localDisp + ", result: " + result, "MaximumVelocity()");
return result;
}
/// <summary>
/// Calculates the maximum speed that will allow the grid to stop at the destination.
/// </summary>
/// <param name="dist">The distance to the destination</param>
/// <param name="direct">The directional thrusters to use</param>
/// <returns>The maximum speed that will allow the grid to stop at the destination.</returns>
private float MaximumSpeed(float dist, Base6Directions.Direction direct)
{
// Mover will attempt to stop with normal thrust
float accel = -myThrust.GetForceInDirection(Base6Directions.GetFlippedDirection(direct)) / Block.Physics.Mass;
myLogger.debugLog("dist: " + dist + ", accel: " + accel + ", max speed: " + PrettySI.makePretty(Math.Sqrt(-2 * accel * dist)) + "m/s" + ", cap: " + dist * 0.5f + " m/s", "MaximumSpeed()");
return Math.Min((float)Math.Sqrt(-2 * accel * dist), dist * 0.5f); // capped for the sake of autopilot's reaction time
}
/// <summary>
/// Calculate the force ratio from acceleration.
/// </summary>
/// <param name="localAccel">Acceleration</param>
/// <returns>Force ratio</returns>
private Vector3 ToForceRatio(Vector3 localAccel)
{
Vector3 result = Vector3.Zero;
if (localAccel.X > 0)
result.X = localAccel.X * Block.Physics.Mass / myThrust.GetForceInDirection(Base6Directions.Direction.Right);
else if (localAccel.X < 0)
result.X = localAccel.X * Block.Physics.Mass / myThrust.GetForceInDirection(Base6Directions.Direction.Left);
if (localAccel.Y > 0)
result.Y = localAccel.Y * Block.Physics.Mass / myThrust.GetForceInDirection(Base6Directions.Direction.Up);
else if (localAccel.Y < 0)
result.Y = localAccel.Y * Block.Physics.Mass / myThrust.GetForceInDirection(Base6Directions.Direction.Down);
if (localAccel.Z > 0)
result.Z = localAccel.Z * Block.Physics.Mass / myThrust.GetForceInDirection(Base6Directions.Direction.Backward);
else if (localAccel.Z < 0)
result.Z = localAccel.Z * Block.Physics.Mass / myThrust.GetForceInDirection(Base6Directions.Direction.Forward);
myLogger.debugLog("local: " + localAccel + ", result: " + result + ", after gravity: " + (result + myThrust.m_gravityReactRatio), "ToForceRatio()");
result += myThrust.m_gravityReactRatio;
return result;
}
/// <summary>
/// Match orientation with the target block.
/// </summary>
/// <param name="block">The navigation block</param>
/// <param name="destBlock">The destination block</param>
/// <param name="forward">The direction of destBlock that will be matched to navigation block's forward</param>
/// <param name="upward">The direction of destBlock that will be matched to navigation block's upward</param>
/// <returns>True iff localMatrix is facing the same direction as destBlock's forward</returns>
public void CalcRotate(PseudoBlock block, IMyCubeBlock destBlock, Base6Directions.Direction? forward, Base6Directions.Direction? upward)
{
if (forward == null)
forward = Base6Directions.Direction.Forward;
//if (upward == null)
// upward = Base6Directions.Direction.Up;
//myLogger.debugLog(forward.Value == upward.Value || forward.Value == Base6Directions.GetFlippedDirection(upward.Value),
// "Invalid orienation: " + forward + ", " + upward, "CalcRotate()", Logger.severity.FATAL);
RelativeDirection3F faceForward = RelativeDirection3F.FromWorld(block.Grid, destBlock.WorldMatrix.GetDirectionVector(forward.Value));
RelativeDirection3F faceUpward = upward.HasValue ? RelativeDirection3F.FromWorld(block.Grid, destBlock.WorldMatrix.GetDirectionVector(upward.Value)) : null;
CalcRotate(block, faceForward, faceUpward);
}
/// <summary>
/// Calculates the force necessary to rotate the grid.
/// </summary>
/// <param name="Direction">The direction to face the localMatrix in.</param>
/// <param name="block"></param>
/// <returns>True iff localMatrix is facing Direction</returns>
public void CalcRotate(PseudoBlock block, RelativeDirection3F Direction, RelativeDirection3F UpDirect = null)
{
Vector3 angleVelocity;
CalcRotate(block.LocalMatrix, Direction, UpDirect, out angleVelocity);
updated_prevAngleVel = Globals.UpdateCount;
prevAngleVel = angleVelocity;
//myLogger.debugLog("displacement.LengthSquared(): " + displacement.LengthSquared(), "CalcRotate()");
//return displacement.LengthSquared() < 0.01f;
//if (NavSet.Settings_Current.CollisionAvoidance)
// myPathfinder.TestRotate(displacement);
}
/// <summary>
/// Calculates the force necessary to rotate the grid.
/// </summary>
/// <param name="localMatrix">The matrix to rotate to face the direction, use a block's local matrix or result of GetMatrix()</param>
/// <param name="Direction">The direction to face the localMatrix in.</param>
/// <param name="angularVelocity">The local angular velocity of the controlling block.</param>
private void CalcRotate(Matrix localMatrix, RelativeDirection3F Direction, RelativeDirection3F UpDirect, out Vector3 angularVelocity)
{
CheckGrid();
myLogger.debugLog(Direction == null, "Direction == null", "CalcRotate()", Logger.severity.ERROR);
angularVelocity = -Vector3.Transform(Block.Physics.AngularVelocity, Block.CubeBlock.WorldMatrixNormalizedInv.GetOrientation());
//myLogger.debugLog("angular: " + angularVelocity, "CalcRotate()");
float gyroForce = myGyro.TotalGyroForce();
const ulong MaxUpdateFrequency = ShipController_Autopilot.UpdateFrequency * 2u;
if (rotateForceRatio != Vector3.Zero)
{
ulong timeSinceLast = Globals.UpdateCount - updated_prevAngleVel;
if (timeSinceLast <= MaxUpdateFrequency)
{
Vector3 ratio = (angularVelocity - prevAngleVel) / (rotateForceRatio * gyroForce * (float)timeSinceLast);
//myLogger.debugLog("rotateForceRatio: " + rotateForceRatio + ", ratio: " + ratio + ", accel: " + (angularVelocity - prevAngleVel) + ", torque: " + (rotateForceRatio * gyroForce), "CalcRotate()");
myGyro.Update_torqueAccelRatio(rotateForceRatio, ratio);
}
else
myLogger.debugLog("prevAngleVel is old: " + (Globals.UpdateCount - updated_prevAngleVel), "CalcRotate()", Logger.severity.DEBUG);
}
localMatrix.M41 = 0; localMatrix.M42 = 0; localMatrix.M43 = 0; localMatrix.M44 = 1;
Matrix inverted; Matrix.Invert(ref localMatrix, out inverted);
localMatrix = localMatrix.GetOrientation();
inverted = inverted.GetOrientation();
//myLogger.debugLog("local matrix: right: " + localMatrix.Right + ", up: " + localMatrix.Up + ", back: " + localMatrix.Backward + ", trans: " + localMatrix.Translation, "CalcRotate()");
//myLogger.debugLog("inverted matrix: right: " + inverted.Right + ", up: " + inverted.Up + ", back: " + inverted.Backward + ", trans: " + inverted.Translation, "CalcRotate()");
//myLogger.debugLog("local matrix: " + localMatrix, "CalcRotate()");
//myLogger.debugLog("inverted matrix: " + inverted, "CalcRotate()");
Vector3 localDirect = Direction.ToLocal();
Vector3 rotBlockDirect; Vector3.Transform(ref localDirect, ref inverted, out rotBlockDirect);
rotBlockDirect.Normalize();
float azimuth, elevation; Vector3.GetAzimuthAndElevation(rotBlockDirect, out azimuth, out elevation);
Vector3 rotaRight = localMatrix.Right;
Vector3 rotaUp = localMatrix.Up;
Vector3 NFR_right = Base6Directions.GetVector(Block.CubeBlock.LocalMatrix.GetClosestDirection(ref rotaRight));
Vector3 NFR_up = Base6Directions.GetVector(Block.CubeBlock.LocalMatrix.GetClosestDirection(ref rotaUp));
Vector3 displacement = -elevation * NFR_right - azimuth * NFR_up;
if (UpDirect != null)
{
Vector3 upLocal = UpDirect.ToLocal();
Vector3 upRotBlock; Vector3.Transform(ref upLocal, ref inverted, out upRotBlock);
float roll; Vector3.Dot(ref upRotBlock, ref Vector3.Right, out roll);
Vector3 rotaBackward = localMatrix.Backward;
Vector3 NFR_backward = Base6Directions.GetVector(Block.CubeBlock.LocalMatrix.GetClosestDirection(ref rotaBackward));
myLogger.debugLog("roll: " + roll + ", displacement: " + displacement + ", NFR_backward: " + NFR_backward + ", change: " + (-roll * NFR_backward), "CalcRotate()");
displacement += roll * NFR_backward;
}
NavSet.Settings_Task_NavWay.DistanceAngle = displacement.Length();
if (NavSet.Settings_Current.CollisionAvoidance)
{
myPathfinder.TestRotate(displacement);
if (!myPathfinder.CanRotate)
{
Logger.debugNotify("Cannot Rotate", 50);
myLogger.debugLog("Pathfinder not allowing rotation", "CalcRotate()");
return;
}
}
//myLogger.debugLog("localDirect: " + localDirect + ", rotBlockDirect: " + rotBlockDirect + ", elevation: " + elevation + ", NFR_right: " + NFR_right + ", azimuth: " + azimuth + ", NFR_up: " + NFR_up + ", disp: " + displacement, "CalcRotate()");
if (myGyro.torqueAccelRatio == 0)
{
// do a test
myLogger.debugLog("torqueAccelRatio == 0", "CalcRotate()");
rotateForceRatio = new Vector3(0, 1f, 0);
return;
}
Vector3 targetVelocity = MaxAngleVelocity(displacement);
// Adjust for moving target by measuring changes in displacement. Part of the change in displacement is attributable to ship rotation.
const float dispToVel = (float)Globals.UpdatesPerSecond / (float)ShipController_Autopilot.UpdateFrequency;
Vector3 addVelocity = angularVelocity - (prevAngleDisp - displacement) * dispToVel;
if (addVelocity.LengthSquared() < 0.01f)
{
myLogger.debugLog("Adjust for moving, adding to target velocity: " + addVelocity, "CalcRotate()");
targetVelocity += addVelocity;
}
else
myLogger.debugLog("Not adjusting for moving, assuming target changed: " + addVelocity, "CalcRotate()");
prevAngleDisp = displacement;
Vector3 diffVel = targetVelocity - angularVelocity;
rotateForceRatio = diffVel / (myGyro.torqueAccelRatio * gyroForce);
myLogger.debugLog("targetVelocity: " + targetVelocity + ", angularVelocity: " + angularVelocity + ", diffVel: " + diffVel, "CalcRotate()");
//myLogger.debugLog("diffVel: " + diffVel + ", torque: " + (myGyro.torqueAccelRatio * gyroForce) + ", rotateForceRatio: " + rotateForceRatio, "CalcRotate()");
// dampeners
for (int i = 0; i < 3; i++)
{
// if targetVelocity is close to 0, use dampeners
float target = targetVelocity.GetDim(i);
if (target > -0.01f && target < 0.01f)
{
myLogger.debugLog("target near 0 for " + i + ", " + target, "CalcRotate()");
rotateForceRatio.SetDim(i, 0f);
continue;
}
float velDim = angularVelocity.GetDim(i);
if (velDim < 0.01f && velDim > -0.01f)
continue;
// where rotateForceRatio opposes angularVelocity, use dampeners
float dim = rotateForceRatio.GetDim(i);
if (Math.Sign(dim) * Math.Sign(angularVelocity.GetDim(i)) < 0)
//{
// myLogger.debugLog("force ratio(" + dim + ") opposes velocity(" + angularVelocity.GetDim(i) + "), index: " + i + ", " + Math.Sign(dim) + ", " + Math.Sign(angularVelocity.GetDim(i)), "CalcRotate()");
rotateForceRatio.SetDim(i, 0f);
//}
//else
// myLogger.debugLog("force ratio is aligned with velocity: " + i + ", " + Math.Sign(dim) + ", " + Math.Sign(angularVelocity.GetDim(i)), "CalcRotate()");
}
}
/// <summary>
/// Calulates the maximum angular velocity to stop at the destination.
/// </summary>
/// <param name="disp">Displacement to the destination.</param>
/// <returns>The maximum angular velocity to stop at the destination.</returns>
private Vector3 MaxAngleVelocity(Vector3 disp)
{
Vector3 result = Vector3.Zero;
// S.E. provides damping for angular motion, we will ignore this
float accel = -myGyro.torqueAccelRatio * myGyro.TotalGyroForce();
//myLogger.debugLog("torqueAccelRatio: " + myGyro.torqueAccelRatio + ", TotalGyroForce: " + myGyro.TotalGyroForce() + ", accel: " + accel, "MaxAngleVelocity()");
//myLogger.debugLog("speed cap: " + speedCap, "MaxAngleVelocity()");
for (int i = 0; i < 3; i++)
{
float dim = disp.GetDim(i);
if (dim > 0)
//result.SetDim(i, Math.Min(MaxAngleSpeed(accel, dim), speedCap));
result.SetDim(i, MaxAngleSpeed(accel, dim));
else if (dim < 0)
//result.SetDim(i, -Math.Min(MaxAngleSpeed(accel, -dim), speedCap));
result.SetDim(i, -MaxAngleSpeed(accel, -dim));
}
return result;
}
/// <summary>
/// Calculates the maximum angular speed to stop at the destination.
/// </summary>
/// <param name="accel">negative number, maximum deceleration</param>
/// <param name="dist">positive number, distance to travel</param>
/// <returns>The maximum angular speed to stop the destination</returns>
private float MaxAngleSpeed(float accel, float dist)
{
//myLogger.debugLog("accel: " + accel + ", dist: " + dist, "MaxAngleSpeed()");
return Math.Min((float)Math.Sqrt(-2 * accel * dist), dist); // capped for the sake of autopilot's reaction time
}
/// <summary>
/// Apply the calculated force ratios to the controller.
/// </summary>
public void MoveAndRotate()
{
CheckGrid();
if (NavSet.Settings_Current.CollisionAvoidance)
{
if (!myPathfinder.CanMove)
{
myLogger.debugLog("Pathfinder not allowing movement", "MoveAndRotate()");
StopMove();
}
if (!myPathfinder.CanRotate)
{
myLogger.debugLog("Pathfinder not allowing rotation", "MoveAndRotate()");
StopRotate();
}
}
myLogger.debugLog("moveForceRatio: " + moveForceRatio + ", rotateForceRatio: " + rotateForceRatio + ", move length: " + moveForceRatio.Length(), "MoveAndRotate()");
MyShipController controller = Block.Controller;
// if all the force ratio values are 0, Autopilot has to stop the ship, MoveAndRotate will not
if (moveForceRatio == Vector3.Zero && rotateForceRatio == Vector3.Zero)
{
MoveAndRotateStop();
return;
}
// clamp values and invert operations MoveAndRotate will perform
Vector3 moveControl; moveForceRatio.ApplyOperation(dim => MathHelper.Clamp(dim, -1, 1), out moveControl);
Vector2 rotateControl = Vector2.Zero;
rotateControl.X = MathHelper.Clamp(rotateForceRatio.X, -1, 1) * pixelsForMaxRotation;
rotateControl.Y = MathHelper.Clamp(rotateForceRatio.Y, -1, 1) * pixelsForMaxRotation;
float rollControl = MathHelper.Clamp(rotateForceRatio.Z, -1, 1) / RollControlMultiplier;
//myLogger.debugLog("moveControl: " + moveControl + ", rotateControl: " + rotateControl + ", rollControl: " + rollControl, "MoveAndRotate()");
m_stopped = false;
MyAPIGateway.Utilities.TryInvokeOnGameThread(() => controller.MoveAndRotate(moveControl, rotateControl, rollControl), myLogger);
}
private void CheckGrid()
{
if (myGrid != Block.CubeGrid)
{
myLogger.debugLog(myGrid != null, "Grid Changed!", "CheckGrid()", Logger.severity.INFO);
myGrid = Block.CubeGrid;
this.myThrust = new ThrustProfiler(myGrid);
this.myGyro = new GyroProfiler(myGrid);
this.myPathfinder = new Pathfinder.Pathfinder(myGrid, NavSet, this);
}
}
}
}
| |
/************************************************************************************
Filename : OVRDevice.cs
Content : Interface for the Oculus Rift Device
Created : February 14, 2013
Authors : Peter Giokaris
Copyright : Copyright 2013 Oculus VR, Inc. All Rights reserved.
Use of this software is subject to the terms of the Oculus LLC license
agreement provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
************************************************************************************/
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
//-------------------------------------------------------------------------------------
// ***** OVRDevice
//
// OVRDevice is the main interface to the Oculus Rift hardware. It includes wrapper functions
// for all exported C++ functions, as well as helper functions that use the stored Oculus
// variables to help set up camera behavior.
//
// This component is added to the OVRCameraController prefab. It can be part of any
// game object that one sees fit to place it. However, it should only be declared once,
// since there are public members that allow for tweaking certain Rift values in the
// Unity inspector.
//
public class OVRDevice : MonoBehaviour
{
// Imported functions from
// OVRPlugin.dll (PC)
// OVRPlugin.bundle (OSX)
// OVRPlugin.so (Linux, Android)
// MessageList
[StructLayout(LayoutKind.Sequential)]
public struct MessageList
{
public byte isHMDSensorAttached;
public byte isHMDAttached;
public byte isLatencyTesterAttached;
public MessageList(byte HMDSensor, byte HMD, byte LatencyTester)
{
isHMDSensorAttached = HMDSensor;
isHMDAttached = HMD;
isLatencyTesterAttached = LatencyTester;
}
}
// GLOBAL FUNCTIONS
[DllImport ("OculusPlugin", EntryPoint="OVR_Update")]
private static extern bool OVR_Update(ref MessageList messageList);
[DllImport ("OculusPlugin")]
private static extern bool OVR_Initialize();
[DllImport ("OculusPlugin")]
private static extern bool OVR_Destroy();
// SENSOR FUNCTIONS
[DllImport ("OculusPlugin")]
private static extern int OVR_GetSensorCount();
[DllImport ("OculusPlugin")]
private static extern bool OVR_IsHMDPresent();
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetSensorOrientation(int sensorID,
ref float w,
ref float x,
ref float y,
ref float z);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetSensorPredictedOrientation(int sensorID,
ref float w,
ref float x,
ref float y,
ref float z);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetSensorPredictionTime(int sensorID, ref float predictionTime);
[DllImport ("OculusPlugin")]
private static extern bool OVR_SetSensorPredictionTime(int sensorID, float predictionTime);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetSensorAccelGain(int sensorID, ref float accelGain);
[DllImport ("OculusPlugin")]
private static extern bool OVR_SetSensorAccelGain(int sensorID, float accelGain);
[DllImport ("OculusPlugin")]
private static extern bool OVR_EnableYawCorrection(int sensorID, float enable);
[DllImport ("OculusPlugin")]
private static extern bool OVR_ResetSensorOrientation(int sensorID);
// HMD FUNCTIONS
[DllImport ("OculusPlugin")]
private static extern bool OVR_IsSensorPresent(int sensor);
[DllImport ("OculusPlugin")]
private static extern System.IntPtr OVR_GetDisplayDeviceName();
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetScreenResolution(ref int hResolution, ref int vResolution);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetScreenSize(ref float hSize, ref float vSize);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetEyeToScreenDistance(ref float eyeToScreenDistance);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetInterpupillaryDistance(ref float interpupillaryDistance);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetLensSeparationDistance(ref float lensSeparationDistance);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetPlayerEyeHeight(ref float eyeHeight);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetEyeOffset(ref float leftEye, ref float rightEye);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetScreenVCenter(ref float vCenter);
[DllImport ("OculusPlugin")]
private static extern bool OVR_GetDistortionCoefficients(ref float k0,
ref float k1,
ref float k2,
ref float k3);
[DllImport ("OculusPlugin")]
private static extern bool OVR_RenderPortraitMode();
// LATENCY TEST FUNCTIONS
[DllImport ("OculusPlugin")]
private static extern void OVR_ProcessLatencyInputs();
[DllImport ("OculusPlugin")]
private static extern bool OVR_DisplayLatencyScreenColor(ref byte r,
ref byte g,
ref byte b);
[DllImport ("OculusPlugin")]
private static extern System.IntPtr OVR_GetLatencyResultsString();
// MAGNETOMETER YAW-DRIFT CORRECTION FUNCTIONS
// AUTOMATIC
[DllImport ("OculusPlugin")]
private static extern bool OVR_BeginMagAutoCalibraton(int sensor);
[DllImport ("OculusPlugin")]
private static extern bool OVR_StopMagAutoCalibraton(int sensor);
[DllImport ("OculusPlugin")]
private static extern bool OVR_UpdateMagAutoCalibration(int sensor);
// MANUAL
[DllImport ("OculusPlugin")]
private static extern bool OVR_BeginMagManualCalibration(int sensor);
[DllImport ("OculusPlugin")]
private static extern bool OVR_StopMagManualCalibration(int sensor);
[DllImport ("OculusPlugin")]
private static extern bool OVR_UpdateMagManualCalibration(int sensor);
[DllImport ("OculusPlugin")]
private static extern int OVR_MagManualCalibrationState(int sensor);
// SHARED
[DllImport ("OculusPlugin")]
private static extern int OVR_MagNumberOfSamples(int sensor);
[DllImport ("OculusPlugin")]
private static extern bool OVR_IsMagCalibrated(int sensor);
[DllImport ("OculusPlugin")]
private static extern bool OVR_EnableMagYawCorrection(int sensor, bool enable);
[DllImport ("OculusPlugin")]
private static extern bool OVR_IsYawCorrectionEnabled(int sensor);
[DllImport ("OculusPlugin")]
private static extern bool OVR_IsMagYawCorrectionInProgress(int sensor);
// Different orientations required for different trackers
enum SensorOrientation {Head, Other};
// PUBLIC
public float InitialPredictionTime = 0.05f; // 50 ms
public float InitialAccelGain = 0.05f; // default value
public bool ResetTracker = true; // if off, tracker will not reset when new scene
// is loaded
// STATIC
private static MessageList MsgList = new MessageList(0, 0, 0);
private static bool OVRInit = false;
public static int SensorCount = 0;
public static String DisplayDeviceName;
public static int HResolution, VResolution = 0; // pixels
public static float HScreenSize, VScreenSize = 0.0f; // meters
public static float EyeToScreenDistance = 0.0f; // meters
public static float LensSeparationDistance = 0.0f; // meters
public static float LeftEyeOffset, RightEyeOffset = 0.0f; // meters
public static float ScreenVCenter = 0.0f; // meters
public static float DistK0, DistK1, DistK2, DistK3 = 0.0f;
// Used to reduce the size of render distortion and give better fidelity
public static float DistortionFitScale = 1.0f;
// The physical offset of the lenses, used for shifting both IPD and lens distortion
private static float LensOffsetLeft, LensOffsetRight = 0.0f;
// Fit to top of the image (default is 5" display)
private static float DistortionFitX = 0.0f;
private static float DistortionFitY = 1.0f;
// Copied from initialized public variables set in editor
private static float PredictionTime = 0.0f;
private static float AccelGain = 0.0f;
// We will keep map sensors to different numbers to know which sensor is
// attached to which device
private static Dictionary<int,int> SensorList = new Dictionary<int, int>();
private static Dictionary<int,SensorOrientation> SensorOrientationList =
new Dictionary<int, SensorOrientation>();
// * * * * * * * * * * * * *
// Awake
void Awake ()
{
// Initialize static Dictionary lists first
InitSensorList(false);
InitOrientationSensorList();
OVRInit = OVR_Initialize();
if(OVRInit == false)
return;
// * * * * * * *
// DISPLAY SETUP
// We will get the HMD so that we can eventually target it within Unity
DisplayDeviceName += Marshal.PtrToStringAnsi(OVR_GetDisplayDeviceName());
OVR_GetScreenResolution (ref HResolution, ref VResolution);
OVR_GetScreenSize (ref HScreenSize, ref VScreenSize);
OVR_GetEyeToScreenDistance(ref EyeToScreenDistance);
OVR_GetLensSeparationDistance(ref LensSeparationDistance);
OVR_GetEyeOffset (ref LeftEyeOffset, ref RightEyeOffset);
OVR_GetScreenVCenter (ref ScreenVCenter);
OVR_GetDistortionCoefficients( ref DistK0, ref DistK1, ref DistK2, ref DistK3);
// Distortion fit parameters based on if we are using a 5" (Prototype, DK2+) or 7" (DK1)
if (HScreenSize < 0.140f) // 5.5"
{
DistortionFitX = 0.0f;
DistortionFitY = 1.0f;
}
else // 7" (DK1)
{
DistortionFitX = -1.0f;
DistortionFitY = 0.0f;
DistortionFitScale = 0.7f;
}
// Calculate the lens offsets for each eye and store
CalculatePhysicalLensOffsets(ref LensOffsetLeft, ref LensOffsetRight);
// * * * * * * *
// SENSOR SETUP
SensorCount = OVR_GetSensorCount();
// PredictionTime set, to init sensor directly
if(PredictionTime > 0.0f)
OVR_SetSensorPredictionTime(SensorList[0], PredictionTime);
else
SetPredictionTime(SensorList[0], InitialPredictionTime);
// AcelGain set, used to correct gyro with accel.
// Default value is appropriate for typical use.
if(AccelGain > 0.0f)
OVR_SetSensorAccelGain(SensorList[0], AccelGain);
else
SetAccelGain(SensorList[0], InitialAccelGain);
}
// Start (Note: make sure to always have a Start function for classes that have
// editors attached to them)
void Start()
{
}
// Update
// We can detect if our devices have been plugged or unplugged, as well as
// run things that need to be updated in our game thread
void Update()
{
MessageList oldMsgList = MsgList;
OVR_Update(ref MsgList);
// HMD SENSOR
if((MsgList.isHMDSensorAttached != 0) &&
(oldMsgList.isHMDSensorAttached == 0))
{
OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.HMDSensor, true);
//Debug.Log("HMD SENSOR ATTACHED");
}
else if((MsgList.isHMDSensorAttached == 0) &&
(oldMsgList.isHMDSensorAttached != 0))
{
OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.HMDSensor, false);
//Debug.Log("HMD SENSOR DETACHED");
}
// HMD
if((MsgList.isHMDAttached != 0) &&
(oldMsgList.isHMDAttached == 0))
{
OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.HMD, true);
//Debug.Log("HMD ATTACHED");
}
else if((MsgList.isHMDAttached == 0) &&
(oldMsgList.isHMDAttached != 0))
{
OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.HMD, false);
//Debug.Log("HMD DETACHED");
}
// LATENCY TESTER
if((MsgList.isLatencyTesterAttached != 0) &&
(oldMsgList.isLatencyTesterAttached == 0))
{
OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.LatencyTester, true);
//Debug.Log("LATENCY TESTER ATTACHED");
}
else if((MsgList.isLatencyTesterAttached == 0) &&
(oldMsgList.isLatencyTesterAttached != 0))
{
OVRMessenger.Broadcast<OVRMainMenu.Device, bool>("Sensor_Attached", OVRMainMenu.Device.LatencyTester, false);
//Debug.Log("LATENCY TESTER DETACHED");
}
}
// OnDestroy
void OnDestroy()
{
// We may want to turn this off so that values are maintained between level / scene loads
if(ResetTracker == true)
{
OVR_Destroy();
OVRInit = false;
}
}
// * * * * * * * * * * * *
// PUBLIC FUNCTIONS
// * * * * * * * * * * * *
// Inited - Check to see if system has been initialized
public static bool IsInitialized()
{
return OVRInit;
}
// HMDPreset
public static bool IsHMDPresent()
{
return OVR_IsHMDPresent();
}
// SensorPreset
public static bool IsSensorPresent(int sensor)
{
return OVR_IsSensorPresent(SensorList[sensor]);
}
// GetOrientation
public static bool GetOrientation(int sensor, ref Quaternion q)
{
float w = 0, x = 0, y = 0, z = 0;
if (OVR_GetSensorOrientation(SensorList[sensor], ref w, ref x, ref y, ref z) == true)
{
q.w = w; q.x = x; q.y = y; q.z = z;
OrientSensor(sensor, ref q);
return true;
}
return false;
}
// GetPredictedOrientation
public static bool GetPredictedOrientation(int sensor, ref Quaternion q)
{
float w = 0, x = 0, y = 0, z = 0;
if (OVR_GetSensorPredictedOrientation(SensorList[sensor], ref w, ref x, ref y, ref z) == true)
{
q.w = w; q.x = x; q.y = y; q.z = z;
OrientSensor(sensor, ref q);
return true;
}
return false;
}
// ResetOrientation
public static bool ResetOrientation(int sensor)
{
return OVR_ResetSensorOrientation(SensorList[sensor]);
}
// GetPredictionTime
public static float GetPredictionTime(int sensor)
{
// return OVRSensorsGetPredictionTime(sensor, ref predictonTime);
return PredictionTime;
}
// SetPredictionTime
public static bool SetPredictionTime(int sensor, float predictionTime)
{
if ( (predictionTime > 0.0f) &&
(OVR_SetSensorPredictionTime(SensorList[sensor], predictionTime) == true))
{
PredictionTime = predictionTime;
return true;
}
return false;
}
// GetAccelGain
public static float GetAccelGain(int sensor)
{
return AccelGain;
}
// SetAccelGain
public static bool SetAccelGain(int sensor, float accelGain)
{
if ( (accelGain > 0.0f) &&
(OVR_SetSensorAccelGain(SensorList[sensor], accelGain) == true))
{
AccelGain = accelGain;
return true;
}
return false;
}
// GetDistortionCorrectionCoefficients
public static bool GetDistortionCorrectionCoefficients(ref float k0,
ref float k1,
ref float k2,
ref float k3)
{
if(!OVRInit)
return false;
k0 = DistK0;
k1 = DistK1;
k2 = DistK2;
k3 = DistK3;
return true;
}
// SetDistortionCorrectionCoefficients
public static bool SetDistortionCorrectionCoefficients(float k0,
float k1,
float k2,
float k3)
{
if(!OVRInit)
return false;
DistK0 = k0;
DistK1 = k1;
DistK2 = k2;
DistK3 = k3;
return true;
}
// GetPhysicalLensOffsets
public static bool GetPhysicalLensOffsets(ref float lensOffsetLeft,
ref float lensOffsetRight)
{
if(!OVRInit)
return false;
lensOffsetLeft = LensOffsetLeft;
lensOffsetRight = LensOffsetRight;
return true;
}
// GetIPD
public static bool GetIPD(ref float IPD)
{
if(!OVRInit)
return false;
OVR_GetInterpupillaryDistance(ref IPD);
return true;
}
// CalculateAspectRatio
public static float CalculateAspectRatio()
{
if(Application.isEditor)
return (Screen.width * 0.5f) / Screen.height;
else
return (HResolution * 0.5f) / VResolution;
}
// VerticalFOV
// Compute Vertical FOV based on distance, distortion, etc.
// Distance from vertical center to render vertical edge perceived through the lens.
// This will be larger then normal screen size due to magnification & distortion.
public static float VerticalFOV()
{
if(!OVRInit)
{
return 90.0f;
}
float percievedHalfScreenDistance = (VScreenSize / 2) * DistortionScale();
float VFov = Mathf.Rad2Deg * 2.0f *
Mathf.Atan(percievedHalfScreenDistance / EyeToScreenDistance);
return VFov;
}
// DistortionScale - Used to adjust size of shader based on
// shader K values to maximize screen size
public static float DistortionScale()
{
if(OVRInit)
{
float ds = 0.0f;
// Compute distortion scale from DistortionFitX & DistortionFitY.
// Fit value of 0.0 means "no fit".
if ((Mathf.Abs(DistortionFitX) < 0.0001f) && (Math.Abs(DistortionFitY) < 0.0001f))
{
ds = 1.0f;
}
else
{
// Convert fit value to distortion-centered coordinates before fit radius
// calculation.
float stereoAspect = 0.5f * Screen.width / Screen.height;
float dx = (DistortionFitX * DistortionFitScale) - LensOffsetLeft;
float dy = (DistortionFitY * DistortionFitScale) / stereoAspect;
float fitRadius = Mathf.Sqrt(dx * dx + dy * dy);
ds = CalcScale(fitRadius);
}
if(ds != 0.0f)
return ds;
}
return 1.0f; // no scale
}
// LatencyProcessInputs
public static void ProcessLatencyInputs()
{
OVR_ProcessLatencyInputs();
}
// LatencyProcessInputs
public static bool DisplayLatencyScreenColor(ref byte r, ref byte g, ref byte b)
{
return OVR_DisplayLatencyScreenColor(ref r, ref g, ref b);
}
// LatencyGetResultsString
public static System.IntPtr GetLatencyResultsString()
{
return OVR_GetLatencyResultsString();
}
// Computes scale that should be applied to the input render texture
// before distortion to fit the result in the same screen size.
// The 'fitRadius' parameter specifies the distance away from distortion center at
// which the input and output coordinates will match, assuming [-1,1] range.
public static float CalcScale(float fitRadius)
{
float s = fitRadius;
// This should match distortion equation used in shader.
float ssq = s * s;
float scale = s * (DistK0 + DistK1 * ssq + DistK2 * ssq * ssq + DistK3 * ssq * ssq * ssq);
return scale / fitRadius;
}
// CalculatePhysicalLensOffsets - Used to offset perspective and distortion shift
public static bool CalculatePhysicalLensOffsets(ref float leftOffset, ref float rightOffset)
{
leftOffset = 0.0f;
rightOffset = 0.0f;
if(!OVRInit)
return false;
float halfHSS = HScreenSize * 0.5f;
float halfLSD = LensSeparationDistance * 0.5f;
leftOffset = (((halfHSS - halfLSD) / halfHSS) * 2.0f) - 1.0f;
rightOffset = (( halfLSD / halfHSS) * 2.0f) - 1.0f;
return true;
}
// MAG YAW-DRIFT CORRECTION FUNCTIONS
// AUTO MAG CALIBRATION FUNCTIONS
// BeginMagAutoCalibraton
public static bool BeginMagAutoCalibration(int sensor)
{
return OVR_BeginMagAutoCalibraton(SensorList[sensor]);
}
// StopMagAutoCalibraton
public static bool StopMagAutoCalibration(int sensor)
{
return OVR_StopMagAutoCalibraton(SensorList[sensor]);
}
// UpdateMagAutoCalibration
public static bool UpdateMagAutoCalibration(int sensor)
{
return OVR_UpdateMagAutoCalibration(SensorList[sensor]);
}
// MANUAL MAG CALIBRATION FUNCTIONS
// BeginMagManualCalibration
public static bool BeginMagManualCalibration(int sensor)
{
return OVR_BeginMagManualCalibration(SensorList[sensor]);
}
// StopMagManualCalibration
public static bool StopMagManualCalibration(int sensor)
{
return OVR_StopMagManualCalibration(SensorList[sensor]);
}
// UpdateMagManualCalibration
public static bool UpdateMagManualCalibration(int sensor)
{
return OVR_UpdateMagManualCalibration(SensorList[sensor]);
}
// OVR_MagManualCalibrationState
// 0 = Forward, 1 = Up, 2 = Left, 3 = Right, 4 = Upper-Right, 5 = FAIL, 6 = SUCCESS!
public static int MagManualCalibrationState(int sensor)
{
return OVR_MagManualCalibrationState(SensorList[sensor]);
}
// SHARED MAG CALIBRATION FUNCTIONS
// MagNumberOfSamples
public static int MagNumberOfSamples(int sensor)
{
return OVR_MagNumberOfSamples(SensorList[sensor]);
}
// IsMagCalibrated
public static bool IsMagCalibrated(int sensor)
{
return OVR_IsMagCalibrated(SensorList[sensor]);
}
// EnableMagYawCorrection
public static bool EnableMagYawCorrection(int sensor, bool enable)
{
return OVR_EnableMagYawCorrection(SensorList[sensor], enable);
}
// OVR_IsYawCorrectionEnabled
public static bool IsYawCorrectionEnabled(int sensor)
{
return OVR_IsYawCorrectionEnabled(SensorList[sensor]);
}
// IsMagYawCorrectionInProgress
public static bool IsMagYawCorrectionInProgress(int sensor)
{
return OVR_IsMagYawCorrectionInProgress(SensorList[sensor]);
}
// InitSensorList:
// We can remap sensors to different parts
public static void InitSensorList(bool reverse)
{
SensorList.Clear();
if(reverse == true)
{
SensorList.Add(0,1);
SensorList.Add(1,0);
}
else
{
SensorList.Add(0,0);
SensorList.Add(1,1);
}
}
// InitOrientationSensorList
public static void InitOrientationSensorList()
{
SensorOrientationList.Clear();
SensorOrientationList.Add (0, SensorOrientation.Head);
SensorOrientationList.Add (1, SensorOrientation.Other);
}
// OrientSensor
// We will set up the sensor based on which one it is
public static void OrientSensor(int sensor, ref Quaternion q)
{
if(SensorOrientationList[sensor] == SensorOrientation.Head)
{
// Change the co-ordinate system from right-handed to Unity left-handed
/*
q.x = x;
q.y = y;
q.z = -z;
q = Quaternion.Inverse(q);
*/
// The following does the exact same conversion as above
q.x = -q.x;
q.y = -q.y;
}
else if(SensorOrientationList[sensor] == SensorOrientation.Other)
{
// Currently not used
float tmp = q.x;
q.x = q.z;
q.y = -q.y;
q.z = tmp;
}
}
// RenderPortraitMode
public static bool RenderPortraitMode()
{
return OVR_RenderPortraitMode();
}
// GetPlayerEyeHeight
public static bool GetPlayerEyeHeight(ref float eyeHeight)
{
return OVR_GetPlayerEyeHeight(ref eyeHeight);
}
}
| |
//
// AutoHideBox.cs
//
// Author:
// Lluis Sanchez Gual
//
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//#define ANIMATE_DOCKING
using System;
using Gtk;
using Gdk;
namespace Pinta.Docking
{
class AutoHideBox: DockFrameTopLevel
{
const bool ANIMATE = false;
static Gdk.Cursor resizeCursorW = new Gdk.Cursor (Gdk.CursorType.SbHDoubleArrow);
static Gdk.Cursor resizeCursorH = new Gdk.Cursor (Gdk.CursorType.SbVDoubleArrow);
bool resizing;
int resizePos;
int origSize;
int origPos;
bool horiz;
bool startPos;
DockFrame frame;
bool animating;
int targetSize;
int targetPos;
ScrollableContainer scrollable;
Gtk.PositionType position;
bool disposed;
bool insideGrip;
int gripSize = 8;
public AutoHideBox (DockFrame frame, DockItem item, Gtk.PositionType pos, int size): base (frame)
{
this.position = pos;
this.frame = frame;
this.targetSize = size;
horiz = pos == PositionType.Left || pos == PositionType.Right;
startPos = pos == PositionType.Top || pos == PositionType.Left;
Events = Events | Gdk.EventMask.EnterNotifyMask | Gdk.EventMask.LeaveNotifyMask;
Box fr;
CustomFrame cframe = new CustomFrame ();
switch (pos) {
case PositionType.Left: cframe.SetMargins (0, 0, 1, 1); break;
case PositionType.Right: cframe.SetMargins (0, 0, 1, 1); break;
case PositionType.Top: cframe.SetMargins (1, 1, 0, 0); break;
case PositionType.Bottom: cframe.SetMargins (1, 1, 0, 0); break;
}
if (frame.UseWindowsForTopLevelFrames) {
// When using a top level window on mac, clicks on the first 4 pixels next to the border
// are not detected. To avoid confusing the user (since the resize cursor is shown),
// we make the resize drag area smaller.
switch (pos) {
case PositionType.Left: cframe.SetPadding (0, 0, 0, 4); gripSize = 4; break;
case PositionType.Right: cframe.SetPadding (0, 0, 4, 0); gripSize = 4; break;
}
}
EventBox sepBox = new EventBox ();
cframe.Add (sepBox);
if (horiz) {
fr = new HBox ();
sepBox.Realized += delegate { sepBox.GdkWindow.Cursor = resizeCursorW; };
sepBox.WidthRequest = gripSize;
} else {
fr = new VBox ();
sepBox.Realized += delegate { sepBox.GdkWindow.Cursor = resizeCursorH; };
sepBox.HeightRequest = gripSize;
}
sepBox.Events = EventMask.AllEventsMask;
if (pos == PositionType.Left || pos == PositionType.Top)
fr.PackEnd (cframe, false, false, 0);
else
fr.PackStart (cframe, false, false, 0);
Add (fr);
ShowAll ();
Hide ();
#if ANIMATE_DOCKING
scrollable = new ScrollableContainer ();
scrollable.ScrollMode = false;
scrollable.Show ();
#endif
VBox itemBox = new VBox ();
itemBox.Show ();
item.TitleTab.Active = true;
itemBox.PackStart (item.TitleTab, false, false, 0);
itemBox.PackStart (item.Widget, true, true, 0);
item.Widget.Show ();
#if ANIMATE_DOCKING
scrollable.Add (itemBox);
fr.PackStart (scrollable, true, true, 0);
#else
fr.PackStart (itemBox, true, true, 0);
#endif
sepBox.ButtonPressEvent += OnSizeButtonPress;
sepBox.ButtonReleaseEvent += OnSizeButtonRelease;
sepBox.MotionNotifyEvent += OnSizeMotion;
sepBox.ExposeEvent += OnGripExpose;
sepBox.EnterNotifyEvent += delegate { insideGrip = true; sepBox.QueueDraw (); };
sepBox.LeaveNotifyEvent += delegate { insideGrip = false; sepBox.QueueDraw (); };
}
public bool Disposed {
get { return disposed; }
set { disposed = value; }
}
public void AnimateShow ()
{
#if ANIMATE_DOCKING
animating = true;
scrollable.ScrollMode = true;
scrollable.SetSize (position, targetSize);
switch (position) {
case PositionType.Left:
Width = 0;
break;
case PositionType.Right:
targetPos = X = X + Width;
Width = 0;
break;
case PositionType.Top:
Height = 0;
break;
case PositionType.Bottom:
targetPos = Y = Y + Height;
Height = 0;
break;
}
Show ();
GLib.Timeout.Add (10, RunAnimateShow);
#else
Show ();
#endif
}
public void AnimateHide ()
{
#if ANIMATE_DOCKING
animating = true;
scrollable.ScrollMode = true;
scrollable.SetSize (position, targetSize);
GLib.Timeout.Add (10, RunAnimateHide);
#else
Hide ();
#endif
}
bool RunAnimateShow ()
{
if (!animating)
return false;
switch (position) {
case PositionType.Left:
Width += 1 + (targetSize - Width) / 3;
if (Width < targetSize)
return true;
break;
case PositionType.Right:
Width += 1 + (targetSize - Width) / 3;
X = targetPos - Width;
if (Width < targetSize)
return true;
break;
case PositionType.Top:
Height += 1 + (targetSize - Height) / 3;
if (Height < targetSize)
return true;
break;
case PositionType.Bottom:
Height += 1 + (targetSize - Height) / 3;
Y = targetPos - Height;
if (Height < targetSize)
return true;
break;
}
scrollable.ScrollMode = false;
if (horiz)
Width = targetSize;
else
Height = targetSize;
animating = false;
return false;
}
bool RunAnimateHide ()
{
if (!animating)
return false;
switch (position) {
case PositionType.Left: {
int ns = Width - 1 - Width / 3;
if (ns > 0) {
Width = ns;
return true;
}
break;
}
case PositionType.Right: {
int ns = Width - 1 - Width / 3;
if (ns > 0) {
Width = ns;
X = targetPos - ns;
return true;
}
break;
}
case PositionType.Top: {
int ns = Height - 1 - Height / 3;
if (ns > 0) {
Height = ns;
return true;
}
break;
}
case PositionType.Bottom: {
int ns = Height - 1 - Height / 3;
if (ns > 0) {
Height = ns;
Y = targetPos - ns;
return true;
}
break;
}
}
Hide ();
animating = false;
return false;
}
protected override void OnHidden ()
{
base.OnHidden ();
animating = false;
}
protected override bool OnButtonPressEvent (EventButton evnt)
{
// Don't propagate the button press event to the parent frame,
// since it has a handler that hides all visible autohide pads
return true;
}
public int PadSize {
get {
return horiz ? Width : Height;
}
}
[GLib.ConnectBefore]
void OnSizeButtonPress (object ob, Gtk.ButtonPressEventArgs args)
{
if (!animating && args.Event.Button == 1 && !args.Event.TriggersContextMenu ()) {
int n;
if (horiz) {
frame.Toplevel.GetPointer (out resizePos, out n);
origSize = Width;
if (!startPos) {
origPos = X + origSize;
}
} else {
frame.Toplevel.GetPointer (out n, out resizePos);
origSize = Height;
if (!startPos) {
origPos = Y + origSize;
}
}
resizing = true;
}
}
void OnSizeButtonRelease (object ob, Gtk.ButtonReleaseEventArgs args)
{
resizing = false;
}
void OnSizeMotion (object ob, Gtk.MotionNotifyEventArgs args)
{
if (resizing) {
int newPos, n;
if (horiz) {
frame.Toplevel.GetPointer (out newPos, out n);
int diff = startPos ? (newPos - resizePos) : (resizePos - newPos);
int newSize = origSize + diff;
if (newSize < Child.SizeRequest ().Width)
newSize = Child.SizeRequest ().Width;
if (!startPos) {
X = origPos - newSize;
}
Width = newSize;
} else {
frame.Toplevel.GetPointer (out n, out newPos);
int diff = startPos ? (newPos - resizePos) : (resizePos - newPos);
int newSize = origSize + diff;
if (newSize < Child.SizeRequest ().Height)
newSize = Child.SizeRequest ().Height;
if (!startPos) {
Y = origPos - newSize;
}
Height = newSize;
}
frame.QueueResize ();
}
}
void OnGripExpose (object sender, Gtk.ExposeEventArgs args)
{
var w = (EventBox) sender;
StateType s = insideGrip ? StateType.Prelight : StateType.Normal;
using (var ctx = CairoHelper.Create (args.Event.Window)) {
ctx.SetSourceColor (w.Style.Background (s).ToCairoColor ());
ctx.Paint ();
}
}
}
class ScrollableContainer: EventBox
{
PositionType expandPos;
bool scrollMode;
int targetSize;
public bool ScrollMode {
get {
return scrollMode;
}
set {
scrollMode = value;
QueueResize ();
}
}
public void SetSize (PositionType expandPosition, int targetSize)
{
this.expandPos = expandPosition;
this.targetSize = targetSize;
QueueResize ();
}
protected override void OnSizeRequested (ref Requisition req)
{
base.OnSizeRequested (ref req);
if (scrollMode || Child == null) {
req.Width = 0;
req.Height = 0;
}
else
req = Child.SizeRequest ();
}
protected override void OnSizeAllocated (Rectangle alloc)
{
if (scrollMode && Child != null) {
switch (expandPos) {
case PositionType.Bottom:
alloc = new Rectangle (alloc.X, alloc.Y, alloc.Width, targetSize);
break;
case PositionType.Top:
alloc = new Rectangle (alloc.X, alloc.Y - targetSize + alloc.Height, alloc.Width, targetSize);
break;
case PositionType.Right:
alloc = new Rectangle (alloc.X, alloc.Y, targetSize, alloc.Height);
break;
case PositionType.Left:
alloc = new Rectangle (alloc.X - targetSize + alloc.Width, alloc.Y, targetSize, alloc.Height);
break;
}
}
base.OnSizeAllocated (alloc);
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GraphicsDeviceControl.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace EffectEditor.Controls
{
// System.Drawing and the XNA Framework both define Color and Rectangle
// types. To avoid conflicts, we specify exactly which ones to use.
using Color = System.Drawing.Color;
using Rectangle = Microsoft.Xna.Framework.Rectangle;
/// <summary>
/// Custom control uses the XNA Framework GraphicsDevice to render onto
/// a Windows Form. Derived classes can override the Initialize and Draw
/// methods to add their own drawing code.
/// </summary>
abstract public class GraphicsDeviceControl : Control
{
#region Fields
// However many GraphicsDeviceControl instances you have, they all share
// the same underlying GraphicsDevice, managed by this helper service.
protected GraphicsDeviceService graphicsDeviceService;
#endregion
#region Properties
/// <summary>
/// Gets a GraphicsDevice that can be used to draw onto this control.
/// </summary>
public GraphicsDevice GraphicsDevice
{
get { return graphicsDeviceService.GraphicsDevice; }
}
/// <summary>
/// Gets an IServiceProvider containing our IGraphicsDeviceService.
/// This can be used with components such as the ContentManager,
/// which use this service to look up the GraphicsDevice.
/// </summary>
public ServiceContainer Services
{
get { return services; }
}
ServiceContainer services = new ServiceContainer();
#endregion
#region Initialization
/// <summary>
/// Initializes the control.
/// </summary>
protected override void OnCreateControl()
{
// Don't initialize the graphics device if we are running in the designer.
if (!DesignMode)
{
graphicsDeviceService = GraphicsDeviceService.AddRef(Handle,
ClientSize.Width,
ClientSize.Height);
// Register the service, so components like ContentManager can find it.
services.AddService<IGraphicsDeviceService>(graphicsDeviceService);
// Give derived classes a chance to initialize themselves.
Initialize();
}
base.OnCreateControl();
}
/// <summary>
/// Disposes the control.
/// </summary>
protected override void Dispose(bool disposing)
{
if (graphicsDeviceService != null)
{
graphicsDeviceService.Release(disposing);
graphicsDeviceService = null;
}
base.Dispose(disposing);
}
#endregion
#region Paint
/// <summary>
/// Redraws the control in response to a WinForms paint message.
/// </summary>
protected override void OnPaint(PaintEventArgs e)
{
string beginDrawError = BeginDraw();
if (string.IsNullOrEmpty(beginDrawError))
{
// Draw the control using the GraphicsDevice.
Draw();
EndDraw();
}
else
{
// If BeginDraw failed, show an error message using System.Drawing.
PaintUsingSystemDrawing(e.Graphics, beginDrawError);
}
}
/// <summary>
/// Attempts to begin drawing the control. Returns an error message string
/// if this was not possible, which can happen if the graphics device is
/// lost, or if we are running inside the Form designer.
/// </summary>
string BeginDraw()
{
// If we have no graphics device, we must be running in the designer.
if (graphicsDeviceService == null)
{
return Text + "\n\n" + GetType();
}
// Make sure the graphics device is big enough, and is not lost.
string deviceResetError = HandleDeviceReset();
if (!string.IsNullOrEmpty(deviceResetError))
{
return deviceResetError;
}
// Many GraphicsDeviceControl instances can be sharing the same
// GraphicsDevice. The device backbuffer will be resized to fit the
// largest of these controls. But what if we are currently drawing
// a smaller control? To avoid unwanted stretching, we set the
// viewport to only use the top left portion of the full backbuffer.
Viewport viewport = new Viewport();
viewport.X = 0;
viewport.Y = 0;
viewport.Width = ClientSize.Width;
viewport.Height = ClientSize.Height;
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
GraphicsDevice.Viewport = viewport;
return null;
}
/// <summary>
/// Ends drawing the control. This is called after derived classes
/// have finished their Draw method, and is responsible for presenting
/// the finished image onto the screen, using the appropriate WinForms
/// control handle to make sure it shows up in the right place.
/// </summary>
void EndDraw()
{
try
{
Rectangle sourceRectangle = new Rectangle(0, 0, ClientSize.Width,
ClientSize.Height);
GraphicsDevice.Present(sourceRectangle, null, this.Handle);
}
catch
{
// Present might throw if the device became lost while we were
// drawing. The lost device will be handled by the next BeginDraw,
// so we just swallow the exception.
}
}
/// <summary>
/// Helper used by BeginDraw. This checks the graphics device status,
/// making sure it is big enough for drawing the current control, and
/// that the device is not lost. Returns an error string if the device
/// could not be reset.
/// </summary>
string HandleDeviceReset()
{
bool deviceNeedsReset = false;
switch (GraphicsDevice.GraphicsDeviceStatus)
{
case GraphicsDeviceStatus.Lost:
// If the graphics device is lost, we cannot use it at all.
return "Graphics device lost";
case GraphicsDeviceStatus.NotReset:
// If device is in the not-reset state, we should try to reset it.
deviceNeedsReset = true;
break;
default:
// If the device state is ok, check whether it is big enough.
PresentationParameters pp = GraphicsDevice.PresentationParameters;
deviceNeedsReset = (ClientSize.Width > pp.BackBufferWidth) ||
(ClientSize.Height > pp.BackBufferHeight);
break;
}
// Do we need to reset the device?
if (deviceNeedsReset)
{
try
{
graphicsDeviceService.ResetDevice(ClientSize.Width,
ClientSize.Height);
}
catch (Exception e)
{
return "Graphics device reset failed\n\n" + e;
}
}
return null;
}
/// <summary>
/// If we do not have a valid graphics device (for instance if the device
/// is lost, or if we are running inside the Form designer), we must use
/// regular System.Drawing method to display a status message.
/// </summary>
protected virtual void PaintUsingSystemDrawing(Graphics graphics, string text)
{
graphics.Clear(Color.CornflowerBlue);
using (Brush brush = new SolidBrush(Color.Black))
{
using (StringFormat format = new StringFormat())
{
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
graphics.DrawString(text, Font, brush, ClientRectangle, format);
}
}
}
/// <summary>
/// Ignores WinForms paint-background messages. The default implementation
/// would clear the control to the current background color, causing
/// flickering when our OnPaint implementation then immediately draws some
/// other color over the top using the XNA Framework GraphicsDevice.
/// </summary>
protected override void OnPaintBackground(PaintEventArgs pevent)
{
}
#endregion
#region Abstract Methods
/// <summary>
/// Derived classes override this to initialize their drawing code.
/// </summary>
protected abstract void Initialize();
/// <summary>
/// Derived classes override this to draw themselves using the GraphicsDevice.
/// </summary>
protected abstract void Draw();
#endregion
}
}
| |
#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.Indicators.Algo
File: ZigZag.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Indicators
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Ecng.Serialization;
using StockSharp.Algo.Candles;
using StockSharp.Localization;
using StockSharp.Messages;
/// <summary>
/// ZigZag.
/// </summary>
/// <remarks>
/// ZigZag traces and combines extreme points of the chart, distanced for not less than specified percentage by the price scale.
/// </remarks>
[DisplayName("ZigZag")]
[DescriptionLoc(LocalizedStrings.Str826Key)]
public class ZigZag : BaseIndicator
{
private readonly IList<Candle> _buffer = new List<Candle>();
private readonly List<decimal> _lowBuffer = new List<decimal>();
private readonly List<decimal> _highBuffer = new List<decimal>();
private readonly List<decimal> _zigZagBuffer = new List<decimal>();
private Func<Candle, decimal> _currentValue = candle => candle.ClosePrice;
private int _depth;
private int _backStep;
private bool _needAdd = true;
/// <summary>
/// Initializes a new instance of the <see cref="ZigZag"/>.
/// </summary>
public ZigZag()
{
BackStep = 3;
Depth = 12;
}
/// <summary>
/// Minimum number of bars between local maximums, minimums.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str827Key)]
[DescriptionLoc(LocalizedStrings.Str828Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public int BackStep
{
get { return _backStep; }
set
{
if (_backStep == value)
return;
_backStep = value;
Reset();
}
}
/// <summary>
/// Bars minimum, on which Zigzag will not build a second maximum (or minimum), if it is smaller (or larger) by a deviation of the previous respectively.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str829Key)]
[DescriptionLoc(LocalizedStrings.Str830Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public int Depth
{
get { return _depth; }
set
{
if (_depth == value)
return;
_depth = value;
Reset();
}
}
private Unit _deviation = new Unit(0.45m, UnitTypes.Percent);
/// <summary>
/// Minimum number of points between maximums (minimums) of two adjacent bars used by Zigzag indicator to form a local peak (local trough).
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str831Key)]
[DescriptionLoc(LocalizedStrings.Str832Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public Unit Deviation
{
get { return _deviation; }
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (_deviation == value)
return;
_deviation = value;
Reset();
}
}
private Func<Candle, decimal> _highValue = candle => candle.HighPrice;
/// <summary>
/// The converter, returning from the candle a price for search of maximum.
/// </summary>
[Browsable(false)]
public Func<Candle, decimal> HighValueFunc
{
get { return _highValue; }
set
{
_highValue = value;
Reset();
}
}
private Func<Candle, decimal> _lowValue = candle => candle.LowPrice;
/// <summary>
/// The converter, returning from the candle a price for search of minimum.
/// </summary>
[Browsable(false)]
public Func<Candle, decimal> LowValueFunc
{
get { return _lowValue; }
set
{
_lowValue = value;
Reset();
}
}
/// <summary>
/// The converter, returning from the candle a price for the current value.
/// </summary>
[Browsable(false)]
public Func<Candle, decimal> CurrentValueFunc
{
get { return _currentValue; }
set
{
_currentValue = value;
Reset();
}
}
/// <summary>
/// The indicator current value.
/// </summary>
[Browsable(false)]
public decimal CurrentValue { get; private set; }
/// <summary>
/// Shift for the last indicator value.
/// </summary>
[Browsable(false)]
public int LastValueShift { get; private set; }
/// <summary>
/// To reset the indicator status to initial. The method is called each time when initial settings are changed (for example, the length of period).
/// </summary>
public override void Reset()
{
_needAdd = true;
_buffer.Clear();
_lowBuffer.Clear();
_highBuffer.Clear();
_zigZagBuffer.Clear();
CurrentValue = 0;
LastValueShift = 0;
base.Reset();
}
/// <summary>
/// To handle the input value.
/// </summary>
/// <param name="input">The input value.</param>
/// <returns>The resulting value.</returns>
protected override IIndicatorValue OnProcess(IIndicatorValue input)
{
var candle = input.GetValue<Candle>();
if (_needAdd)
{
_buffer.Insert(0, candle);
_lowBuffer.Insert(0, 0);
_highBuffer.Insert(0, 0);
_zigZagBuffer.Insert(0, 0);
}
else
{
_buffer[0] = candle;
_lowBuffer[0] = 0;
_highBuffer[0] = 0;
_zigZagBuffer[0] = 0;
}
const int level = 3;
int limit;
decimal lastHigh = 0;
decimal lastLow = 0;
if (_buffer.Count - 1 == 0)
{
limit = _buffer.Count - Depth;
}
else
{
int i = 0, count = 0;
while (count < level && i < _buffer.Count - Depth)
{
var res = _zigZagBuffer[i];
if (res != 0)
{
count++;
}
i++;
}
limit = --i;
}
for (var shift = limit; shift >= 0; shift--)
{
//--- low
var val = _buffer.Skip(shift).Take(Depth).Min(v => _lowValue(v));
if (val == lastLow)
{
val = 0.0m;
}
else
{
lastLow = val;
if (_lowValue(_buffer[shift]) - val > 0.0m * val / 100)
{
val = 0.0m;
}
else
{
for (var back = 1; back <= BackStep; back++)
{
var res = _lowBuffer[shift + back];
if (res != 0 && res > val)
{
_lowBuffer[shift + back] = 0.0m;
}
}
}
}
if (_lowValue(_buffer[shift]) == val)
_lowBuffer[shift] = val;
else
_lowBuffer[shift] = 0m;
//--- high
val = _buffer.Skip(shift).Take(Depth).Max(v => _highValue(v));
if (val == lastHigh)
{
val = 0.0m;
}
else
{
lastHigh = val;
if (val - _highValue(_buffer[shift]) > 0.0m * val / 100)
{
val = 0.0m;
}
else
{
for (var back = 1; back <= BackStep; back++)
{
var res = _highBuffer[shift + back];
if (res != 0 && res < val)
{
_highBuffer[shift + back] = 0.0m;
}
}
}
}
if (_highValue(_buffer[shift]) == val)
_highBuffer[shift] = val;
else
_highBuffer[shift] = 0m;
}
// final cutting
lastHigh = -1;
lastLow = -1;
var lastHighPos = -1;
var lastLowPos = -1;
for (var shift = limit; shift >= 0; shift--)
{
var curLow = _lowBuffer[shift];
var curHigh = _highBuffer[shift];
if ((curLow == 0) && (curHigh == 0))
continue;
//---
if (curHigh != 0)
{
if (lastHigh > 0)
{
if (lastHigh < curHigh)
{
_highBuffer[lastHighPos] = 0;
}
else
{
_highBuffer[shift] = 0;
}
}
//---
if (lastHigh < curHigh || lastHigh < 0)
{
lastHigh = curHigh;
lastHighPos = shift;
}
lastLow = -1;
}
//----
if (curLow != 0)
{
if (lastLow > 0)
{
if (lastLow > curLow)
{
_lowBuffer[lastLowPos] = 0;
}
else
{
_lowBuffer[shift] = 0;
}
}
//---
if ((curLow < lastLow) || (lastLow < 0))
{
lastLow = curLow;
lastLowPos = shift;
}
lastHigh = -1;
}
}
for (var shift = limit; shift >= 0; shift--)
{
if (shift >= _buffer.Count - Depth)
{
_zigZagBuffer[shift] = 0.0m;
}
else
{
var res = _highBuffer[shift];
if (res != 0.0m)
{
_zigZagBuffer[shift] = res;
}
else
{
_zigZagBuffer[shift] = _lowBuffer[shift];
}
}
}
int valuesCount = 0, valueId = 0;
for (; valueId < _zigZagBuffer.Count && valuesCount < 2; valueId++)
{
if (_zigZagBuffer[valueId] != 0)
valuesCount++;
}
_needAdd = input.IsFinal;
if (valuesCount != 2)
return new DecimalIndicatorValue(this);
if (input.IsFinal)
IsFormed = true;
LastValueShift = valueId - 1;
CurrentValue = _currentValue(_buffer[0]);
return new DecimalIndicatorValue(this, _zigZagBuffer[LastValueShift]);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="settings">Settings storage.</param>
public override void Load(SettingsStorage settings)
{
base.Load(settings);
BackStep = settings.GetValue<int>(nameof(BackStep));
Depth = settings.GetValue<int>(nameof(Depth));
Deviation.Load(settings.GetValue<SettingsStorage>(nameof(Deviation)));
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="settings">Settings storage.</param>
public override void Save(SettingsStorage settings)
{
base.Save(settings);
settings.SetValue(nameof(BackStep), BackStep);
settings.SetValue(nameof(Depth), Depth);
settings.SetValue(nameof(Deviation), Deviation.Save());
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
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.Linq;
using SpatialAnalysis.Geometry;
using SpatialAnalysis.CellularEnvironment;
using System.Windows;
namespace SpatialAnalysis.IsovistUtility
{
/// <summary>
/// Enum EscapeRouteType
/// </summary>
public enum EscapeRouteType
{
/// <summary>
/// All of the escape routes will be returned
/// </summary>
All = 0,
/// <summary>
/// The escape routes will be simplified with respect to angle and their weighting factors
/// </summary>
WeightedAndSimplified = 1,
}
/// <summary>
/// Defines the cell states in the generation of the isovist
/// </summary>
public enum CELL_STATE
{
/// <summary>
/// Not processed yet
/// </summary>
UNKNOWN = 0,
/// <summary>
/// Visible Cell
/// </summary>
VISIBLE = 1,
/// <summary>
/// Cell on the edge which can propagate in the field of visibility
/// </summary>
EDGE = 2,
/// <summary>
/// Cell that intersect with rays
/// </summary>
RAY_EXCLUDED = 3
}
/// <summary>
/// This class includes methods for calculating cellular isovists, cells on the borders of the isovists, calculating scape routs and their simplifications.
/// </summary>
public class CellularIsovistCalculator
{
private List<Index> _edge { get; set; }
private List<Index> _temp_edge { get; set; }
private CELL_STATE[,] _cell_states { get; set; }
private CellularFloor _cellularFloor { get; set; }
private UV _vantagePoint { get; set; }
private double _tolerance { get; set; }
private BarrierType _barrierType { get; set; }
private Index _vantageIndex { get; set; }
private double _depthSquared { get; set; }
private double _depth { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CellularIsovistCalculator"/> class.
/// This constructor is designed to be called in parallel and access to it is only allowed internally.
/// </summary>
/// <param name="isovistVantagePoint">The isovist vantage point.</param>
/// <param name="typeOfBarrier">The type of barrier.</param>
/// <param name="cellularFloor">The cellular floor.</param>
/// <param name="Tolerance">The tolerance.</param>
internal CellularIsovistCalculator(UV isovistVantagePoint, BarrierType typeOfBarrier,
CellularFloor cellularFloor, double depth, double Tolerance = OSMDocument.AbsoluteTolerance)
{
this._edge = new List<Index>();
this._temp_edge = new List<Index>();
this._cell_states = new CELL_STATE[cellularFloor.GridWidth, cellularFloor.GridHeight];
this._cellularFloor = cellularFloor;
this._vantagePoint = isovistVantagePoint;
this._tolerance = Tolerance;
this._barrierType = typeOfBarrier;
this._vantageIndex = cellularFloor.FindIndex(this._vantagePoint);
this._depth = Math.Abs(depth);
this._depthSquared = this._depth * this._depth;
}
private CellularIsovistCalculator(Cell cell, BarrierType typeOfBarrier,
CellularFloor cellularFloor, double depth, double Tolerance = OSMDocument.AbsoluteTolerance)
{
this._edge = new List<Index>();
this._temp_edge = new List<Index>();
this._cell_states = new CELL_STATE[cellularFloor.GridWidth, cellularFloor.GridHeight];
this._cellularFloor = cellularFloor;
this._vantagePoint = cell + new UV(cellularFloor.CellSize / 2, cellularFloor.CellSize / 2);
this._tolerance = Tolerance;
this._barrierType = typeOfBarrier;
this._vantageIndex = cellularFloor.FindIndex(this._vantagePoint);
this._depth = Math.Abs(depth);
this._depthSquared = this._depth * this._depth;
}
private bool addToTempEdge(Index index)
{
if (this._cell_states[index.I, index.J] != CELL_STATE.EDGE)
{
this._temp_edge.Add(index);
this._cell_states[index.I, index.J] = CELL_STATE.EDGE;
return true;
}
return false;
}
private void swapEdges()
{
this._edge.Clear();
foreach (var index in this._temp_edge)
{
//chances are that a cell on the visibility edge gets ray excluded
if (this._cell_states[index.I, index.J] != CELL_STATE.RAY_EXCLUDED)
{
this._cell_states[index.I, index.J] = CELL_STATE.VISIBLE;
this._edge.Add(index);
}
}
this._temp_edge.Clear();
}
private void shootRay(UV rayOrigin)
{
UV direction = rayOrigin - this._vantagePoint;
Ray ray = new Ray(rayOrigin, direction, this._cellularFloor.Origin, this._cellularFloor.CellSize, this._tolerance);
double rayLength = this._depth - ray.InitialDirectionLength;
if (rayLength < 0) return;//Very unlikely to happen
UV rayEndPoint = ray.PointAt(rayLength + this._tolerance);
Index rayEndPointIndex = this._cellularFloor.FindIndex(rayEndPoint);
bool rayEndindexBelongToFloor = this._cellularFloor.ContainsCell(rayEndPointIndex);
if (rayEndindexBelongToFloor)
{
this._cell_states[rayEndPointIndex.I, rayEndPointIndex.J] = CELL_STATE.RAY_EXCLUDED;
}
Index baseIndex = this._cellularFloor.FindIndex(rayOrigin);
Index nextIndex = baseIndex.Copy();
bool extendRay = true;
//while (nextIndex != null)
while (extendRay)
{
//nextIndex = ray.NextIndex(this._cellularFloor.FindIndex, this._tolerance);
if (this._cellularFloor.ContainsCell(nextIndex))
{
switch (this._barrierType)
{
case BarrierType.Visual:
switch (this._cellularFloor.Cells[nextIndex.I, nextIndex.J].VisualOverlapState)
{
case OverlapState.Overlap:
foreach (var item in this._cellularFloor.Cells[nextIndex.I, nextIndex.J].VisualBarrierEdgeIndices)
{
double? distance = ray.DistanceToForIsovist(this._cellularFloor.VisualBarrierEdges[item], this._tolerance);
if (distance != null)
{
if (distance > this._tolerance)
{
extendRay = false;
//nextIndex = null;
}
}
}
break;
case OverlapState.Inside:
nextIndex = null;
break;
case OverlapState.Outside:
this._cell_states[nextIndex.I, nextIndex.J] = CELL_STATE.RAY_EXCLUDED; ;
break;
default:
break;
}
break;
case BarrierType.Physical:
switch (this._cellularFloor.Cells[nextIndex.I, nextIndex.J].PhysicalOverlapState)
{
case OverlapState.Overlap:
foreach (var item in this._cellularFloor.Cells[nextIndex.I, nextIndex.J].PhysicalBarrierEdgeIndices)
{
double? distance = ray.DistanceToForIsovist(this._cellularFloor.PhysicalBarrierEdges[item], this._tolerance);
if (distance != null)
{
if (distance > this._tolerance)
{
extendRay = false;
//nextIndex = null;
}
}
}
break;
case OverlapState.Inside:
nextIndex = null;
break;
case OverlapState.Outside:
this._cell_states[nextIndex.I, nextIndex.J] = CELL_STATE.RAY_EXCLUDED;
break;
default:
break;
}
break;
case BarrierType.Field:
switch (this._cellularFloor.Cells[nextIndex.I, nextIndex.J].FieldOverlapState)
{
case OverlapState.Overlap:
foreach (var item in this._cellularFloor.Cells[nextIndex.I, nextIndex.J].FieldBarrierEdgeIndices)
{
double? distance = ray.DistanceToForIsovist(this._cellularFloor.FieldBarrierEdges[item], this._tolerance);
if (distance != null)
{
if (distance > this._tolerance)
{
extendRay = false;
//nextIndex = null;
}
}
}
break;
case OverlapState.Inside:
this._cell_states[nextIndex.I, nextIndex.J] = CELL_STATE.RAY_EXCLUDED;
break;
case OverlapState.Outside:
nextIndex = null;
break;
default:
break;
}
break;
case BarrierType.BarrierBuffer:
switch (this._cellularFloor.Cells[nextIndex.I, nextIndex.J].BarrierBufferOverlapState)
{
case OverlapState.Overlap:
foreach (var item in this._cellularFloor.Cells[nextIndex.I, nextIndex.J].BarrierBufferEdgeIndices)
{
double? distance = ray.DistanceToForIsovist(this._cellularFloor.BarrierBufferEdges[item], this._tolerance);
if (distance != null)
{
if (distance > this._tolerance)
{
extendRay = false;
//nextIndex = null;
}
}
}
break;
case OverlapState.Inside:
nextIndex = null;
break;
case OverlapState.Outside:
this._cell_states[nextIndex.I, nextIndex.J] = CELL_STATE.RAY_EXCLUDED;
break;
default:
break;
}
break;
default:
break;
}
}
else
{
extendRay = false;
nextIndex = null;
}
if (extendRay)
{
nextIndex = ray.NextIndex(this._cellularFloor.FindIndex, this._tolerance);
if (nextIndex != null && this._cellularFloor.ContainsCell(nextIndex))
{
if(rayEndindexBelongToFloor && nextIndex == rayEndPointIndex)
{
extendRay = false;
}
}
}
}
if (nextIndex != null && nextIndex.Equals(baseIndex))
{
nextIndex = null;
}
if (nextIndex != null)
{
/*
* When a barrier blocks ray marching, the cell that contains it might be the end index at
* the current marching ray; however, if this cell is on a corner, it may contain edge points
* that should be considered for shooting new rays. If these rays are ignored the isovist
* will be calculated inaccurately. This case if rare in high resolution grids and is needed
* for robustness of the calculation. Checking this condition adds around 15% to the time of
* isovist calculation, but makes the results more accurate.
*/
List<UV> points = this._cellularFloor.Cells[nextIndex.I, nextIndex.J].GetEdgeEndPoint(this._barrierType);
if (null == points)
{
return;
}
foreach (var other in points)
{
this.shootRay(other);
}
}
}
/// <summary>
/// This function tests to see if a new index (possible) juxtapposed to an existing visible index
/// should be added to the visible indices or not.
/// </summary>
private void addNextIndex(Index possible)
{
if (this._cell_states[possible.I, possible.J] == CELL_STATE.UNKNOWN)
{
double distance = UV.GetLengthSquared(this._cellularFloor.Cells[possible.I, possible.J], this._vantagePoint);
if (distance < this._depthSquared)
{
switch (this._barrierType)
{
case BarrierType.Visual:
if (this._cellularFloor.Cells[possible.I, possible.J].VisualOverlapState == OverlapState.Overlap)
{
if(this._cellularFloor.Cells[possible.I, possible.J].VisualBarrierEndPoints != null)
{
foreach (var pt in this._cellularFloor.Cells[possible.I, possible.J].VisualBarrierEndPoints)
{
shootRay(pt);
}
}
}
if (this._cellularFloor.Cells[possible.I, possible.J].VisualOverlapState == OverlapState.Outside)
{
this.addToTempEdge(possible);
}
break;
case BarrierType.Physical:
if (this._cellularFloor.Cells[possible.I, possible.J].PhysicalOverlapState == OverlapState.Overlap)
{
if (this._cellularFloor.Cells[possible.I, possible.J].PhysicalBarrierEndPoints != null)
{
foreach (var pt in this._cellularFloor.Cells[possible.I, possible.J].PhysicalBarrierEndPoints)
{
shootRay(pt);
}
}
}
if (this._cellularFloor.Cells[possible.I, possible.J].PhysicalOverlapState == OverlapState.Outside)
{
this.addToTempEdge(possible);
}
break;
case BarrierType.Field:
if (this._cellularFloor.Cells[possible.I, possible.J].FieldOverlapState == OverlapState.Overlap)
{
if (this._cellularFloor.Cells[possible.I, possible.J].FieldBarrierEndPoints != null)
{
foreach (var pt in this._cellularFloor.Cells[possible.I, possible.J].FieldBarrierEndPoints)
{
shootRay(pt);
}
}
}
if (this._cellularFloor.Cells[possible.I, possible.J].FieldOverlapState == OverlapState.Inside)
{
this.addToTempEdge(possible);
}
break;
case BarrierType.BarrierBuffer:
if (this._cellularFloor.Cells[possible.I, possible.J].BarrierBufferOverlapState == OverlapState.Overlap)
{
if (this._cellularFloor.Cells[possible.I, possible.J].BufferBarrierEndPoints != null)
{
foreach (var pt in this._cellularFloor.Cells[possible.I, possible.J].BufferBarrierEndPoints)
{
shootRay(pt);
}
}
}
if (this._cellularFloor.Cells[possible.I, possible.J].BarrierBufferOverlapState == OverlapState.Outside)
{
this.addToTempEdge(possible);
}
break;
default:
break;
}
}
}
}
/// <summary>
/// Returns a collection of cells that are completely visible from a vantage point withing a given distance
/// </summary>
/// <param name="vantagePoint">Center of Visibility</param>
/// <param name="tolerance">Numerical Tolerance</param>
/// <returns>Isovist as Collection of Cells</returns>
private Isovist getIsovist()
{
Cell cell = this._cellularFloor.FindCell(this._vantageIndex);
if (cell == null)
{
return null;
}
switch (this._barrierType)
{
case BarrierType.Visual:
if (cell.VisualOverlapState != OverlapState.Outside)
{
return null;
}
break;
case BarrierType.Physical:
if (cell.PhysicalOverlapState != OverlapState.Outside)
{
return null;
}
break;
case BarrierType.Field:
if (cell.FieldOverlapState != OverlapState.Inside)
{
return null;
}
break;
case BarrierType.BarrierBuffer:
if (cell.BarrierBufferOverlapState != OverlapState.Outside)
{
return null;
}
break;
default:
break;
}
//creating the first neighbors
foreach (var item in Index.Neighbors)
{
Index neighbor = item + this._vantageIndex;
if (this._cellularFloor.ContainsCell(neighbor))
{
switch (this._barrierType)
{
case BarrierType.Visual:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].VisualOverlapState == OverlapState.Outside)
{
this.addToTempEdge(neighbor);
}
break;
case BarrierType.Physical:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].PhysicalOverlapState == OverlapState.Outside)
{
this.addToTempEdge(neighbor);
}
break;
case BarrierType.Field:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].FieldOverlapState == OverlapState.Inside)
{
this.addToTempEdge(neighbor);
}
break;
case BarrierType.BarrierBuffer:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].BarrierBufferOverlapState == OverlapState.Outside)
{
this.addToTempEdge(neighbor);
}
break;
default:
break;
}
}
}
this._cell_states[this._vantageIndex.I, this._vantageIndex.J] = CELL_STATE.VISIBLE;
foreach (var item in this._temp_edge)
{
this._cell_states[item.I, item.J] = CELL_STATE.VISIBLE;
}
this.swapEdges();
while (this._edge.Count != 0)
{
foreach (Index item in _edge)
{
var _direction = item - this._vantageIndex;
if (_direction.I == 0)
{
// first
Index possible = new Index(
item.I - 1,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// second
possible = new Index(
item.I,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// third
possible = new Index(
item.I + 1,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
}
else if (_direction.J == 0)
{
// first
Index possible = new Index(
item.I + Math.Sign(_direction.I),
item.J - 1);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// second
possible = new Index(
item.I + Math.Sign(_direction.I),
item.J);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// third
possible = new Index(
item.I + Math.Sign(_direction.I),
item.J + 1);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
}
else
{
// first
Index possible = new Index(
item.I + Math.Sign(_direction.I),
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// second
possible = new Index(
item.I + Math.Sign(_direction.I),
item.J);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// third
possible = new Index(
item.I,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
}
}
this.swapEdges();
}
HashSet<int> cells = new HashSet<int>();
for (int i = 0; i < this._cellularFloor.GridWidth; i++)
{
for (int j = 0; j < this._cellularFloor.GridHeight; j++)
{
if (this._cell_states[i, j] == CELL_STATE.VISIBLE)
{
cells.Add(this._cellularFloor.Cells[i, j].ID);
}
}
}
var isovist = new Isovist(cell, cells);
return isovist;
}
private HashSet<Cell> getEscapeRoute(double depth)
{
Cell cell = this._cellularFloor.FindCell(this._vantageIndex);
if (cell == null)
{
return null;
}
switch (this._barrierType)
{
case BarrierType.Visual:
if (cell.VisualOverlapState != OverlapState.Outside)
{
return null;
}
break;
case BarrierType.Physical:
if (cell.PhysicalOverlapState != OverlapState.Outside)
{
return null;
}
break;
case BarrierType.Field:
if (cell.FieldOverlapState != OverlapState.Inside)
{
return null;
}
break;
case BarrierType.BarrierBuffer:
if (cell.BarrierBufferOverlapState != OverlapState.Outside)
{
return null;
}
break;
default:
break;
}
double depthSquared = depth * depth;
//creating the first neighbors
foreach (var item in Index.Neighbors)
{
Index neighbor = item + this._vantageIndex;
if (this._cellularFloor.ContainsCell(neighbor))
{
switch (this._barrierType)
{
case BarrierType.Visual:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].VisualOverlapState == OverlapState.Outside)
{
this.addToTempEdge(neighbor);
}
break;
case BarrierType.Physical:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].PhysicalOverlapState == OverlapState.Outside)
{
this.addToTempEdge(neighbor);
}
break;
case BarrierType.Field:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].FieldOverlapState == OverlapState.Inside)
{
this.addToTempEdge(neighbor);
}
break;
case BarrierType.BarrierBuffer:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].BarrierBufferOverlapState == OverlapState.Outside)
{
this.addToTempEdge(neighbor);
}
break;
default:
break;
}
}
}
this._cell_states[this._vantageIndex.I, this._vantageIndex.J] = CELL_STATE.VISIBLE;
this.swapEdges();
while (_edge.Count != 0)
{
foreach (Index item in _edge)
{
var _direction = item - this._vantageIndex;
if (_direction.I == 0)
{
// first
Index possible = new Index(
item.I - 1,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// second
possible = new Index(
item.I,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// third
possible = new Index(
item.I + 1,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
}
else if (_direction.J == 0)
{
// first
Index possible = new Index(
item.I + Math.Sign(_direction.I),
item.J - 1);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// second
possible = new Index(
item.I + Math.Sign(_direction.I),
item.J);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// third
possible = new Index(
item.I + Math.Sign(_direction.I),
item.J + 1);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
}
else
{
// first
Index possible = new Index(
item.I + Math.Sign(_direction.I),
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// second
possible = new Index(
item.I + Math.Sign(_direction.I),
item.J);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// third
possible = new Index(
item.I,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
}
}
this.swapEdges();
}
HashSet<Cell> Overlap = new HashSet<Cell>();
for (int i = 0; i < this._cellularFloor.GridWidth; i++)
{
for (int j = 0; j < this._cellularFloor.GridHeight; j++)
{
if (this._cell_states[i, j] == CELL_STATE.RAY_EXCLUDED)
{
foreach (Index neighbor in Index.Neighbors)
{
int i_ = neighbor.I + i;
int j_ = neighbor.J + j;
if (this._cellularFloor.ContainsCell(i_, j_))
{
if (this._cell_states[i_, j_] == CELL_STATE.VISIBLE)
{
Overlap.Add(this._cellularFloor.Cells[i_, j_]);
}
}
}
}
}
}
return Overlap;
}
private void calculateIsovist(double depth)
{
Cell cell = this._cellularFloor.FindCell(this._vantageIndex);
if (cell == null)
{
return;
}
switch (this._barrierType)
{
case BarrierType.Visual:
if (cell.VisualOverlapState != OverlapState.Outside)
{
return;
}
break;
case BarrierType.Physical:
if (cell.PhysicalOverlapState != OverlapState.Outside)
{
return;
}
break;
case BarrierType.Field:
if (cell.FieldOverlapState != OverlapState.Inside)
{
return;
}
break;
case BarrierType.BarrierBuffer:
if (cell.BarrierBufferOverlapState != OverlapState.Outside)
{
return;
}
break;
default:
break;
}
double depthSquared = depth * depth;
//creating the first neighbors
foreach (var item in Index.Neighbors)
{
Index neighbor = item + this._vantageIndex;
if (this._cellularFloor.ContainsCell(neighbor))
{
switch (this._barrierType)
{
case BarrierType.Visual:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].VisualOverlapState == OverlapState.Outside)
{
this.addToTempEdge(neighbor);
}
break;
case BarrierType.Physical:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].PhysicalOverlapState == OverlapState.Outside)
{
this.addToTempEdge(neighbor);
}
break;
case BarrierType.Field:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].FieldOverlapState == OverlapState.Inside)
{
this.addToTempEdge(neighbor);
}
break;
case BarrierType.BarrierBuffer:
if (this._cellularFloor.Cells[neighbor.I, neighbor.J].BarrierBufferOverlapState == OverlapState.Outside)
{
this.addToTempEdge(neighbor);
}
break;
default:
break;
}
}
}
this._cell_states[this._vantageIndex.I, this._vantageIndex.J] = CELL_STATE.VISIBLE;
foreach (var item in this._temp_edge)
{
this._cell_states[item.I, item.J] = CELL_STATE.VISIBLE;
}
this.swapEdges();
while (this._edge.Count != 0)
{
foreach (Index item in _edge)
{
var _direction = item - this._vantageIndex;
if (_direction.I == 0)
{
// first
Index possible = new Index(
item.I - 1,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// second
possible = new Index(
item.I,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// third
possible = new Index(
item.I + 1,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
}
else if (_direction.J == 0)
{
// first
Index possible = new Index(
item.I + Math.Sign(_direction.I),
item.J - 1);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// second
possible = new Index(
item.I + Math.Sign(_direction.I),
item.J);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// third
possible = new Index(
item.I + Math.Sign(_direction.I),
item.J + 1);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
}
else
{
// first
Index possible = new Index(
item.I + Math.Sign(_direction.I),
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// second
possible = new Index(
item.I + Math.Sign(_direction.I),
item.J);
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
// third
possible = new Index(
item.I,
item.J + Math.Sign(_direction.J));
if (this._cellularFloor.ContainsCell(possible))
{
this.addNextIndex(possible);
}
}
}
this.swapEdges();
}
}
/// <summary>
/// Gets the isovist.
/// </summary>
/// <param name="isovistVantagePoint">The isovist vantage point.</param>
/// <param name="depth">The depth of the isovist view.</param>
/// <param name="typeOfBarrier">The type of barriers.</param>
/// <param name="cellularFloor">The cellular floor.</param>
/// <param name="Tolerance">The tolerance.</param>
/// <returns>Isovist.</returns>
public static Isovist GetIsovist(UV isovistVantagePoint, double depth, BarrierType typeOfBarrier,
CellularFloor cellularFloor, double Tolerance = OSMDocument.AbsoluteTolerance)
{
CellularIsovistCalculator isovistCalculator = new CellularIsovistCalculator(isovistVantagePoint, typeOfBarrier, cellularFloor, depth, Tolerance);
Isovist isovist = isovistCalculator.getIsovist();
isovistCalculator._cellularFloor = null;
isovistCalculator._vantagePoint = null;
isovistCalculator._vantageIndex = null;
isovistCalculator._temp_edge.Clear();
isovistCalculator._temp_edge = null;
isovistCalculator._cell_states = null;
isovistCalculator._edge.Clear();
isovistCalculator._edge = null;
isovistCalculator = null;
return isovist;
}
private static object _lock = new object();
/// <summary>
/// Gets all escape routes from a vantage point.
/// </summary>
/// <param name="isovistVantagePoint">The isovist vantage point.</param>
/// <param name="depth">The depth of isovist view.</param>
/// <param name="typeOfBarrier">The type of barriers.</param>
/// <param name="cellularFloor">The cellular floor.</param>
/// <param name="Tolerance">The tolerance.</param>
/// <returns>IsovistEscapeRoutes.</returns>
public static IsovistEscapeRoutes GetAllEscapeRoute(UV isovistVantagePoint, double depth,
BarrierType typeOfBarrier, CellularFloor cellularFloor, double Tolerance = OSMDocument.AbsoluteTolerance)
{
CellularIsovistCalculator isovistCalculator = new CellularIsovistCalculator(isovistVantagePoint, typeOfBarrier, cellularFloor, depth, Tolerance);
var cells = isovistCalculator.getEscapeRoute(depth);
List<Cell> OtherCells = CellularIsovistCalculator.ExtractIsovistEscapeRoute(cellularFloor, isovistCalculator._cell_states, typeOfBarrier);
cells.UnionWith(OtherCells);
IsovistEscapeRoutes isovistEscapeRoutes = new IsovistEscapeRoutes(cells.ToArray(),
cellularFloor.Cells[isovistCalculator._vantageIndex.I, isovistCalculator._vantageIndex.J]);
cells.Clear();
cells = null;
isovistCalculator._cellularFloor = null;
isovistCalculator._vantagePoint = null;
isovistCalculator._vantageIndex = null;
isovistCalculator._temp_edge.Clear();
isovistCalculator._temp_edge = null;
isovistCalculator._cell_states = null;
isovistCalculator._edge.Clear();
isovistCalculator._edge = null;
isovistCalculator = null;
return isovistEscapeRoutes;
}
private static bool isIsovistEscapeRoute(int i, int j, CellularFloor cellularFloor,
CELL_STATE[,] collection, BarrierType barriertype)
{
bool isEscapeRoute = false;
bool allneighborsInside = true;
foreach (Index item in Index.Neighbors)
{
int neighbor_I = item.I + i;
int neighbor_J = item.J + j;
if (cellularFloor.ContainsCell(neighbor_I, neighbor_J))
{
if (collection[neighbor_I, neighbor_J] != CELL_STATE.VISIBLE)
{
isEscapeRoute = true;
}
switch (barriertype)
{
case BarrierType.Visual:
if (cellularFloor.Cells[neighbor_I, neighbor_J].VisualOverlapState != OverlapState.Outside)
{
allneighborsInside = false;
}
break;
case BarrierType.Physical:
if (cellularFloor.Cells[neighbor_I, neighbor_J].PhysicalOverlapState != OverlapState.Outside)
{
allneighborsInside = false;
}
break;
case BarrierType.Field:
if (cellularFloor.Cells[neighbor_I, neighbor_J].FieldOverlapState != OverlapState.Inside)
{
allneighborsInside = false;
}
break;
case BarrierType.BarrierBuffer:
if (cellularFloor.Cells[neighbor_I, neighbor_J].BarrierBufferOverlapState != OverlapState.Outside)
{
allneighborsInside = false;
}
break;
default:
break;
}
}
}
return isEscapeRoute && allneighborsInside;
}
/// <summary>
/// Extracts the isovist escape routes.
/// </summary>
/// <param name="cellularFloor">The cellular floor.</param>
/// <param name="collection">A two dimensional array of Booleans representing the cellular floor in which the escape routs are marked true; otherwise false.</param>
/// <param name="barriertype">The barriertype.</param>
/// <param name="tolerance">The tolerance.</param>
/// <returns>List<Cell>.</returns>
public static List<Cell> ExtractIsovistEscapeRoute(CellularFloor cellularFloor,
CELL_STATE[,] collection, BarrierType barriertype, double tolerance = OSMDocument.AbsoluteTolerance)
{
var edge = new List<Cell>();
for (int i = 0; i < cellularFloor.GridWidth; i++)
{
for (int j = 0; j < cellularFloor.GridHeight; j++)
{
if (collection[i, j] == CELL_STATE.VISIBLE)
{
if (CellularIsovistCalculator.isIsovistEscapeRoute(i, j, cellularFloor, collection, barriertype))
{
edge.Add(cellularFloor.Cells[i, j]);
}
}
}
}
return edge;
}
// SimplifiedEscapeRoute step 1
#region GetWeightedSimplifiedEscapeRoute
/// <summary>
/// Gets the escape route which is simplified according to angle and the weighting factors that are assigned to them.
/// </summary>
/// <param name="isovistVantagePoint">The isovist vantage point.</param>
/// <param name="depth">The depth of the isovist view.</param>
/// <param name="typeOfBarrier">The type of barrier.</param>
/// <param name="cellularFloor">The cellular floor.</param>
/// <param name="staticCost">The static cost used to assign weighting factors.</param>
/// <param name="angleIntercept">The angle intercept.</param>
/// <param name="Tolerance">The tolerance.</param>
/// <returns>IsovistEscapeRoutes.</returns>
public static IsovistEscapeRoutes GetWeightedSimplifiedEscapeRoute(UV isovistVantagePoint, double depth,
BarrierType typeOfBarrier, CellularFloor cellularFloor, Dictionary<Cell, double> staticCost,
int angleIntercept, double Tolerance = OSMDocument.AbsoluteTolerance)
{
CellularIsovistCalculator isovistCalculator = new CellularIsovistCalculator(isovistVantagePoint, typeOfBarrier, cellularFloor, depth, Tolerance);
var cells = isovistCalculator.getEscapeRoute(depth);
List<Cell> OtherCells = CellularIsovistCalculator.ExtractIsovistEscapeRoute(cellularFloor, isovistCalculator._cell_states, typeOfBarrier);
cells.UnionWith(OtherCells);
IsovistEscapeRoutes weightedAndSimplifiedEscapeRoutes = new IsovistEscapeRoutes(cells.ToArray(),
cellularFloor.FindCell(isovistVantagePoint), angleIntercept, staticCost);
cells.Clear();
cells = null;
isovistCalculator._cellularFloor = null;
isovistCalculator._vantagePoint = null;
isovistCalculator._vantageIndex = null;
isovistCalculator._temp_edge.Clear();
isovistCalculator._temp_edge = null;
isovistCalculator._cell_states = null;
isovistCalculator._edge.Clear();
isovistCalculator._edge = null;
isovistCalculator = null;
return weightedAndSimplifiedEscapeRoutes;
}
#endregion
#region AgentEscapeRoutes
// step 3
/// <summary>
/// Gets the agent escape routes.
/// </summary>
/// <param name="vantageCell">The vantage cell.</param>
/// <param name="isovistDepth">The isovist depth.</param>
/// <param name="desiredNumber">The desired number of escape routes.</param>
/// <param name="cellularFloor">The cellular floor.</param>
/// <param name="staticCost">The static cost used as weighting factors.</param>
/// <param name="Tolerance">The tolerance.</param>
/// <returns>AgentEscapeRoutes.</returns>
public static AgentEscapeRoutes GetAgentEscapeRoutes(Cell vantageCell,
double isovistDepth, int desiredNumber,
CellularFloor cellularFloor, Dictionary<Cell, double> staticCost, double Tolerance = OSMDocument.AbsoluteTolerance)
{
CellularIsovistCalculator isovistCalculator = new CellularIsovistCalculator(vantageCell, BarrierType.BarrierBuffer, cellularFloor, isovistDepth, Tolerance);
var cells = isovistCalculator.getEscapeRoute(isovistDepth);
List<Cell> OtherCells = CellularIsovistCalculator.ExtractIsovistEscapeRoute(cellularFloor, isovistCalculator._cell_states, BarrierType.BarrierBuffer);
cells.UnionWith(OtherCells);
if (cells.Count == 0)
{
cells = null;
isovistCalculator._cellularFloor = null;
isovistCalculator._vantagePoint = null;
isovistCalculator._vantageIndex = null;
isovistCalculator._temp_edge.Clear();
isovistCalculator._temp_edge = null;
isovistCalculator._cell_states = null;
isovistCalculator._edge.Clear();
isovistCalculator._edge = null;
isovistCalculator = null;
return null;
}
AgentCellDestination[] destinations = AgentCellDestination.ExtractedEscapeRoute(vantageCell,
desiredNumber, cells, staticCost);
AgentEscapeRoutes agentScapeRoutes = new AgentEscapeRoutes(vantageCell, destinations);
cells.Clear();
cells = null;
isovistCalculator._cellularFloor = null;
isovistCalculator._vantagePoint = null;
isovistCalculator._vantageIndex = null;
isovistCalculator._temp_edge.Clear();
isovistCalculator._temp_edge = null;
isovistCalculator._cell_states = null;
isovistCalculator._edge.Clear();
isovistCalculator._edge = null;
isovistCalculator = null;
return agentScapeRoutes;
}
#endregion
}
}
| |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Orleans.Configuration;
using Orleans.GrainDirectory;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.LogConsistency;
using Orleans.Runtime.MembershipService;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.MultiClusterNetwork;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Providers;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
using Orleans.Runtime.Versions.Compatibility;
using Orleans.Runtime.Versions.Selector;
using Orleans.Serialization;
using Orleans.Streams;
using Orleans.Streams.Core;
using Orleans.Timers;
using Orleans.Versions;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Transactions;
using Orleans.LogConsistency;
using Microsoft.Extensions.Logging;
using Orleans.ApplicationParts;
using Orleans.Runtime.Utilities;
using System;
using System.Collections.Generic;
using Orleans.Metadata;
using Orleans.Statistics;
using Microsoft.Extensions.Options;
using Orleans.Configuration.Validators;
using Orleans.Runtime.Configuration;
namespace Orleans.Hosting
{
internal static class DefaultSiloServices
{
internal static void AddDefaultServices(HostBuilderContext context, IServiceCollection services)
{
services.AddOptions();
services.AddTransient<IConfigurationValidator, EndpointOptionsValidator>();
// Options logging
services.TryAddSingleton(typeof(IOptionFormatter<>), typeof(DefaultOptionsFormatter<>));
services.TryAddSingleton(typeof(IOptionFormatterResolver<>), typeof(DefaultOptionsFormatterResolver<>));
// Register system services.
services.TryAddSingleton<ILocalSiloDetails, LocalSiloDetails>();
services.TryAddSingleton<ISiloHost, SiloWrapper>();
services.TryAddTransient<ILifecycleSubject,LifecycleSubject>();
services.TryAddSingleton<ISiloLifecycleSubject,SiloLifecycleSubject>();
services.TryAddSingleton<ILifecycleParticipant<ISiloLifecycle>, SiloOptionsLogger>();
services.PostConfigure<SiloMessagingOptions>(options =>
{
//
// Assign environment specific defaults post configuration if user did not configured otherwise.
//
if (options.SiloSenderQueues==0)
{
options.SiloSenderQueues = Environment.ProcessorCount;
}
if (options.GatewaySenderQueues==0)
{
options.GatewaySenderQueues = Environment.ProcessorCount;
}
});
services.TryAddSingleton<TelemetryManager>();
services.TryAddFromExisting<ITelemetryProducer, TelemetryManager>();
services.TryAddSingleton<IAppEnvironmentStatistics, AppEnvironmentStatistics>();
services.TryAddSingleton<IHostEnvironmentStatistics, NoOpHostEnvironmentStatistics>();
services.TryAddSingleton<OverloadDetector>();
services.TryAddSingleton<ExecutorService>();
// queue balancer contructing related
services.TryAddTransient<IStreamQueueBalancer, ConsistentRingQueueBalancer>();
services.TryAddSingleton<IStreamSubscriptionHandleFactory, StreamSubscriptionHandlerFactory>();
services.TryAddSingleton<FallbackSystemTarget>();
services.TryAddSingleton<LifecycleSchedulingSystemTarget>();
services.AddLogging();
services.TryAddSingleton<ITimerRegistry, TimerRegistry>();
services.TryAddSingleton<IReminderRegistry, ReminderRegistry>();
services.TryAddSingleton<GrainRuntime>();
services.TryAddSingleton<IGrainRuntime, GrainRuntime>();
services.TryAddSingleton<IGrainCancellationTokenRuntime, GrainCancellationTokenRuntime>();
services.TryAddSingleton<OrleansTaskScheduler>();
services.TryAddSingleton<GrainFactory>(sp => sp.GetService<InsideRuntimeClient>().ConcreteGrainFactory);
services.TryAddFromExisting<IGrainFactory, GrainFactory>();
services.TryAddFromExisting<IInternalGrainFactory, GrainFactory>();
services.TryAddFromExisting<IGrainReferenceConverter, GrainFactory>();
services.TryAddSingleton<IGrainReferenceRuntime, GrainReferenceRuntime>();
services.TryAddSingleton<TypeMetadataCache>();
services.TryAddSingleton<ActivationDirectory>();
services.TryAddSingleton<ActivationCollector>();
services.TryAddSingleton<LocalGrainDirectory>();
services.TryAddFromExisting<ILocalGrainDirectory, LocalGrainDirectory>();
services.TryAddSingleton(sp => sp.GetRequiredService<LocalGrainDirectory>().GsiActivationMaintainer);
services.TryAddSingleton<SiloStatisticsManager>();
services.TryAddSingleton<GrainTypeManager>();
services.TryAddSingleton<MessageCenter>();
services.TryAddFromExisting<IMessageCenter, MessageCenter>();
services.TryAddFromExisting<ISiloMessageCenter, MessageCenter>();
services.TryAddSingleton(FactoryUtility.Create<MessageCenter, Gateway>);
services.TryAddSingleton<Dispatcher>(sp => sp.GetRequiredService<Catalog>().Dispatcher);
services.TryAddSingleton<InsideRuntimeClient>();
services.TryAddFromExisting<IRuntimeClient, InsideRuntimeClient>();
services.TryAddFromExisting<ISiloRuntimeClient, InsideRuntimeClient>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, InsideRuntimeClient>();
services.TryAddSingleton<MultiClusterGossipChannelFactory>();
services.TryAddSingleton<MultiClusterOracle>();
services.TryAddSingleton<MultiClusterRegistrationStrategyManager>();
services.TryAddFromExisting<IMultiClusterOracle, MultiClusterOracle>();
services.TryAddSingleton<DeploymentLoadPublisher>();
services.TryAddSingleton<MembershipOracle>();
services.TryAddFromExisting<IMembershipOracle, MembershipOracle>();
services.TryAddFromExisting<ISiloStatusOracle, MembershipOracle>();
services.TryAddSingleton<ClientObserverRegistrar>();
services.TryAddSingleton<SiloProviderRuntime>();
services.TryAddFromExisting<IStreamProviderRuntime, SiloProviderRuntime>();
services.TryAddFromExisting<IProviderRuntime, SiloProviderRuntime>();
services.TryAddSingleton<ImplicitStreamSubscriberTable>();
services.TryAddSingleton<MessageFactory>();
services.TryAddSingleton<IGrainRegistrar<GlobalSingleInstanceRegistration>, GlobalSingleInstanceRegistrar>();
services.TryAddSingleton<IGrainRegistrar<ClusterLocalRegistration>, ClusterLocalRegistrar>();
services.TryAddSingleton<RegistrarManager>();
services.TryAddSingleton<Factory<Grain, IMultiClusterRegistrationStrategy, ILogConsistencyProtocolServices>>(FactoryUtility.Create<Grain, IMultiClusterRegistrationStrategy, ProtocolServices>);
services.TryAddSingleton(FactoryUtility.Create<GrainDirectoryPartition>);
// Placement
services.AddSingleton<IConfigurationValidator, ActivationCountBasedPlacementOptionsValidator>();
services.TryAddSingleton<PlacementDirectorsManager>();
services.TryAddSingleton<ClientObserversPlacementDirector>();
// Configure the default placement strategy.
services.TryAddSingleton<PlacementStrategy, RandomPlacement>();
// Placement directors
services.AddPlacementDirector<RandomPlacement, RandomPlacementDirector>();
services.AddPlacementDirector<PreferLocalPlacement, PreferLocalPlacementDirector>();
services.AddPlacementDirector<StatelessWorkerPlacement, StatelessWorkerDirector>();
services.AddPlacementDirector<ActivationCountBasedPlacement, ActivationCountPlacementDirector>();
services.AddPlacementDirector<HashBasedPlacement, HashBasedPlacementDirector>();
// Activation selectors
services.AddSingletonKeyedService<Type, IActivationSelector, RandomPlacementDirector>(typeof(RandomPlacement));
services.AddSingletonKeyedService<Type, IActivationSelector, StatelessWorkerDirector>(typeof(StatelessWorkerPlacement));
// Versioning
services.TryAddSingleton<VersionSelectorManager>();
services.TryAddSingleton<CachedVersionSelectorManager>();
// Version selector strategy
services.TryAddSingleton<GrainVersionStore>();
services.AddFromExisting<IVersionStore, GrainVersionStore>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, GrainVersionStore>();
services.AddSingletonNamedService<VersionSelectorStrategy, AllCompatibleVersions>(nameof(AllCompatibleVersions));
services.AddSingletonNamedService<VersionSelectorStrategy, LatestVersion>(nameof(LatestVersion));
services.AddSingletonNamedService<VersionSelectorStrategy, MinimumVersion>(nameof(MinimumVersion));
// Versions selectors
services.AddSingletonKeyedService<Type, IVersionSelector, MinimumVersionSelector>(typeof(MinimumVersion));
services.AddSingletonKeyedService<Type, IVersionSelector, LatestVersionSelector>(typeof(LatestVersion));
services.AddSingletonKeyedService<Type, IVersionSelector, AllCompatibleVersionsSelector>(typeof(AllCompatibleVersions));
// Compatibility
services.TryAddSingleton<CompatibilityDirectorManager>();
// Compatability strategy
services.AddSingletonNamedService<CompatibilityStrategy, AllVersionsCompatible>(nameof(AllVersionsCompatible));
services.AddSingletonNamedService<CompatibilityStrategy, BackwardCompatible>(nameof(BackwardCompatible));
services.AddSingletonNamedService<CompatibilityStrategy, StrictVersionCompatible>(nameof(StrictVersionCompatible));
// Compatability directors
services.AddSingletonKeyedService<Type, ICompatibilityDirector, BackwardCompatilityDirector>(typeof(BackwardCompatible));
services.AddSingletonKeyedService<Type, ICompatibilityDirector, AllVersionsCompatibilityDirector>(typeof(AllVersionsCompatible));
services.AddSingletonKeyedService<Type, ICompatibilityDirector, StrictVersionCompatibilityDirector>(typeof(StrictVersionCompatible));
services.TryAddSingleton<Factory<IGrainRuntime>>(sp => () => sp.GetRequiredService<IGrainRuntime>());
// Grain activation
services.TryAddSingleton<Catalog>();
services.TryAddSingleton<GrainCreator>();
services.TryAddSingleton<IGrainActivator, DefaultGrainActivator>();
services.TryAddScoped<ActivationData.GrainActivationContextFactory>();
services.TryAddScoped<IGrainActivationContext>(sp => sp.GetRequiredService<ActivationData.GrainActivationContextFactory>().Context);
services.TryAddSingleton<IStreamSubscriptionManagerAdmin>(sp => new StreamSubscriptionManagerAdmin(sp.GetRequiredService<IStreamProviderRuntime>()));
services.TryAddSingleton<IConsistentRingProvider>(
sp =>
{
// TODO: make this not sux - jbragg
var consistentRingOptions = sp.GetRequiredService<IOptions<ConsistentRingOptions>>().Value;
var siloDetails = sp.GetRequiredService<ILocalSiloDetails>();
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
if (consistentRingOptions.UseVirtualBucketsConsistentRing)
{
return new VirtualBucketsRingProvider(siloDetails.SiloAddress, loggerFactory, consistentRingOptions.NumVirtualBucketsConsistentRing);
}
return new ConsistentRingProvider(siloDetails.SiloAddress, loggerFactory);
});
services.TryAddSingleton(typeof(IKeyedServiceCollection<,>), typeof(KeyedServiceCollection<,>));
// Serialization
services.TryAddSingleton<SerializationManager>();
services.TryAddSingleton<ITypeResolver, CachedTypeResolver>();
services.TryAddSingleton<IFieldUtils, FieldUtils>();
services.AddSingleton<BinaryFormatterSerializer>();
services.AddSingleton<BinaryFormatterISerializableSerializer>();
services.AddFromExisting<IKeyedSerializer, BinaryFormatterISerializableSerializer>();
services.AddSingleton<ILBasedSerializer>();
services.AddFromExisting<IKeyedSerializer, ILBasedSerializer>();
// Transactions
services.TryAddSingleton<ITransactionAgent, TransactionAgent>();
services.TryAddSingleton<Factory<ITransactionAgent>>(sp => () => sp.GetRequiredService<ITransactionAgent>());
services.TryAddSingleton<ITransactionManagerService, DisabledTransactionManagerService>();
// Application Parts
var applicationPartManager = context.GetApplicationPartManager();
services.TryAddSingleton<IApplicationPartManager>(applicationPartManager);
applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(RuntimeVersion).Assembly) {IsFrameworkAssembly = true});
applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(Silo).Assembly) {IsFrameworkAssembly = true});
applicationPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<GrainInterfaceFeature>());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<GrainClassFeature>());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<SerializerFeature>());
services.AddTransient<IConfigurationValidator, ApplicationPartValidator>();
//Add default option formatter if none is configured, for options which are required to be configured
services.ConfigureFormatter<SiloOptions>();
services.ConfigureFormatter<ProcessExitHandlingOptions>();
services.ConfigureFormatter<SchedulingOptions>();
services.ConfigureFormatter<PerformanceTuningOptions>();
services.ConfigureFormatter<SerializationProviderOptions>();
services.ConfigureFormatter<NetworkingOptions>();
services.ConfigureFormatter<SiloMessagingOptions>();
services.ConfigureFormatter<TypeManagementOptions>();
services.ConfigureFormatter<ClusterMembershipOptions>();
services.ConfigureFormatter<GrainDirectoryOptions>();
services.ConfigureFormatter<ActivationCountBasedPlacementOptions>();
services.ConfigureFormatter<GrainCollectionOptions>();
services.ConfigureFormatter<GrainVersioningOptions>();
services.ConfigureFormatter<ConsistentRingOptions>();
services.ConfigureFormatter<MultiClusterOptions>();
services.ConfigureFormatter<SiloStatisticsOptions>();
services.ConfigureFormatter<TelemetryOptions>();
services.ConfigureFormatter<LoadSheddingOptions>();
services.ConfigureFormatter<EndpointOptions>();
// This validator needs to construct the IMembershipOracle and the IMembershipTable
// so move it in the end so other validator are called first
services.AddTransient<IConfigurationValidator, SiloClusteringValidator>();
}
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:40 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.form
{
#region FieldSet
/// <inheritdocs />
/// <summary>
/// <p>A container for grouping sets of fields, rendered as a HTML <c>fieldset</c> element. The <see cref="Ext.form.FieldSetConfig.title">title</see>
/// config will be rendered as the fieldset's <c>legend</c>.</p>
/// <p>While FieldSets commonly contain simple groups of fields, they are general <see cref="Ext.container.Container">Containers</see>
/// and may therefore contain any type of components in their <see cref="Ext.form.FieldSetConfig.items">items</see>, including other nested containers.
/// The default <see cref="Ext.form.FieldSetConfig.layout">layout</see> for the FieldSet's items is <c>'anchor'</c>, but it can be configured to use any other
/// layout type.</p>
/// <p>FieldSets may also be collapsed if configured to do so; this can be done in two ways:</p>
/// <ol>
/// <li>Set the <see cref="Ext.form.FieldSetConfig.collapsible">collapsible</see> config to true; this will result in a collapse button being rendered next to
/// the <see cref="Ext.form.FieldSetConfig.title">legend title</see>, or:</li>
/// <li>Set the <see cref="Ext.form.FieldSetConfig.checkboxToggle">checkboxToggle</see> config to true; this is similar to using <see cref="Ext.form.FieldSetConfig.collapsible">collapsible</see> but renders
/// a <see cref="Ext.form.field.Checkbox">checkbox</see> in place of the toggle button. The fieldset will be expanded when the
/// checkbox is checked and collapsed when it is unchecked. The checkbox will also be included in the
/// <see cref="Ext.form.Basic.submit">form submit parameters</see> using the <see cref="Ext.form.FieldSetConfig.checkboxName">checkboxName</see> as its parameter name.</li>
/// </ol>
/// <h1>Example usage</h1>
/// <pre><code><see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.form.Panel">Ext.form.Panel</see>', {
/// title: 'Simple Form with FieldSets',
/// labelWidth: 75, // label settings here cascade unless overridden
/// url: 'save-form.php',
/// frame: true,
/// bodyStyle: 'padding:5px 5px 0',
/// width: 550,
/// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>(),
/// layout: 'column', // arrange fieldsets side by side
/// defaults: {
/// bodyPadding: 4
/// },
/// items: [{
/// // Fieldset in Column 1 - collapsible via toggle button
/// xtype:'fieldset',
/// columnWidth: 0.5,
/// title: 'Fieldset 1',
/// collapsible: true,
/// defaultType: 'textfield',
/// defaults: {anchor: '100%'},
/// layout: 'anchor',
/// items :[{
/// fieldLabel: 'Field 1',
/// name: 'field1'
/// }, {
/// fieldLabel: 'Field 2',
/// name: 'field2'
/// }]
/// }, {
/// // Fieldset in Column 2 - collapsible via checkbox, collapsed by default, contains a panel
/// xtype:'fieldset',
/// title: 'Show Panel', // title or checkboxToggle creates fieldset header
/// columnWidth: 0.5,
/// checkboxToggle: true,
/// collapsed: true, // fieldset initially collapsed
/// layout:'anchor',
/// items :[{
/// xtype: 'panel',
/// anchor: '100%',
/// title: 'Panel inside a fieldset',
/// frame: true,
/// height: 52
/// }]
/// }]
/// });
/// </code></pre>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class FieldSet : Ext.container.Container
{
/// <summary>
/// The name to assign to the fieldset's checkbox if checkboxToggle = true
/// (defaults to '[fieldset id]-checkbox').
/// </summary>
public JsString checkboxName;
/// <summary>
/// Set to true to render a checkbox into the fieldset frame just in front of the legend to expand/collapse the
/// fieldset when the checkbox is toggled.. This checkbox will be included in form submits using
/// the checkboxName.
/// Defaults to: <c>false</c>
/// </summary>
public bool checkboxToggle;
/// <summary>
/// Set to true to render the fieldset as collapsed by default. If checkboxToggle is specified, the checkbox
/// will also be unchecked by default.
/// Defaults to: <c>false</c>
/// </summary>
public bool collapsed;
/// <summary>
/// Set to true to make the fieldset collapsible and have the expand/collapse toggle button automatically rendered
/// into the legend element, false to keep the fieldset statically sized with no collapse button.
/// Another option is to configure checkboxToggle. Use the collapsed config to collapse the
/// fieldset by default.
/// Defaults to: <c>false</c>
/// </summary>
public bool collapsible;
/// <summary>
/// A title to be displayed in the fieldset's legend. May contain HTML markup.
/// </summary>
public JsString title;
/// <summary>
/// Set to true will add a listener to the titleCmp property for the click event which will execute the
/// toggle method. This option is only used when the collapsible property is set to true.
/// Defaults to: <c>true</c>
/// </summary>
public bool toggleOnTitleClick;
/// <summary>
/// Refers to the Ext.form.field.Checkbox component that is added next to the title in the legend. Only
/// populated if the fieldset is configured with checkboxToggle:true.
/// </summary>
public Ext.form.field.Checkbox checkboxCmp{get;set;}
/// <summary>
/// The component for the fieldset's legend. Will only be defined if the configuration requires a legend to be
/// created, by setting the title or checkboxToggle options.
/// </summary>
public Ext.Component legend{get;set;}
/// <summary>
/// Refers to the Ext.panel.Tool component that is added as the collapse/expand button next to the title in
/// the legend. Only populated if the fieldset is configured with collapsible:true.
/// </summary>
public Ext.panel.Tool toggleCmp{get;set;}
/// <summary>
/// Collapses the fieldset.
/// </summary>
/// <returns>
/// <span><see cref="Ext.form.FieldSet">Ext.form.FieldSet</see></span><div><p>this</p>
/// </div>
/// </returns>
public Ext.form.FieldSet collapse(){return null;}
/// <summary>
/// Creates the checkbox component. This is only called internally, but could be overridden in subclasses to
/// customize the checkbox's configuration or even return an entirely different component type.
/// </summary>
protected void createCheckboxCmp(){}
/// <summary>
/// Creates the legend title component. This is only called internally, but could be overridden in subclasses to
/// customize the title component. If toggleOnTitleClick is set to true, a listener for the click event
/// will toggle the collapsed state of the FieldSet.
/// </summary>
protected void createTitleCmp(){}
/// <summary>
/// Creates the toggle button component. This is only called internally, but could be overridden in subclasses to
/// customize the toggle component.
/// </summary>
protected void createToggleCmp(){}
/// <summary>
/// Expands the fieldset.
/// </summary>
/// <returns>
/// <span><see cref="Ext.form.FieldSet">Ext.form.FieldSet</see></span><div><p>this</p>
/// </div>
/// </returns>
public Ext.form.FieldSet expand(){return null;}
/// <summary>
/// Handle changes in the checkbox checked state
/// </summary>
/// <param name="cmp">
/// </param>
/// <param name="checked">
/// </param>
private void onCheckChange(object cmp, object @checked){}
/// <summary>
/// Collapse or expand the fieldset
/// </summary>
/// <param name="expanded">
/// </param>
private void setExpanded(object expanded){}
/// <summary>
/// Sets the title of this fieldset
/// </summary>
/// <param name="title"><p>The new title</p>
/// </param>
/// <returns>
/// <span><see cref="Ext.form.FieldSet">Ext.form.FieldSet</see></span><div><p>this</p>
/// </div>
/// </returns>
public Ext.form.FieldSet setTitle(JsString title){return null;}
/// <summary>
/// Toggle the fieldset's collapsed state to the opposite of what it is currently
/// </summary>
public void toggle(){}
public FieldSet(Ext.form.FieldSetConfig config){}
public FieldSet(){}
public FieldSet(params object[] args){}
}
#endregion
#region FieldSetConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class FieldSetConfig : Ext.container.ContainerConfig
{
/// <summary>
/// The name to assign to the fieldset's checkbox if checkboxToggle = true
/// (defaults to '[fieldset id]-checkbox').
/// </summary>
public JsString checkboxName;
/// <summary>
/// Set to true to render a checkbox into the fieldset frame just in front of the legend to expand/collapse the
/// fieldset when the checkbox is toggled.. This checkbox will be included in form submits using
/// the checkboxName.
/// Defaults to: <c>false</c>
/// </summary>
public bool checkboxToggle;
/// <summary>
/// Set to true to render the fieldset as collapsed by default. If checkboxToggle is specified, the checkbox
/// will also be unchecked by default.
/// Defaults to: <c>false</c>
/// </summary>
public bool collapsed;
/// <summary>
/// Set to true to make the fieldset collapsible and have the expand/collapse toggle button automatically rendered
/// into the legend element, false to keep the fieldset statically sized with no collapse button.
/// Another option is to configure checkboxToggle. Use the collapsed config to collapse the
/// fieldset by default.
/// Defaults to: <c>false</c>
/// </summary>
public bool collapsible;
/// <summary>
/// A title to be displayed in the fieldset's legend. May contain HTML markup.
/// </summary>
public JsString title;
/// <summary>
/// Set to true will add a listener to the titleCmp property for the click event which will execute the
/// toggle method. This option is only used when the collapsible property is set to true.
/// Defaults to: <c>true</c>
/// </summary>
public bool toggleOnTitleClick;
public FieldSetConfig(params object[] args){}
}
#endregion
#region FieldSetEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class FieldSetEvents : Ext.container.ContainerEvents
{
/// <summary>
/// Fires before this FieldSet is collapsed. Return false to prevent the collapse.
/// </summary>
/// <param name="f"><p>The FieldSet being collapsed.</p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void beforecollapse(Ext.form.FieldSet f, object eOpts){}
/// <summary>
/// Fires before this FieldSet is expanded. Return false to prevent the expand.
/// </summary>
/// <param name="f"><p>The FieldSet being expanded.</p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void beforeexpand(Ext.form.FieldSet f, object eOpts){}
/// <summary>
/// Fires after this FieldSet has collapsed.
/// </summary>
/// <param name="f"><p>The FieldSet that has been collapsed.</p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void collapse(Ext.form.FieldSet f, object eOpts){}
/// <summary>
/// Fires after this FieldSet has expanded.
/// </summary>
/// <param name="f"><p>The FieldSet that has been expanded.</p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void expand(Ext.form.FieldSet f, object eOpts){}
public FieldSetEvents(params object[] args){}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
namespace HackPrototype
{
abstract class HackGameBoardNodeContent
{
public HackGameBoardNodeContent() { }
abstract public void DrawSelf(SpriteBatch sb, HackGameBoardElement_Node node, HackNodeGameBoardMedia gameboarddrawing, Vector2 Nodedrawpos, float zoom);
abstract public void UpdateState(GameTime time, HackGameBoard board, HackGameBoardElement_Node node);
abstract public void OnAgentEnter(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node);
abstract public void OnAgentStay(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node);
abstract public void OnAgentExit(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node);
}
class HackGameBoardNodeContent_Loot : HackGameBoardNodeContent
{
/*
public enum HackGameBoardNodeContent_Loot_Level
{
HackGameBoardNodeContent_Loot_Level_One,
HackGameBoardNodeContent_Loot_Level_Two,
HackGameBoardNodeContent_Loot_Level_Three,
HackGameBoardNodeContent_Loot_Level_Four
};
*/
public enum HackGameBoardNodeContent_Loot_Color
{
HackGameBoardNodeContent_Loot_Color_Yellow,
HackGameBoardNodeContent_Loot_Color_Blue,
HackGameBoardNodeContent_Loot_Color_Black
};
//string currentValueString; //the string representation of what it's worth
float valueMultiplier = 1.0f; //what it's worth due to any multipliers
int baseValue; //what it's normally worth
int drawOffsetX; //offset of the draw to center it lengthwise
HackGameForwardLerpDrawHelper lerp;
CurrencyStringer valuestring = new CurrencyStringer(0);
HackGameReversibleLerpDrawHelper pulseEffect = new HackGameReversibleLerpDrawHelper(0.3f, 0.02f, 0.9f, 1.0f, Color.White, Color.White, Vector2.Zero, Vector2.Zero);
bool Empty = false;
HackGameAgent_Player PlayerHacking = null;
StringBuilder hackbackgroundstringbuilder;
float HackTimerRemaining = 0.0f;
float HackTimerMax = 0.0f;
int HackBackgroundMaxDrawDots = 40;
float HackBackgroundTextUpdateTimer = 0.0f;
float HackBackgroundTextUpdateTimerMax = 0.1f;
HackGameBoardNodeContent_Loot_Color LootColor = HackGameBoardNodeContent_Loot_Color.HackGameBoardNodeContent_Loot_Color_Blue;
//HackGameBoardNodeContent_Loot_Level LootLevel = HackGameBoardNodeContent_Loot_Level.HackGameBoardNodeContent_Loot_Level_One;
/*
public HackGameBoardNodeContent_Loot_Level GetLevel()
{
return LootLevel;
}
*/
public HackGameBoardNodeContent_Loot_Color GetColor()
{
return LootColor;
}
public int GetFinalValue()
{
return (int)((float)baseValue * valueMultiplier);
}
public void ApplyMultiplier(float multiplier)
{
if (valueMultiplier != multiplier)
{
valueMultiplier = multiplier;
UpdateValueString();
//set as "new" so it flashes a little
FlashNew();
}
}
private void FlashNew()
{
lerp = new HackGameForwardLerpDrawHelper(3.0f, 2.0f, 1.0f, 2.0f, Color.Yellow, Color.White, 2.0f, new Vector2(0, 5.0f), Vector2.Zero, 2.0f);
}
private void UpdateValueString()
{
valuestring.UpdateString((UInt64)GetFinalValue());
}
public HackGameBoardNodeContent_Loot(HackGameBoardNodeContent_Loot_Color color) : base()
{
LootColor = color;
switch (color)
{
case HackGameBoardNodeContent_Loot_Color.HackGameBoardNodeContent_Loot_Color_Blue:
baseValue = 5000;
HackTimerMax = 2.0f;
break;
case HackGameBoardNodeContent_Loot_Color.HackGameBoardNodeContent_Loot_Color_Yellow:
baseValue = 25000;
HackTimerMax = 4.0f;
break;
case HackGameBoardNodeContent_Loot_Color.HackGameBoardNodeContent_Loot_Color_Black:
baseValue = 100000;
HackTimerMax = 8.0f;
break;
}
HackTimerRemaining = HackTimerMax;
hackbackgroundstringbuilder = new StringBuilder(HackBackgroundMaxDrawDots);
UpdateValueString();
FlashNew();
}
public override void DrawSelf(SpriteBatch sb, HackGameBoardElement_Node node, HackNodeGameBoardMedia gameboarddrawing, Vector2 Nodedrawpos, float zoom)
{
Color drawColor = Color.White;
Texture2D tex = null;
if (Empty)
{
drawColor = new Color(.05f, .05f, .05f);
}
switch(LootColor)
{
case HackGameBoardNodeContent_Loot_Color.HackGameBoardNodeContent_Loot_Color_Blue:
tex = gameboarddrawing.Loot_Blue_Texture;
break;
case HackGameBoardNodeContent_Loot_Color.HackGameBoardNodeContent_Loot_Color_Black:
tex = gameboarddrawing.Loot_Black_Texture;
break;
case HackGameBoardNodeContent_Loot_Color.HackGameBoardNodeContent_Loot_Color_Yellow:
tex = gameboarddrawing.Loot_Yellow_Texture;
break;
}
sb.Draw(tex, Nodedrawpos, null, drawColor, 0, Vector2.Zero, zoom, SpriteEffects.None, 0);
//draw the 2x/4x
if (valueMultiplier == 2.0f)
{
sb.Draw(gameboarddrawing.Loot_2x_Score_Texture, Nodedrawpos, null, drawColor, 0, Vector2.Zero, zoom * pulseEffect.CurrentScale(), SpriteEffects.None, 0);
}
else if (valueMultiplier == 4.0f)
{
sb.Draw(gameboarddrawing.Loot_4x_Score_Texture, Nodedrawpos, null, drawColor, 0, Vector2.Zero, zoom * pulseEffect.CurrentScale(), SpriteEffects.None, 0);
}
//draw the timing ring
//0-10% - 0
//11-35% - 1
//36-60% - 2
//61-85% - 3
//86-100% - 4
if (!Empty && PlayerHacking != null)
{
if (PlayerHacking.IsHacking() == true)
{
Texture2D timingTex = null;
float pctTiming = HackTimerMax != 0.0f ? 1.0f - (HackTimerRemaining / HackTimerMax) : 0.0f;
{
if (pctTiming <= .1f)
{
timingTex = gameboarddrawing.TimingRingEmpty;
}
else if (pctTiming > .1f && pctTiming <= .35f)
{
timingTex = gameboarddrawing.TimingRing1_4;
}
else if (pctTiming > .35f && pctTiming <= .60f)
{
timingTex = gameboarddrawing.TimingRing2_4;
}
else if (pctTiming > .60f && pctTiming <= .85f)
{
timingTex = gameboarddrawing.TimingRing3_4;
}
else if (pctTiming > .85f)
{
timingTex = gameboarddrawing.TimingRingComplete;
}
}
sb.Draw(timingTex, Nodedrawpos, null, Color.White, 0, Vector2.Zero, zoom, SpriteEffects.None, 0);
}
}
//draw the $ amount
if (!Empty)
{
drawOffsetX = (int)(HackGameBoard.elementSize * zoom / 2.0f - (gameboarddrawing.LootAmount_Font.MeasureString(valuestring.outputstring).X) * zoom / 2.0f);
if (lerp != null && lerp.IsAlive())
{
drawOffsetX = (int)(HackGameBoard.elementSize / 2.0f - (gameboarddrawing.LootAmount_Font.MeasureString(valuestring.outputstring).X * lerp.CurrentScale()) / 2.0f);
sb.DrawString(gameboarddrawing.LootAmount_Font, valuestring.outputstring, Nodedrawpos + new Vector2(drawOffsetX, -20.0f * zoom) + lerp.CurrentPosition(), lerp.CurrentColor(), 0, Vector2.Zero, lerp.CurrentScale() * zoom, SpriteEffects.None, 0);
}
else
{
sb.DrawString(gameboarddrawing.LootAmount_Font, valuestring.outputstring, Nodedrawpos + new Vector2(drawOffsetX, -20.0f * zoom), Color.White, 0, Vector2.Zero, zoom, SpriteEffects.None, 1);
}
}
}
public override void OnAgentEnter(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node)
{
}
public override void OnAgentStay(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node)
{
if (!Empty && agent is HackGameAgent_Player)
{
PlayerHacking = (HackGameAgent_Player)agent;
PlayerHacking.SetHacking(true);
//our first time in!
board.GetMedia().StartHackLoopSound();
HackBackgroundTextUpdateTimer = HackBackgroundTextUpdateTimerMax;
}
}
public override void OnAgentExit(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node)
{
if (agent is HackGameAgent_Player)
{
((HackGameAgent_Player)(agent)).SetHacking(false);
PlayerHacking = null;
board.GetMedia().StopHackLoopSound();
//reset timer
HackTimerRemaining = HackTimerMax;
HackBackgroundTextUpdateTimer = 0.0f;
}
}
public override void UpdateState(GameTime time, HackGameBoard board, HackGameBoardElement_Node node)
{
if (lerp != null && lerp.IsAlive())
{
lerp.Update(time);
}
pulseEffect.Update(time);
if (!Empty && PlayerHacking != null && PlayerHacking.IsHacking() == true)
{
HackTimerRemaining -= (float)time.ElapsedGameTime.TotalSeconds * board.GetSpeedUpFactor();
float pctTiming = HackTimerMax != 0.0f ? 1.0f - (HackTimerRemaining / HackTimerMax) : 0.0f;
board.SetHackLoopSoundAmountComplete(pctTiming);
HackBackgroundTextUpdateTimer -= (float)time.ElapsedGameTime.TotalSeconds;
if (HackBackgroundTextUpdateTimer <= 0)
{
HackBackgroundTextUpdateTimer = HackBackgroundTextUpdateTimerMax;
//draw the right number of dots
pctTiming = HackTimerMax != 0.0f ? 1.0f - (HackTimerRemaining / HackTimerMax) : 0.0f;
int numdots = HackBackgroundMaxDrawDots - (int)((float)HackBackgroundMaxDrawDots * pctTiming);//blah
hackbackgroundstringbuilder.Remove(0, hackbackgroundstringbuilder.Length);
for(int i = 0; i < numdots; i++)
{
hackbackgroundstringbuilder.Append(board.r.NextDouble() > 0.5f ? '0' : '1');
}
board.AddBackgroundTextStandard(new StringBuilder(hackbackgroundstringbuilder.ToString()), 0); //have to create a copy in order for it to be unique in the list
}
if (HackTimerRemaining <= 0.0f)
{
Empty = true;
PlayerHacking.SetHacking(false);
PlayerHacking.HackSuccess();
board.StopHackLoopSound();
board.PlayHackSuccessSound();
board.AwardNodeContents(this);
//board.PopUpScoreboard(4.0f);
board.AddBackgroundTextAward(new StringBuilder("CRACKER SUCCESSFUL"), 0);
board.AddBackgroundTextAward(new StringBuilder("CONTENTS UNENCRYPTED"), 0.25f);
board.AddBackgroundTextAward(new StringBuilder("DELETING TRACES"), 0.5f);
}
}
}
}
class HackGameBoardNodeContent_Exit : HackGameBoardNodeContent
{
float timeToNextPing = 0.05f;
const float timePerPing = 0.75f;
bool StartPing_Draw = false;
const float timePerFlash = 0.75f;
float timeToNextFlash = 0.05f;
bool StartFlash_Draw = false;
HackGameForwardLerpDrawHelper lerp;
bool active = true;
public HackGameBoardNodeContent_Exit()
: base()
{
FlashNew();
}
public override void DrawSelf(SpriteBatch sb, HackGameBoardElement_Node node, HackNodeGameBoardMedia gameboarddrawing, Vector2 Nodedrawpos, float zoom)
{
if (active)
{
if (StartPing_Draw)
{
node.AddUIElement(gameboarddrawing.PingTexture, 1.5f, new Vector2(41.0f * zoom, 41.0f * zoom), new Vector2(41.0f * zoom, 41.0f * zoom), new Color(1.0f, 1.0f, 1.0f, 0.0f), new Color(0.0f, 0, 0, 0), 0.2f, 2.0f, 0.0f);
//gameboarddrawing.PlayerPingSound.Play();
StartPing_Draw = false;
}
}
if (StartFlash_Draw)
{
FlashNew();
StartFlash_Draw = false;
}
Vector2 newdrawpos = new Vector2(Nodedrawpos.X + (HackGameBoard.elementSize * zoom / 2.0f - HackGameBoard.elementSize * zoom * lerp.CurrentScale() / 2.0f), Nodedrawpos.Y);
sb.Draw(gameboarddrawing.ExitTexture, newdrawpos + lerp.CurrentPosition() * zoom, null, lerp.CurrentColor(), 0, Vector2.Zero, zoom * lerp.CurrentScale(), SpriteEffects.None, 0);
}
public override void UpdateState(GameTime time, HackGameBoard board, HackGameBoardElement_Node node)
{
float floatt = (float)time.ElapsedGameTime.TotalSeconds;
timeToNextPing -= floatt;
if (timeToNextPing <= 0)
{
StartPing_Draw = true;
timeToNextPing = timePerPing;
}
timeToNextFlash -= floatt;
if (timeToNextFlash <= 0)
{
StartFlash_Draw = true;
timeToNextFlash = timePerFlash;
}
if (lerp != null)
{
lerp.Update(time);
}
}
private void FlashNew()
{
lerp = new HackGameForwardLerpDrawHelper(0.66f, 0.9f, 1.0f, 0.66f, Color.Azure, Color.White, 0.66f, Vector2.Zero, Vector2.Zero, 2.0f);
}
public override void OnAgentEnter(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node)
{
if (agent is HackGameAgent_Player)
{
//YOU DID IT! EXIT!
((HackGameAgent_Player)agent).SetIsExiting();
active = false;
}
}
public override void OnAgentExit(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node) { }
public override void OnAgentStay(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node) { }
}
class HackGameBoardNodeContent_Weapon_Multimissile : HackGameBoardNodeContent
{
bool fired = false;
bool drawFire = false;
HackGameReversibleLerpDrawHelper pulseEffect = new HackGameReversibleLerpDrawHelper(0.3f, 0.01f, 0.9f, 1.0f, Color.White, Color.White, Vector2.Zero, Vector2.Zero);
public override void OnAgentEnter(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node)
{
if (!fired && agent is HackGameAgent_Player)
{
fired = true;
drawFire = true;
HackGameAgent_Projectile_Multimissile multi_north = new HackGameAgent_Projectile_Multimissile(board, HackGameAgent.MovementDirection.MovementDirection_North);
board.AddAgent(multi_north);
HackGameAgent_Projectile_Multimissile multi_south = new HackGameAgent_Projectile_Multimissile(board, HackGameAgent.MovementDirection.MovementDirection_South);
board.AddAgent(multi_south);
HackGameAgent_Projectile_Multimissile multi_east = new HackGameAgent_Projectile_Multimissile(board, HackGameAgent.MovementDirection.MovementDirection_East);
board.AddAgent(multi_east);
HackGameAgent_Projectile_Multimissile multi_west = new HackGameAgent_Projectile_Multimissile(board, HackGameAgent.MovementDirection.MovementDirection_West);
board.AddAgent(multi_west);
}
}
public override void OnAgentExit(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node) { }
public override void OnAgentStay(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node) { }
public override void DrawSelf(SpriteBatch sb, HackGameBoardElement_Node node, HackNodeGameBoardMedia gameboarddrawing, Vector2 Nodedrawpos, float zoom)
{
if (drawFire == true)
{
drawFire = false;
node.AddUIElement(gameboarddrawing.WeaponPingTexture, 0.75f, new Vector2(41.0f * zoom, 41.0f * zoom), new Vector2(41.0f * zoom, 41.0f * zoom), new Color(1.0f, 0.4f, 0.0f, 0.0f), new Color(1.0f, 1.0f, 0.0f, 0.0f), 0.2f, 4.0f, 0.0f);
gameboarddrawing.MissileLaunchSound.Play();
}
if (!fired)
{
sb.Draw(gameboarddrawing.Weapon_Multimissile_texture, Nodedrawpos + new Vector2(40.0f * zoom, 40.0f * zoom), null, Color.White, 0, new Vector2(40.0f, 40.0f), pulseEffect.CurrentScale() * zoom, SpriteEffects.None, 0);
}
}
public override void UpdateState(GameTime time, HackGameBoard board, HackGameBoardElement_Node node)
{ pulseEffect.Update(time); }
}
class HackGameBoardNodeContent_Weapon_Heatseeker : HackGameBoardNodeContent
{
bool fired = false;
bool drawFire = false;
HackGameReversibleLerpDrawHelper pulseEffect = new HackGameReversibleLerpDrawHelper(0.3f, 0.02f, 0.9f, 1.0f, Color.White, Color.White, Vector2.Zero, Vector2.Zero);
public override void OnAgentEnter(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node)
{
if (!fired && agent is HackGameAgent_Player)
{
fired = true;
drawFire = true;
HackGameAgent_Projectile_Heatseeker heatseeker = new HackGameAgent_Projectile_Heatseeker(board);
board.AddAgent(heatseeker);
}
}
public override void OnAgentExit(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node) { }
public override void OnAgentStay(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node) { }
public override void DrawSelf(SpriteBatch sb, HackGameBoardElement_Node node, HackNodeGameBoardMedia gameboarddrawing, Vector2 Nodedrawpos, float zoom)
{
if (drawFire == true)
{
drawFire = false;
node.AddUIElement(gameboarddrawing.WeaponPingTexture, 0.75f, new Vector2(41.0f * zoom, 41.0f * zoom), new Vector2(41.0f * zoom, 41.0f * zoom), new Color(1.0f, 0.4f, 0.0f, 0.0f), new Color(1.0f, 1.0f, 0.0f, 0.0f), 0.2f, 4.0f, 0.0f);
gameboarddrawing.MissileLaunchSound.Play();
}
if (!fired)
{
sb.Draw(gameboarddrawing.Weapon_Heatseeker_texture, Nodedrawpos+ new Vector2(40.0f * zoom, 40.0f * zoom), null, Color.White, 0, new Vector2(40.0f, 40.0f), zoom * pulseEffect.CurrentScale(), SpriteEffects.None, 0);
}
}
public override void UpdateState(GameTime time, HackGameBoard board, HackGameBoardElement_Node node)
{ pulseEffect.Update(time); }
}
class HackGameBoardNodeContent_Weapon_Decoy : HackGameBoardNodeContent
{
bool fired = false;
bool drawFire = false;
HackGameReversibleLerpDrawHelper pulseEffect = new HackGameReversibleLerpDrawHelper(0.3f, 0.03f, 0.9f, 1.0f, Color.White, Color.White, Vector2.Zero, Vector2.Zero);
public override void OnAgentEnter(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node)
{
if (!fired && agent is HackGameAgent_Player)
{
fired = true;
drawFire = true;
}
}
public override void OnAgentExit(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node) { }
public override void OnAgentStay(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node) { }
public override void DrawSelf(SpriteBatch sb, HackGameBoardElement_Node node, HackNodeGameBoardMedia gameboarddrawing, Vector2 Nodedrawpos, float zoom)
{
if (drawFire == true)
{
drawFire = false;
node.AddUIElement(gameboarddrawing.WeaponPingTexture, 0.75f, new Vector2(41.0f * zoom, 41.0f * zoom), new Vector2(41.0f * zoom, 41.0f * zoom), new Color(1.0f, 0.4f, 0.0f, 0.0f), new Color(1.0f, 1.0f, 0.0f, 0.0f), 0.2f, 4.0f, 0.0f);
}
if (!fired)
{
sb.Draw(gameboarddrawing.Weapon_Decoy_texture, Nodedrawpos + new Vector2(41.0f * zoom, 41.0f * zoom), null, Color.White, 0, new Vector2(40.0f, 40.0f), zoom * pulseEffect.CurrentScale(), SpriteEffects.None, 0);
}
}
public override void UpdateState(GameTime time, HackGameBoard board, HackGameBoardElement_Node node)
{ pulseEffect.Update(time); }
}
class HackGameBoardNodeContent_Weapon_Mortar : HackGameBoardNodeContent
{
bool fired = false;
bool drawFire = false;
HackGameReversibleLerpDrawHelper pulseEffect = new HackGameReversibleLerpDrawHelper(0.3f, 0.01f, 0.9f, 1.0f, Color.White, Color.White, Vector2.Zero, Vector2.Zero);
public override void OnAgentEnter(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node)
{
if (!fired && agent is HackGameAgent_Player)
{
fired = true;
drawFire = true;
HackGameAgent_Projectile_Mortar mortar = new HackGameAgent_Projectile_Mortar(board);
board.AddAgent(mortar);
}
}
public override void OnAgentExit(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node) { }
public override void OnAgentStay(HackGameAgent agent, HackGameBoard board, HackGameBoardElement_Node node) { }
public override void DrawSelf(SpriteBatch sb, HackGameBoardElement_Node node, HackNodeGameBoardMedia gameboarddrawing, Vector2 Nodedrawpos, float zoom)
{
if (drawFire == true)
{
drawFire = false;
node.AddUIElement(gameboarddrawing.WeaponPingTexture, 0.75f, new Vector2(41.0f * zoom, 41.0f * zoom), new Vector2(41.0f * zoom, 41.0f * zoom), new Color(1.0f, 0.4f, 0.0f, 0.0f), new Color(1.0f, 1.0f, 0.0f, 0.0f), 0.2f, 4.0f, 0.0f);
gameboarddrawing.MissileLaunchSound.Play();
}
if (!fired)
{
sb.Draw(gameboarddrawing.Weapon_Mortar_texture, Nodedrawpos + new Vector2(40.0f * zoom, 40.0f * zoom), null, Color.White, 0, new Vector2(40.0f, 40.0f), pulseEffect.CurrentScale() * zoom, SpriteEffects.None, 0);
}
}
public override void UpdateState(GameTime time, HackGameBoard board, HackGameBoardElement_Node node)
{ pulseEffect.Update(time); }
}
}
| |
/*
* UIPermission.cs - Implementation of the
* "System.Security.Permissions.UIPermission" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* 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
*/
namespace System.Security.Permissions
{
#if CONFIG_PERMISSIONS && !ECMA_COMPAT
using System;
using System.Security;
public sealed class UIPermission
: CodeAccessPermission, IUnrestrictedPermission
{
// Internal state.
private UIPermissionWindow window;
private UIPermissionClipboard clipboard;
// Constructors.
public UIPermission(PermissionState state)
{
if(state == PermissionState.None)
{
window = UIPermissionWindow.NoWindows;
clipboard = UIPermissionClipboard.NoClipboard;
}
else if(state == PermissionState.Unrestricted)
{
window = UIPermissionWindow.AllWindows;
clipboard = UIPermissionClipboard.AllClipboard;
}
else
{
throw new ArgumentException(_("Arg_PermissionState"));
}
}
public UIPermission(UIPermissionWindow windowFlag)
{
if(windowFlag < UIPermissionWindow.NoWindows ||
windowFlag > UIPermissionWindow.AllWindows)
{
throw new ArgumentException(_("Arg_WindowFlag"));
}
window = windowFlag;
clipboard = UIPermissionClipboard.NoClipboard;
}
public UIPermission(UIPermissionClipboard clipboardFlag)
{
if(clipboardFlag < UIPermissionClipboard.NoClipboard ||
clipboardFlag > UIPermissionClipboard.AllClipboard)
{
throw new ArgumentException(_("Arg_ClipboardFlag"));
}
window = UIPermissionWindow.NoWindows;
clipboard = clipboardFlag;
}
public UIPermission(UIPermissionWindow windowFlag,
UIPermissionClipboard clipboardFlag)
{
if(windowFlag < UIPermissionWindow.NoWindows ||
windowFlag > UIPermissionWindow.AllWindows)
{
throw new ArgumentException(_("Arg_WindowFlag"));
}
if(clipboardFlag < UIPermissionClipboard.NoClipboard ||
clipboardFlag > UIPermissionClipboard.AllClipboard)
{
throw new ArgumentException(_("Arg_ClipboardFlag"));
}
window = windowFlag;
clipboard = clipboardFlag;
}
// Convert an XML value into a permissions value.
public override void FromXml(SecurityElement esd)
{
String value;
if(esd == null)
{
throw new ArgumentNullException("esd");
}
if(esd.Attribute("version") != "1")
{
throw new ArgumentException(_("Arg_PermissionVersion"));
}
value = esd.Attribute("Unrestricted");
if(value != null && Boolean.Parse(value))
{
window = UIPermissionWindow.NoWindows;
clipboard = UIPermissionClipboard.NoClipboard;
}
else
{
value = esd.Attribute("Window");
if(value != null)
{
window = (UIPermissionWindow)
Enum.Parse(typeof(UIPermissionWindow), value);
}
else
{
window = UIPermissionWindow.NoWindows;
}
value = esd.Attribute("Clipboard");
if(value != null)
{
clipboard = (UIPermissionClipboard)
Enum.Parse(typeof(UIPermissionClipboard), value);
}
else
{
clipboard = UIPermissionClipboard.NoClipboard;
}
}
}
// Convert this permissions object into an XML value.
public override SecurityElement ToXml()
{
SecurityElement element;
element = new SecurityElement("IPermission");
element.AddAttribute
("class",
SecurityElement.Escape(typeof(UIPermission).
AssemblyQualifiedName));
element.AddAttribute("version", "1");
if(IsUnrestricted())
{
element.AddAttribute("Unrestricted", "true");
}
else
{
element.AddAttribute("Window", window.ToString());
element.AddAttribute("Clipboard", clipboard.ToString());
}
return element;
}
// Implement the IPermission interface.
public override IPermission Copy()
{
return new UIPermission(window, clipboard);
}
public override IPermission Intersect(IPermission target)
{
// Handle the easy cases first.
if(target == null)
{
return target;
}
else if(!(target is UIPermission))
{
throw new ArgumentException(_("Arg_PermissionMismatch"));
}
else if(((UIPermission)target)
.IsUnrestricted())
{
return Copy();
}
else if(IsUnrestricted())
{
return target.Copy();
}
// Get the minimum flag values.
UIPermissionWindow w = ((UIPermission)target).window;
if(((int)w) > ((int)window))
{
w = window;
}
UIPermissionClipboard c = ((UIPermission)target).clipboard;
if(((int)c) > ((int)clipboard))
{
c = clipboard;
}
// Create a new object for the intersection.
if(w == UIPermissionWindow.NoWindows &&
c == UIPermissionClipboard.NoClipboard)
{
return null;
}
else
{
return new UIPermission(w, c);
}
}
public override bool IsSubsetOf(IPermission target)
{
if(target == null)
{
return (window == UIPermissionWindow.NoWindows &&
clipboard == UIPermissionClipboard.NoClipboard);
}
else if(!(target is UIPermission))
{
throw new ArgumentException(_("Arg_PermissionMismatch"));
}
else if(((UIPermission)target)
.IsUnrestricted())
{
return true;
}
else if(IsUnrestricted())
{
return false;
}
else if(((int)window) >
((int)(((UIPermission)target).window)))
{
return false;
}
else if(((int)clipboard) >
((int)(((UIPermission)target).clipboard)))
{
return false;
}
else
{
return true;
}
}
public override IPermission Union(IPermission target)
{
// Handle the easy cases first.
if(target == null)
{
return Copy();
}
else if(!(target is UIPermission))
{
throw new ArgumentException(_("Arg_PermissionMismatch"));
}
else if(IsUnrestricted() ||
((UIPermission)target).IsUnrestricted())
{
return new UIPermission(PermissionState.Unrestricted);
}
// Get the maximum flag values.
UIPermissionWindow w = ((UIPermission)target).window;
if(((int)w) < ((int)window))
{
w = window;
}
UIPermissionClipboard c = ((UIPermission)target).clipboard;
if(((int)c) < ((int)clipboard))
{
c = clipboard;
}
// Create a new object for the union.
if(w == UIPermissionWindow.NoWindows &&
c == UIPermissionClipboard.NoClipboard)
{
return null;
}
else
{
return new UIPermission(w, c);
}
}
// Determine if this object has unrestricted permissions.
public bool IsUnrestricted()
{
return (window == UIPermissionWindow.AllWindows &&
clipboard == UIPermissionClipboard.AllClipboard);
}
// Get or set the window flag.
public UIPermissionWindow Window
{
get
{
return window;
}
set
{
if(value < UIPermissionWindow.NoWindows ||
value > UIPermissionWindow.AllWindows)
{
throw new ArgumentException(_("Arg_WindowFlag"));
}
window = value;
}
}
// Get or set the clipboard flag.
public UIPermissionClipboard Clipboard
{
get
{
return clipboard;
}
set
{
if(value < UIPermissionClipboard.NoClipboard ||
value > UIPermissionClipboard.AllClipboard)
{
throw new ArgumentException(_("Arg_ClipboardFlag"));
}
clipboard = value;
}
}
}; // class UIPermission
#endif // CONFIG_PERMISSIONS && !ECMA_COMPAT
}; // namespace System.Security.Permissions
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Security.Principal
{
//
// Identifier authorities
//
internal enum IdentifierAuthority : long
{
NullAuthority = 0,
WorldAuthority = 1,
LocalAuthority = 2,
CreatorAuthority = 3,
NonUniqueAuthority = 4,
NTAuthority = 5,
SiteServerAuthority = 6,
InternetSiteAuthority = 7,
ExchangeAuthority = 8,
ResourceManagerAuthority = 9,
}
//
// SID name usage
//
internal enum SidNameUse
{
User = 1,
Group = 2,
Domain = 3,
Alias = 4,
WellKnownGroup = 5,
DeletedAccount = 6,
Invalid = 7,
Unknown = 8,
Computer = 9,
}
//
// Well-known SID types
//
public enum WellKnownSidType
{
NullSid = 0,
WorldSid = 1,
LocalSid = 2,
CreatorOwnerSid = 3,
CreatorGroupSid = 4,
CreatorOwnerServerSid = 5,
CreatorGroupServerSid = 6,
NTAuthoritySid = 7,
DialupSid = 8,
NetworkSid = 9,
BatchSid = 10,
InteractiveSid = 11,
ServiceSid = 12,
AnonymousSid = 13,
ProxySid = 14,
EnterpriseControllersSid = 15,
SelfSid = 16,
AuthenticatedUserSid = 17,
RestrictedCodeSid = 18,
TerminalServerSid = 19,
RemoteLogonIdSid = 20,
LogonIdsSid = 21,
LocalSystemSid = 22,
LocalServiceSid = 23,
NetworkServiceSid = 24,
BuiltinDomainSid = 25,
BuiltinAdministratorsSid = 26,
BuiltinUsersSid = 27,
BuiltinGuestsSid = 28,
BuiltinPowerUsersSid = 29,
BuiltinAccountOperatorsSid = 30,
BuiltinSystemOperatorsSid = 31,
BuiltinPrintOperatorsSid = 32,
BuiltinBackupOperatorsSid = 33,
BuiltinReplicatorSid = 34,
BuiltinPreWindows2000CompatibleAccessSid = 35,
BuiltinRemoteDesktopUsersSid = 36,
BuiltinNetworkConfigurationOperatorsSid = 37,
AccountAdministratorSid = 38,
AccountGuestSid = 39,
AccountKrbtgtSid = 40,
AccountDomainAdminsSid = 41,
AccountDomainUsersSid = 42,
AccountDomainGuestsSid = 43,
AccountComputersSid = 44,
AccountControllersSid = 45,
AccountCertAdminsSid = 46,
AccountSchemaAdminsSid = 47,
AccountEnterpriseAdminsSid = 48,
AccountPolicyAdminsSid = 49,
AccountRasAndIasServersSid = 50,
NtlmAuthenticationSid = 51,
DigestAuthenticationSid = 52,
SChannelAuthenticationSid = 53,
ThisOrganizationSid = 54,
OtherOrganizationSid = 55,
BuiltinIncomingForestTrustBuildersSid = 56,
BuiltinPerformanceMonitoringUsersSid = 57,
BuiltinPerformanceLoggingUsersSid = 58,
BuiltinAuthorizationAccessSid = 59,
WinBuiltinTerminalServerLicenseServersSid = 60,
MaxDefined = WinBuiltinTerminalServerLicenseServersSid,
}
//
// This class implements revision 1 SIDs
// NOTE: The SecurityIdentifier class is immutable and must remain this way
//
public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier>
{
#region Public Constants
//
// Identifier authority must be at most six bytes long
//
internal static readonly long MaxIdentifierAuthority = 0xFFFFFFFFFFFF;
//
// Maximum number of subauthorities in a SID
//
internal static readonly byte MaxSubAuthorities = 15;
//
// Minimum length of a binary representation of a SID
//
public static readonly int MinBinaryLength = 1 + 1 + 6; // Revision (1) + subauth count (1) + identifier authority (6)
//
// Maximum length of a binary representation of a SID
//
public static readonly int MaxBinaryLength = 1 + 1 + 6 + MaxSubAuthorities * 4; // 4 bytes for each subauth
#endregion
#region Private Members
//
// Immutable properties of a SID
//
private IdentifierAuthority _identifierAuthority;
private int[] _subAuthorities;
private byte[] _binaryForm;
private SecurityIdentifier _accountDomainSid;
private bool _accountDomainSidInitialized = false;
//
// Computed attributes of a SID
//
private string _sddlForm = null;
#endregion
#region Constructors
//
// Shared constructor logic
// NOTE: subauthorities are really unsigned integers, but due to CLS
// lack of support for unsigned integers the caller must perform
// the typecast
//
private void CreateFromParts(IdentifierAuthority identifierAuthority, int[] subAuthorities)
{
if (subAuthorities == null)
{
throw new ArgumentNullException("subAuthorities");
}
Contract.EndContractBlock();
//
// Check the number of subauthorities passed in
//
if (subAuthorities.Length > MaxSubAuthorities)
{
throw new ArgumentOutOfRangeException(
"subAuthorities.Length",
subAuthorities.Length,
SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities));
}
//
// Identifier authority is at most 6 bytes long
//
if (identifierAuthority < 0 ||
(long)identifierAuthority > MaxIdentifierAuthority)
{
throw new ArgumentOutOfRangeException(
"identifierAuthority",
identifierAuthority,
SR.IdentityReference_IdentifierAuthorityTooLarge);
}
//
// Create a local copy of the data passed in
//
_identifierAuthority = identifierAuthority;
_subAuthorities = new int[subAuthorities.Length];
subAuthorities.CopyTo(_subAuthorities, 0);
//
// Compute and store the binary form
//
// typedef struct _SID {
// UCHAR Revision;
// UCHAR SubAuthorityCount;
// SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
// ULONG SubAuthority[ANYSIZE_ARRAY]
// } SID, *PISID;
//
byte i;
_binaryForm = new byte[1 + 1 + 6 + 4 * this.SubAuthorityCount];
//
// First two bytes contain revision and subauthority count
//
_binaryForm[0] = Revision;
_binaryForm[1] = (byte)this.SubAuthorityCount;
//
// Identifier authority takes up 6 bytes
//
for (i = 0; i < 6; i++)
{
_binaryForm[2 + i] = (byte)((((ulong)_identifierAuthority) >> ((5 - i) * 8)) & 0xFF);
}
//
// Subauthorities go last, preserving big-endian representation
//
for (i = 0; i < this.SubAuthorityCount; i++)
{
byte shift;
for (shift = 0; shift < 4; shift += 1)
{
_binaryForm[8 + 4 * i + shift] = (byte)(((ulong)_subAuthorities[i]) >> (shift * 8));
}
}
}
private void CreateFromBinaryForm(byte[] binaryForm, int offset)
{
//
// Give us something to work with
//
if (binaryForm == null)
{
throw new ArgumentNullException("binaryForm");
}
//
// Negative offsets are not allowed
//
if (offset < 0)
{
throw new ArgumentOutOfRangeException(
"offset",
offset,
SR.ArgumentOutOfRange_NeedNonNegNum);
}
//
// At least a minimum-size SID should fit in the buffer
//
if (binaryForm.Length - offset < SecurityIdentifier.MinBinaryLength)
{
throw new ArgumentOutOfRangeException(
"binaryForm",
SR.ArgumentOutOfRange_ArrayTooSmall);
}
Contract.EndContractBlock();
IdentifierAuthority Authority;
int[] SubAuthorities;
//
// Extract the elements of a SID
//
if (binaryForm[offset] != Revision)
{
//
// Revision is incorrect
//
throw new ArgumentException(
SR.IdentityReference_InvalidSidRevision,
"binaryForm");
}
//
// Insist on the correct number of subauthorities
//
if (binaryForm[offset + 1] > MaxSubAuthorities)
{
throw new ArgumentException(
SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities),
"binaryForm");
}
//
// Make sure the buffer is big enough
//
int Length = 1 + 1 + 6 + 4 * binaryForm[offset + 1];
if (binaryForm.Length - offset < Length)
{
throw new ArgumentException(
SR.ArgumentOutOfRange_ArrayTooSmall,
"binaryForm");
}
Authority =
(IdentifierAuthority)(
(((long)binaryForm[offset + 2]) << 40) +
(((long)binaryForm[offset + 3]) << 32) +
(((long)binaryForm[offset + 4]) << 24) +
(((long)binaryForm[offset + 5]) << 16) +
(((long)binaryForm[offset + 6]) << 8) +
(((long)binaryForm[offset + 7])));
SubAuthorities = new int[binaryForm[offset + 1]];
//
// Subauthorities are represented in big-endian format
//
for (byte i = 0; i < binaryForm[offset + 1]; i++)
{
SubAuthorities[i] =
(int)(
(((uint)binaryForm[offset + 8 + 4 * i + 0]) << 0) +
(((uint)binaryForm[offset + 8 + 4 * i + 1]) << 8) +
(((uint)binaryForm[offset + 8 + 4 * i + 2]) << 16) +
(((uint)binaryForm[offset + 8 + 4 * i + 3]) << 24));
}
CreateFromParts(Authority, SubAuthorities);
return;
}
//
// Constructs a SecurityIdentifier object from its string representation
// Returns 'null' if string passed in is not a valid SID
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier(string sddlForm)
{
byte[] resultSid;
//
// Give us something to work with
//
if (sddlForm == null)
{
throw new ArgumentNullException("sddlForm");
}
Contract.EndContractBlock();
//
// Call into the underlying O/S conversion routine
//
int Error = Win32.CreateSidFromString(sddlForm, out resultSid);
if (Error == Interop.mincore.Errors.ERROR_INVALID_SID)
{
throw new ArgumentException(SR.Argument_InvalidValue, "sddlForm");
}
else if (Error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (Error != Interop.mincore.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateSidFromString returned unrecognized error {0}", Error));
throw new Win32Exception(Error);
}
CreateFromBinaryForm(resultSid, 0);
}
//
// Constructs a SecurityIdentifier object from its binary representation
//
public SecurityIdentifier(byte[] binaryForm, int offset)
{
CreateFromBinaryForm(binaryForm, offset);
}
//
// Constructs a SecurityIdentifier object from an IntPtr
//
public SecurityIdentifier(IntPtr binaryForm)
: this(binaryForm, true)
{
}
internal SecurityIdentifier(IntPtr binaryForm, bool noDemand)
: this(Win32.ConvertIntPtrSidToByteArraySid(binaryForm), 0)
{
}
//
// Constructs a well-known SID
// The 'domainSid' parameter is optional and only used
// by the well-known types that require it
// NOTE: although there is a P/Invoke call involved in the implementation of this constructor,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
{
//
// sidType must not be equal to LogonIdsSid
//
if (sidType == WellKnownSidType.LogonIdsSid)
{
throw new ArgumentException(SR.IdentityReference_CannotCreateLogonIdsSid, "sidType");
}
Contract.EndContractBlock();
byte[] resultSid;
int Error;
//
// sidType should not exceed the max defined value
//
if ((sidType < WellKnownSidType.NullSid) || (sidType > WellKnownSidType.MaxDefined))
{
throw new ArgumentException(SR.Argument_InvalidValue, "sidType");
}
//
// for sidType between 38 to 50, the domainSid parameter must be specified
//
if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid))
{
if (domainSid == null)
{
throw new ArgumentNullException("domainSid", SR.Format(SR.IdentityReference_DomainSidRequired, sidType));
}
//
// verify that the domain sid is a valid windows domain sid
// to do that we call GetAccountDomainSid and the return value should be the same as the domainSid
//
SecurityIdentifier resultDomainSid;
int ErrorCode;
ErrorCode = Win32.GetWindowsAccountDomainSid(domainSid, out resultDomainSid);
if (ErrorCode == Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER)
{
throw new OutOfMemoryException();
}
else if (ErrorCode == Interop.mincore.Errors.ERROR_NON_ACCOUNT_SID)
{
// this means that the domain sid is not valid
throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, "domainSid");
}
else if (ErrorCode != Interop.mincore.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", ErrorCode));
throw new Win32Exception(ErrorCode);
}
//
// if domainSid is passed in as S-1-5-21-3-4-5-6, the above api will return S-1-5-21-3-4-5 as the domainSid
// Since these do not match S-1-5-21-3-4-5-6 is not a valid domainSid (wrong number of subauthorities)
//
if (resultDomainSid != domainSid)
{
throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, "domainSid");
}
}
Error = Win32.CreateWellKnownSid(sidType, domainSid, out resultSid);
if (Error == Interop.mincore.Errors.ERROR_INVALID_PARAMETER)
{
throw new ArgumentException(new Win32Exception(Error).Message, "sidType/domainSid");
}
else if (Error != Interop.mincore.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateWellKnownSid returned unrecognized error {0}", Error));
throw new Win32Exception(Error);
}
CreateFromBinaryForm(resultSid, 0);
}
internal SecurityIdentifier(SecurityIdentifier domainSid, uint rid)
{
int i;
int[] SubAuthorities = new int[domainSid.SubAuthorityCount + 1];
for (i = 0; i < domainSid.SubAuthorityCount; i++)
{
SubAuthorities[i] = domainSid.GetSubAuthority(i);
}
SubAuthorities[i] = (int)rid;
CreateFromParts(domainSid.IdentifierAuthority, SubAuthorities);
}
internal SecurityIdentifier(IdentifierAuthority identifierAuthority, int[] subAuthorities)
{
CreateFromParts(identifierAuthority, subAuthorities);
}
#endregion
#region Static Properties
//
// Revision is always '1'
//
internal static byte Revision
{
get
{
return 1;
}
}
#endregion
#region Non-static Properties
//
// This is for internal consumption only, hence it is marked 'internal'
// Making this call public would require a deep copy of the data to
// prevent the caller from messing with the internal representation.
//
internal byte[] BinaryForm
{
get
{
return _binaryForm;
}
}
internal IdentifierAuthority IdentifierAuthority
{
get
{
return _identifierAuthority;
}
}
internal int SubAuthorityCount
{
get
{
return _subAuthorities.Length;
}
}
public int BinaryLength
{
get
{
return _binaryForm.Length;
}
}
//
// Returns the domain portion of a SID or null if the specified
// SID is not an account SID
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier AccountDomainSid
{
get
{
if (!_accountDomainSidInitialized)
{
_accountDomainSid = GetAccountDomainSid();
_accountDomainSidInitialized = true;
}
return _accountDomainSid;
}
}
#endregion
#region Inherited properties and methods
public override bool Equals(object o)
{
return (this == o as SecurityIdentifier); // invokes operator==
}
public bool Equals(SecurityIdentifier sid)
{
return (this == sid); // invokes operator==
}
public override int GetHashCode()
{
int hashCode = ((long)this.IdentifierAuthority).GetHashCode();
for (int i = 0; i < SubAuthorityCount; i++)
{
hashCode ^= this.GetSubAuthority(i);
}
return hashCode;
}
public override string ToString()
{
if (_sddlForm == null)
{
StringBuilder result = new StringBuilder();
//
// Typecasting of _IdentifierAuthority to a long below is important, since
// otherwise you would see this: "S-1-NTAuthority-32-544"
//
result.AppendFormat("S-1-{0}", (long)_identifierAuthority);
for (int i = 0; i < SubAuthorityCount; i++)
{
result.AppendFormat("-{0}", (uint)(_subAuthorities[i]));
}
_sddlForm = result.ToString();
}
return _sddlForm;
}
public override string Value
{
get
{
return ToString().ToUpperInvariant();
}
}
internal static bool IsValidTargetTypeStatic(Type targetType)
{
if (targetType == typeof(NTAccount))
{
return true;
}
else if (targetType == typeof(SecurityIdentifier))
{
return true;
}
else
{
return false;
}
}
public override bool IsValidTargetType(Type targetType)
{
return IsValidTargetTypeStatic(targetType);
}
internal SecurityIdentifier GetAccountDomainSid()
{
SecurityIdentifier ResultSid;
int Error;
Error = Win32.GetWindowsAccountDomainSid(this, out ResultSid);
if (Error == Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER)
{
throw new OutOfMemoryException();
}
else if (Error == Interop.mincore.Errors.ERROR_NON_ACCOUNT_SID)
{
ResultSid = null;
}
else if (Error != Interop.mincore.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", Error));
throw new Win32Exception(Error);
}
return ResultSid;
}
public bool IsAccountSid()
{
if (!_accountDomainSidInitialized)
{
_accountDomainSid = GetAccountDomainSid();
_accountDomainSidInitialized = true;
}
if (_accountDomainSid == null)
{
return false;
}
return true;
}
public override IdentityReference Translate(Type targetType)
{
if (targetType == null)
{
throw new ArgumentNullException("targetType");
}
Contract.EndContractBlock();
if (targetType == typeof(SecurityIdentifier))
{
return this; // assumes SecurityIdentifier objects are immutable
}
else if (targetType == typeof(NTAccount))
{
IdentityReferenceCollection irSource = new IdentityReferenceCollection(1);
irSource.Add(this);
IdentityReferenceCollection irTarget;
irTarget = SecurityIdentifier.Translate(irSource, targetType, true);
return irTarget[0];
}
else
{
throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, "targetType");
}
}
#endregion
#region Operators
public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right)
{
object l = left;
object r = right;
if (l == r)
{
return true;
}
else if (l == null || r == null)
{
return false;
}
else
{
return (left.CompareTo(right) == 0);
}
}
public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right)
{
return !(left == right);
}
#endregion
#region IComparable implementation
public int CompareTo(SecurityIdentifier sid)
{
if (sid == null)
{
throw new ArgumentNullException("sid");
}
Contract.EndContractBlock();
if (this.IdentifierAuthority < sid.IdentifierAuthority)
{
return -1;
}
if (this.IdentifierAuthority > sid.IdentifierAuthority)
{
return 1;
}
if (this.SubAuthorityCount < sid.SubAuthorityCount)
{
return -1;
}
if (this.SubAuthorityCount > sid.SubAuthorityCount)
{
return 1;
}
for (int i = 0; i < this.SubAuthorityCount; i++)
{
int diff = this.GetSubAuthority(i) - sid.GetSubAuthority(i);
if (diff != 0)
{
return diff;
}
}
return 0;
}
#endregion
#region Public Methods
internal int GetSubAuthority(int index)
{
return _subAuthorities[index];
}
//
// Determines whether this SID is a well-known SID of the specified type
//
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public bool IsWellKnown(WellKnownSidType type)
{
return Win32.IsWellKnownSid(this, type);
}
public void GetBinaryForm(byte[] binaryForm, int offset)
{
_binaryForm.CopyTo(binaryForm, offset);
}
//
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public bool IsEqualDomainSid(SecurityIdentifier sid)
{
return Win32.IsEqualDomainSid(this, sid);
}
private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed)
{
if (sourceSids == null)
{
throw new ArgumentNullException("sourceSids");
}
if (sourceSids.Count == 0)
{
throw new ArgumentException(SR.Arg_EmptyCollection, "sourceSids");
}
Contract.EndContractBlock();
IntPtr[] SidArrayPtr = new IntPtr[sourceSids.Count];
GCHandle[] HandleArray = new GCHandle[sourceSids.Count];
SafeLsaPolicyHandle LsaHandle = SafeLsaPolicyHandle.InvalidHandle;
SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle;
SafeLsaMemoryHandle NamesPtr = SafeLsaMemoryHandle.InvalidHandle;
try
{
//
// Pin all elements in the array of SIDs
//
int currentSid = 0;
foreach (IdentityReference id in sourceSids)
{
SecurityIdentifier sid = id as SecurityIdentifier;
if (sid == null)
{
throw new ArgumentException(SR.Argument_ImproperType, "sourceSids");
}
HandleArray[currentSid] = GCHandle.Alloc(sid.BinaryForm, GCHandleType.Pinned);
SidArrayPtr[currentSid] = HandleArray[currentSid].AddrOfPinnedObject();
currentSid++;
}
//
// Open LSA policy (for lookup requires it)
//
LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
//
// Perform the actual lookup
//
someFailed = false;
uint ReturnCode;
ReturnCode = Interop.mincore.LsaLookupSids(LsaHandle, sourceSids.Count, SidArrayPtr, ref ReferencedDomainsPtr, ref NamesPtr);
//
// Make a decision regarding whether it makes sense to proceed
// based on the return code and the value of the forceSuccess argument
//
if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY ||
ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES)
{
throw new OutOfMemoryException();
}
else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED ||
ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
{
someFailed = true;
}
else if (ReturnCode != 0)
{
int win32ErrorCode = Interop.mincore.RtlNtStatusToDosError(unchecked((int)ReturnCode));
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupSids returned {0}", win32ErrorCode));
throw new Win32Exception(win32ErrorCode);
}
NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_NAME>());
Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
//
// Interpret the results and generate NTAccount objects
//
IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceSids.Count);
if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
{
//
// Interpret the results and generate NT Account objects
//
Interop.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0);
string[] ReferencedDomains = new string[rdl.Entries];
for (int i = 0; i < rdl.Entries; i++)
{
Interop.LSA_TRUST_INFORMATION ti = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure<Interop.LSA_TRUST_INFORMATION>(new IntPtr((long)rdl.Domains + i * Marshal.SizeOf<Interop.LSA_TRUST_INFORMATION>()));
ReferencedDomains[i] = Marshal.PtrToStringUni(ti.Name.Buffer, ti.Name.Length / sizeof(char));
}
Interop.LSA_TRANSLATED_NAME[] translatedNames = new Interop.LSA_TRANSLATED_NAME[sourceSids.Count];
NamesPtr.ReadArray(0, translatedNames, 0, translatedNames.Length);
for (int i = 0; i < sourceSids.Count; i++)
{
Interop.LSA_TRANSLATED_NAME Ltn = translatedNames[i];
switch ((SidNameUse)Ltn.Use)
{
case SidNameUse.User:
case SidNameUse.Group:
case SidNameUse.Alias:
case SidNameUse.Computer:
case SidNameUse.WellKnownGroup:
string account = Marshal.PtrToStringUni(Ltn.Name.Buffer, Ltn.Name.Length / sizeof(char)); ;
string domain = ReferencedDomains[Ltn.DomainIndex];
Result.Add(new NTAccount(domain, account));
break;
default:
someFailed = true;
Result.Add(sourceSids[i]);
break;
}
}
}
else
{
for (int i = 0; i < sourceSids.Count; i++)
{
Result.Add(sourceSids[i]);
}
}
return Result;
}
finally
{
for (int i = 0; i < sourceSids.Count; i++)
{
if (HandleArray[i].IsAllocated)
{
HandleArray[i].Free();
}
}
LsaHandle.Dispose();
ReferencedDomainsPtr.Dispose();
NamesPtr.Dispose();
}
}
internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, bool forceSuccess)
{
bool SomeFailed = false;
IdentityReferenceCollection Result;
Result = Translate(sourceSids, targetType, out SomeFailed);
if (forceSuccess && SomeFailed)
{
IdentityReferenceCollection UnmappedIdentities = new IdentityReferenceCollection();
foreach (IdentityReference id in Result)
{
if (id.GetType() != targetType)
{
UnmappedIdentities.Add(id);
}
}
throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, UnmappedIdentities);
}
return Result;
}
internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, out bool someFailed)
{
if (sourceSids == null)
{
throw new ArgumentNullException("sourceSids");
}
Contract.EndContractBlock();
if (targetType == typeof(NTAccount))
{
return TranslateToNTAccounts(sourceSids, out someFailed);
}
throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, "targetType");
}
#endregion
}
}
| |
using System.CodeDom;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace System.Workflow.Activities.Rules
{
public static class RuleDecompiler
{
#region Decompile literals
public static void DecompileObjectLiteral(StringBuilder decompilation, object primitiveValue)
{
if (primitiveValue == null)
{
decompilation.Append("null");
}
else
{
Type primitiveType = primitiveValue.GetType();
if (primitiveType == typeof(string))
DecompileStringLiteral(decompilation, (string)primitiveValue);
else if (primitiveType == typeof(char))
DecompileCharacterLiteral(decompilation, (char)primitiveValue);
else if (primitiveType == typeof(long))
DecompileSuffixedIntegerLiteral(decompilation, primitiveValue, "L");
else if (primitiveType == typeof(uint))
DecompileSuffixedIntegerLiteral(decompilation, primitiveValue, "U");
else if (primitiveType == typeof(ulong))
DecompileSuffixedIntegerLiteral(decompilation, primitiveValue, "UL");
else if (primitiveType == typeof(float))
DecompileFloatingPointLiteral(decompilation, primitiveValue, 'f');
else if (primitiveType == typeof(double))
DecompileFloatingPointLiteral(decompilation, primitiveValue, 'd');
else if (primitiveType == typeof(decimal))
DecompileFloatingPointLiteral(decompilation, primitiveValue, 'm');
else
decompilation.Append(primitiveValue.ToString());
}
}
private static void DecompileFloatingPointLiteral(StringBuilder decompilation, object value, char suffix)
{
// Make sure decimal point isn't converted to a comma in European locales.
string svalue = Convert.ToString(value, CultureInfo.InvariantCulture);
decompilation.Append(svalue);
if (suffix == 'd')
{
// Don't append 'd' suffixes, they're ugly. Only if the string-ified value contains
// no decimal and no exponent do we need to append a ".0" to make it a double (as
// opposed to an integer).
bool hasDecimal = svalue.IndexOf('.') >= 0;
bool hasExponent = svalue.IndexOfAny(new char[] { 'e', 'E' }) >= 0;
if (!hasDecimal && !hasExponent)
decompilation.Append(".0");
}
else
{
decompilation.Append(suffix);
}
}
private static void DecompileSuffixedIntegerLiteral(StringBuilder decompilation, object value, string suffix)
{
decompilation.Append(value.ToString());
decompilation.Append(suffix);
}
private static void DecompileStringLiteral(StringBuilder decompilation, string strValue)
{
decompilation.Append("\"");
for (int i = 0; i < strValue.Length; ++i)
{
char c = strValue[i];
// is this character a surrogate pair?
if ((char.IsHighSurrogate(c)) && (i + 1 < strValue.Length) && (char.IsLowSurrogate(strValue[i + 1])))
{
// yes, so leave the two characters unchanged
decompilation.Append(c);
++i;
decompilation.Append(strValue[i]);
}
else
AppendCharacter(decompilation, c, '"');
}
decompilation.Append("\"");
}
private static void DecompileCharacterLiteral(StringBuilder decompilation, char charValue)
{
decompilation.Append("'");
AppendCharacter(decompilation, charValue, '\'');
decompilation.Append("'");
}
private static void AppendCharacter(StringBuilder decompilation, char charValue, char quoteCharacter)
{
if (charValue == quoteCharacter)
{
decompilation.Append("\\");
decompilation.Append(quoteCharacter);
}
else if (charValue == '\\')
{
decompilation.Append("\\\\");
}
else if ((charValue >= ' ' && charValue < '\u007f') || char.IsLetterOrDigit(charValue) || char.IsPunctuation(charValue))
{
decompilation.Append(charValue);
}
else
{
string escapeSequence = null;
switch (charValue)
{
case '\0':
escapeSequence = "\\0";
break;
case '\n':
escapeSequence = "\\n";
break;
case '\r':
escapeSequence = "\\r";
break;
case '\b':
escapeSequence = "\\b";
break;
case '\a':
escapeSequence = "\\a";
break;
case '\t':
escapeSequence = "\\t";
break;
case '\f':
escapeSequence = "\\f";
break;
case '\v':
escapeSequence = "\\v";
break;
}
if (escapeSequence != null)
{
decompilation.Append(escapeSequence);
}
else
{
decompilation.Append("\\u");
UInt16 cv = (UInt16)charValue;
for (int i = 12; i >= 0; i -= 4)
{
int mask = 0xF << i;
byte c = (byte)((cv & mask) >> i);
decompilation.Append("0123456789ABCDEF"[c]);
}
}
}
}
#endregion
#region Type decompilation
public static string DecompileType(Type type)
{
if (type == null)
return string.Empty;
StringBuilder sb = new StringBuilder();
DecompileType_Helper(sb, type);
return sb.ToString();
}
private static void DecompileType_Helper(StringBuilder decompilation, Type type)
{
int i;
if (type.HasElementType)
{
DecompileType_Helper(decompilation, type.GetElementType());
if (type.IsArray)
{
decompilation.Append("[");
decompilation.Append(',', type.GetArrayRank() - 1);
decompilation.Append("]");
}
else if (type.IsByRef)
{
decompilation.Append('&');
}
else if (type.IsPointer)
{
decompilation.Append('*');
}
}
else
{
string typeName = type.FullName;
if (typeName == null) // Full name may be null for an unbound generic.
typeName = type.Name;
typeName = UnmangleTypeName(typeName);
decompilation.Append(typeName);
if (type.IsGenericType)
{
decompilation.Append("<");
Type[] typeArgs = type.GetGenericArguments();
DecompileType_Helper(decompilation, typeArgs[0]); // decompile the first type arg
for (i = 1; i < typeArgs.Length; ++i)
{
decompilation.Append(", ");
DecompileType_Helper(decompilation, typeArgs[i]);
}
decompilation.Append(">");
}
}
}
internal static void DecompileType(StringBuilder decompilation, CodeTypeReference typeRef)
{
// Remove any back-tick decorations on generic types, if present.
string baseType = UnmangleTypeName(typeRef.BaseType);
decompilation.Append(baseType);
if (typeRef.TypeArguments != null && typeRef.TypeArguments.Count > 0)
{
decompilation.Append("<");
bool first = true;
foreach (CodeTypeReference argTypeRef in typeRef.TypeArguments)
{
if (!first)
decompilation.Append(", ");
first = false;
DecompileType(decompilation, argTypeRef);
}
decompilation.Append(">");
}
if (typeRef.ArrayRank > 0)
{
do
{
decompilation.Append("[");
for (int i = 1; i < typeRef.ArrayRank; ++i)
decompilation.Append(",");
decompilation.Append("]");
typeRef = typeRef.ArrayElementType;
} while (typeRef.ArrayRank > 0);
}
}
private static Dictionary<string, string> knownTypeMap = InitializeKnownTypeMap();
private static Dictionary<string, string> InitializeKnownTypeMap()
{
Dictionary<string, string> map = new Dictionary<string, string>
{
{ "System.Char", "char" },
{ "System.Byte", "byte" },
{ "System.SByte", "sbyte" },
{ "System.Int16", "short" },
{ "System.UInt16", "ushort" },
{ "System.Int32", "int" },
{ "System.UInt32", "uint" },
{ "System.Int64", "long" },
{ "System.UInt64", "ulong" },
{ "System.Single", "float" },
{ "System.Double", "double" },
{ "System.Decimal", "decimal" },
{ "System.Boolean", "bool" },
{ "System.String", "string" },
{ "System.Object", "object" },
{ "System.Void", "void" }
};
return map;
}
private static string TryReplaceKnownTypes(string typeName)
{
if (!knownTypeMap.TryGetValue(typeName, out string newTypeName))
newTypeName = typeName;
return newTypeName;
}
private static string UnmangleTypeName(string typeName)
{
int tickIndex = typeName.IndexOf('`');
if (tickIndex > 0)
typeName = typeName.Substring(0, tickIndex);
// Replace the '+' for a nested type with a '.'
typeName = typeName.Replace('+', '.');
typeName = TryReplaceKnownTypes(typeName);
return typeName;
}
#endregion
#region Method decompilation
internal static string DecompileMethod(MethodInfo method)
{
if (method == null)
return string.Empty;
StringBuilder sb = new StringBuilder();
DecompileType_Helper(sb, method.DeclaringType);
sb.Append('.');
if (knownOperatorMap.TryGetValue(method.Name, out string operatorName))
sb.Append(operatorName);
else
sb.Append(method.Name);
sb.Append('(');
ParameterInfo[] parms = method.GetParameters();
for (int i = 0; i < parms.Length; ++i)
{
DecompileType_Helper(sb, parms[i].ParameterType);
if (i != parms.Length - 1)
sb.Append(", ");
}
sb.Append(')');
return sb.ToString();
}
private static Dictionary<string, string> knownOperatorMap = InitializeKnownOperatorMap();
private static Dictionary<string, string> InitializeKnownOperatorMap()
{
Dictionary<string, string> map = new Dictionary<string, string>(27)
{
// unary operators
{ "op_UnaryPlus", "operator +" },
{ "op_UnaryNegation", "operator -" },
{ "op_OnesComplement", "operator ~" },
{ "op_LogicalNot", "operator !" },
{ "op_Increment", "operator ++" },
{ "op_Decrement", "operator --" },
{ "op_True", "operator true" },
{ "op_False", "operator false" },
{ "op_Implicit", "implicit operator" },
{ "op_Explicit", "explicit operator" },
// binary operators
{ "op_Equality", "operator ==" },
{ "op_Inequality", "operator !=" },
{ "op_GreaterThan", "operator >" },
{ "op_GreaterThanOrEqual", "operator >=" },
{ "op_LessThan", "operator <" },
{ "op_LessThanOrEqual", "operator <=" },
{ "op_Addition", "operator +" },
{ "op_Subtraction", "operator -" },
{ "op_Multiply", "operator *" },
{ "op_Division", "operator /" },
{ "op_IntegerDivision", "operator \\" },
{ "op_Modulus", "operator %" },
{ "op_LeftShift", "operator <<" },
{ "op_RightShift", "operator >>" },
{ "op_BitwiseAnd", "operator &" },
{ "op_BitwiseOr", "operator |" },
{ "op_ExclusiveOr", "operator ^" }
};
return map;
}
#endregion
#region Operator Precedence
// These operations are sorted in order of precedence, lowest-to-highest
private enum Operation
{
RootExpression,
LogicalOr, // ||
LogicalAnd, // &&
BitwiseOr, // |
BitwiseAnd, // &
Equality, // == !=
Comparitive, // < <= > >=
Additive, // + -
Multiplicative, // * / %
Unary, // - ! (cast)
Postfix, // field/property ref and method call
NoParentheses // Highest
}
private delegate Operation ComputePrecedence(CodeExpression expresssion);
private static Dictionary<Type, ComputePrecedence> precedenceMap = InitializePrecedenceMap();
private static Dictionary<Type, ComputePrecedence> InitializePrecedenceMap()
{
Dictionary<Type, ComputePrecedence> map = new Dictionary<Type, ComputePrecedence>(7)
{
{ typeof(CodeBinaryOperatorExpression), GetBinaryPrecedence },
{ typeof(CodeCastExpression), GetCastPrecedence },
{ typeof(CodeFieldReferenceExpression), GetPostfixPrecedence },
{ typeof(CodePropertyReferenceExpression), GetPostfixPrecedence },
{ typeof(CodeMethodInvokeExpression), GetPostfixPrecedence },
{ typeof(CodeObjectCreateExpression), GetPostfixPrecedence },
{ typeof(CodeArrayCreateExpression), GetPostfixPrecedence }
};
return map;
}
private static Operation GetPostfixPrecedence(CodeExpression expression)
{
return Operation.Postfix;
}
private static Operation GetCastPrecedence(CodeExpression expression)
{
return Operation.Unary;
}
private static Operation GetBinaryPrecedence(CodeExpression expression)
{
CodeBinaryOperatorExpression binaryExpr = (CodeBinaryOperatorExpression)expression;
Operation operation = Operation.NoParentheses;
switch (binaryExpr.Operator)
{
case CodeBinaryOperatorType.Multiply:
case CodeBinaryOperatorType.Divide:
case CodeBinaryOperatorType.Modulus:
operation = Operation.Multiplicative;
break;
case CodeBinaryOperatorType.Subtract:
case CodeBinaryOperatorType.Add:
operation = Operation.Additive;
break;
case CodeBinaryOperatorType.LessThan:
case CodeBinaryOperatorType.LessThanOrEqual:
case CodeBinaryOperatorType.GreaterThan:
case CodeBinaryOperatorType.GreaterThanOrEqual:
operation = Operation.Comparitive;
break;
case CodeBinaryOperatorType.IdentityEquality:
case CodeBinaryOperatorType.ValueEquality:
case CodeBinaryOperatorType.IdentityInequality:
operation = Operation.Equality;
break;
case CodeBinaryOperatorType.BitwiseAnd:
operation = Operation.BitwiseAnd;
break;
case CodeBinaryOperatorType.BitwiseOr:
operation = Operation.BitwiseOr;
break;
case CodeBinaryOperatorType.BooleanAnd:
operation = Operation.LogicalAnd;
break;
case CodeBinaryOperatorType.BooleanOr:
operation = Operation.LogicalOr;
break;
default:
string message = string.Format(CultureInfo.CurrentCulture, Messages.BinaryOpNotSupported, binaryExpr.Operator.ToString());
NotSupportedException exception = new NotSupportedException(message);
exception.Data[RuleUserDataKeys.ErrorObject] = binaryExpr;
throw exception;
}
return operation;
}
private static Operation GetPrecedence(CodeExpression expression)
{
// Assume the operation needs no parentheses.
Operation operation = Operation.NoParentheses;
if (precedenceMap.TryGetValue(expression.GetType(), out ComputePrecedence computePrecedence))
operation = computePrecedence(expression);
return operation;
}
internal static bool MustParenthesize(CodeExpression childExpr, CodeExpression parentExpr)
{
// No parent... we're at the root, so no need to parenthesize the root.
if (parentExpr == null)
return false;
Operation childOperation = GetPrecedence(childExpr);
Operation parentOperation = GetPrecedence(parentExpr);
if (parentOperation == childOperation)
{
if (parentExpr is CodeBinaryOperatorExpression parentBinary)
{
if (childExpr == parentBinary.Right)
{
// Something like 2 - (3 - 4) needs parentheses.
return true;
}
else
{
// Something like (2 - 3) - 4 doesn't need parentheses.
return false;
}
}
else
{
return false;
}
}
else if (parentOperation > childOperation)
{
return true;
}
else
{
return false;
}
}
#endregion
}
}
| |
#if ORIGIN_SHIFT
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using MessagePack;
using Microsoft.Xna.Framework;
public partial class Entity
{
public static void KeepOriginForPosition(Vector2 position)
{
EntityChunkRegionSystem.KeepOriginForPosition(position); //TODO cache and run outside behavior update loop
}
public static void DebugDrawEntityChunks()
{
EntityChunkRegionSystem.DebugDrawEntityChunks();
}
public static Action<Vector2> OnOriginShift;
private static class EntityChunkRegionSystem
{
class Chunk
{
public Chunk(int chunkIndexInRegion, int absRegionX)
{
this.chunkIndexInRegion = chunkIndexInRegion;
this.absRegionX = absRegionX;
isLoaded = false;
}
public Vector2 GetWorldCenter(int relRegionX)
{
return new Vector2(
RelativeRegionAndChunkIndexToWorld(relRegionX, chunkIndexInRegion) + CHUNK_SIZE/2f
,0
);
}
private readonly int chunkIndexInRegion;
private string Id => $"{absRegionX}_{chunkIndexInRegion}";
private bool isLoaded;
public int absRegionX { get; private set; }
public List<Entity> entities { get; } = new List<Entity>();
public void UnloadChunk(int relRegionX)
{
List<entityData> listToStoreEntityDatas = new List<entityData>();
while (entities.Count>0)
{
Entity e = entities[entities.Count-1];
if (e.persistent)
listToStoreEntityDatas.Add(e.GetCereal(
new Vector2(RelativeRegionAndChunkIndexToWorld(relRegionX, chunkIndexInRegion), 0)));
if (e.shifts)
e.Dispose();
else
entities.Remove(e); //if entity doesn't shift, parent is responsible for disposing
}
//entities.Clear();
//saving data
if (listToStoreEntityDatas.Count > 0)
{
byte[] chunkSerialData = MessagePackSerializer.Serialize(listToStoreEntityDatas);
savedChunks[Id] = chunkSerialData;
// File.WriteAllBytes(DATADIR + Id, chunkSerialData);
//
//// #if DEBUG
// string dbgText = $"DEBUG INFORMATION. Entity count: {listToStoreEntityDatas.Count}, specifics:";
// //File.WriteAllText(DATADIR + Id + "_debug", MessagePackSerializer.ToJson(chunkSerialData));
// foreach (entityData entityData in listToStoreEntityDatas)
// {
// dbgText = string.Concat(dbgText, $"\npos: {entityData.position.ToVector2()}, rot: {entityData.rotation}");
// foreach (ComponentData data in entityData.components)
// {
// dbgText = string.Concat(dbgText, $"\n + component: {Enum.GetName(typeof(ComponentTypes), data.typeId)}, data: {MessagePackSerializer.ToJson(data.serialData)}");
// }
// }
// File.WriteAllText(DATADIR + Id + "_debug", dbgText);
// #endif
}
}
public void MarkAsNew()
{
isLoaded = false;
}
public void SetRegionX(int absRegionX)
{
this.absRegionX = absRegionX;
}
public bool TryLoadChunk(int relRegionX)
{
if (isLoaded) return false;
List<entityData> existingData = null;
if (savedChunks.ContainsKey(Id))
{
existingData = MessagePackSerializer.Deserialize<List<entityData>>(savedChunks[Id]);
DebugHelper.AddDebugText("LOADED",
new Vector2(RelativeRegionAndChunkIndexToWorld(relRegionX,chunkIndexInRegion),-1),
Color.White, 30);
}
// if (File.Exists(DATADIR + Id))
// {
// Debug.WriteLine("data file exists, loading...");
// existingData = MessagePackSerializer.Deserialize<List<entityData>>(File.ReadAllBytes(DATADIR+Id));
// }
if (existingData != null)
{
foreach (entityData data in existingData)
new Entity(data, new Vector2(RelativeRegionAndChunkIndexToWorld(relRegionX, chunkIndexInRegion), 0));
}
else
{
Debug.WriteLine($"there's no existing data for chunk {Id}, calling generation");
for (int i = 0; i < CHUNK_SIZE; i++)
{
// float worldChunkStartPos = RelativeRegionAndChunkIndexToWorld(relRegionX,chunkIndexInRegion);
//
// DebugHelper.AddDebugText("GEN",
// new Vector2(worldChunkStartPos,-1),
// Color.Yellow, 30);
//
// var e = new Entity(new Vector2(worldChunkStartPos + i, 4+i));
// var b = new DynamicBody(e, true);
//
// new Rotator(e, (r.NextDouble() > 0.9) ? 1 : (r.NextDouble() > 0.8) ? -1 : 0);
//
// b.CreateCollider(new rectangleColliderData(Vector2.One.ToVec2F()));
//
// //b.CreateCollider(new circleColliderData(0.3f, 1, Vector2.One.ToVec2F()));
//
// var ce = new Entity(new Vector2(worldChunkStartPos + i, 4+i+1.5f));
// var cb = new StaticBody(ce);
//// cb.CreateCollider(new circleColliderData(0.3f));
// cb.CreateCollider(new rectangleColliderData(Vector2.One.ToVec2F()));
// new ICANHAZNAME(ce, $"{worldChunkStartPos}_{i}");
//
//
// var cont = new EntityContainer(e);
// cont.AddChild(ce);
// var ce2 = new Entity(new Vector2(worldChunkStartPos + i, 4+i+3f));
// var cb2 = new StaticBody(ce2);
// cb2.CreateCollider(new rectangleColliderData(Vector2.One.ToVec2F()));
//
// var cont2 = new EntityContainer(ce);
// cont2.AddChild(ce2);
// e.Rotation -= r.NextDouble().ToFloat()/3f;
}
}
isLoaded = true;
return true;
}
static Random r = new Random(42);
public override string ToString(){return Id;}
}
private const int CHUNK_LOG_SIZE = 6;//3;//TODO
private const int CHUNK_SIZE = 1 << CHUNK_LOG_SIZE;
private const int REGION_LOG_SIZE_IN_CHUNKS = 1;
private const int REGION_SIZE_IN_CHUNKS = 1 << REGION_LOG_SIZE_IN_CHUNKS;
private const int REGION_SIZE_IN_METERS = REGION_SIZE_IN_CHUNKS * CHUNK_SIZE;
private static int currentOriginInRegions = 0;
private static Chunk[] chunks_ = new Chunk[REGION_SIZE_IN_CHUNKS*4];
//TODO remove this dbg shit
private static Dictionary<string, byte[]> savedChunks = new Dictionary<string, byte[]>();
private const string DATADIR = "mapdata\\";
static EntityChunkRegionSystem()
{
Directory.CreateDirectory(DATADIR);
InitEntityChunks();
}
public static void KeepOriginForPosition(Vector2 position)
{
Point pos = position.Settle();
//shift when appropriate
Point shiftDirection = Point.Zero;
if (pos.X > REGION_SIZE_IN_METERS) shiftDirection = new Point(pos.X/REGION_SIZE_IN_METERS,0);
else if (pos.X < -REGION_SIZE_IN_METERS) shiftDirection = new Point(pos.X/REGION_SIZE_IN_METERS,0);
// up to 100,000 from origin ok on nvidia 500 series... let's just shift every 10,000k then //todo
if (shiftDirection != Point.Zero) //FIXME origin shift atm is slow and naive
{
// get previous regions range
int prevAbsRegionsStart = currentOriginInRegions;
int prevAbsRegionsEnd = currentOriginInRegions + 4;
// store regions shift amount
currentOriginInRegions += shiftDirection.X;
// get current regions range
int curAbsRegionsStart = currentOriginInRegions;
int curAbsRegionsEnd = currentOriginInRegions + 4;
// cleanup regions outta range
for (var i = 0; i < chunks_.Length; i++)
{
Chunk chunk = chunks_[i];
int relRegionX = i >> REGION_LOG_SIZE_IN_CHUNKS;
//if chunk abs region is not in current bounds
if (chunk.absRegionX < curAbsRegionsStart || chunk.absRegionX >= curAbsRegionsEnd)
{
chunk.UnloadChunk(relRegionX);
}
}
// translate all entities
Vector2 shift = shiftDirection.ToVector2() * -REGION_SIZE_IN_METERS;
Entity.ShiftAllEntities(shift);
OnOriginShift?.Invoke(shift);
// mark new chunks for loading
for (var i = 0; i < chunks_.Length; i++)
{
int relRegionX = i >> REGION_LOG_SIZE_IN_CHUNKS;
int absRegionX = currentOriginInRegions + relRegionX;
Chunk chunk = chunks_[i];
chunk.SetRegionX(absRegionX);
//load new chunks
if (chunk.absRegionX < prevAbsRegionsStart || chunk.absRegionX >= prevAbsRegionsEnd)
{
chunk.MarkAsNew();
}
int relChunkX = i % REGION_SIZE_IN_CHUNKS;
DebugHelper.AddDebugText(absRegionX.ToString(), chunk.GetWorldCenter(relRegionX) - Vector2.UnitY * 8,Color.White);
DebugHelper.AddDebugText(relChunkX.ToString(), chunk.GetWorldCenter(relRegionX) - Vector2.UnitY * 12,Color.Lime);
DebugHelper.AddDebugText(chunk.absRegionX.ToString(), chunk.GetWorldCenter(relRegionX) - Vector2.UnitY * 18,Color.Yellow);
}
}
// load as appropriate TODO culling
for (var i = 0; i < chunks_.Length; i++)
{
chunks_[i].TryLoadChunk(i >> REGION_LOG_SIZE_IN_CHUNKS);
}
}
private static void InitEntityChunks()
{
//TODO load at correct starting position
currentOriginInRegions = 0;
for (var i = 0; i < chunks_.Length; i++)
{
chunks_[i] = new Chunk(i % REGION_SIZE_IN_CHUNKS, currentOriginInRegions + i / REGION_SIZE_IN_CHUNKS);
}
}
public static Point GetChunkForPosition(Vector2 position)
{
return new Point(
(position.X.Settle() >> CHUNK_LOG_SIZE) + REGION_SIZE_IN_CHUNKS * 2, // same as: pos.Y / CHUNK_SIZE
0
);
}
private static int RelativeRegionAndChunkIndexToWorld(int relRegion, int chunkIdx)
{
int relativeRegion = -2 * REGION_SIZE_IN_METERS + relRegion * REGION_SIZE_IN_METERS;
return relativeRegion + chunkIdx * CHUNK_SIZE;
}
public static void UpdateChunkSystemForEntity(Entity e) //maintains chunks
{
int lastChunkPos = GetChunkForPosition(e.LastPosition).X;
int curChunkPos = GetChunkForPosition(e.Position).X;
//if entity didn't change chunk
if (lastChunkPos == curChunkPos) return;
if (lastChunkPos >= 0 && lastChunkPos < chunks_.Length) //if last chunk pos is valid
{
var lastChunk = chunks_[lastChunkPos];
lastChunk.entities.Remove(e);
}
if (curChunkPos >= 0 && curChunkPos < chunks_.Length) //if chunk pos is valid
{
var curChunk = chunks_[curChunkPos];
if(!curChunk.entities.Contains(e))
curChunk.entities.Add(e);
}
}
public static bool IsChunkIndexInBounds(int index)
{
if (index >= 0 && index < REGION_SIZE_IN_CHUNKS * 4)
return true;
return false;
}
public static void RemoveEntityFromSystem(Entity e)
{
int chunkPos = GetChunkForPosition(e.Position).X;
if (IsChunkIndexInBounds(chunkPos))
{
chunks_[chunkPos].entities.Remove(e);
}
}
public static void DebugDrawEntityChunks()
{
for (var i = 0; i < chunks_.Length; i++)
{
Chunk chunk = chunks_[i];
Vector2 chunkStart = new Vector2(REGION_SIZE_IN_METERS*-2 + i* CHUNK_SIZE, 0);
int curRegion = (i >> REGION_LOG_SIZE_IN_CHUNKS) +currentOriginInRegions;
// color according to region
Color c = Color.Red;
if(curRegion == 1)c=Color.Lime;
else if (curRegion == 2)c=Color.Yellow;
else if (curRegion == 3)c=Color.Cyan;
DebugHelper.AddDebugText(
$"regn:{curRegion}\narri:{i}\ncnki:{i% REGION_SIZE_IN_CHUNKS}\nents:{chunk.entities.Count}"
, chunkStart+Vector2.UnitY*-6, c);
DebugHelper.AddDebugLine(chunkStart, chunkStart+Vector2.UnitY* CHUNK_SIZE, new Color(0,1,0,0.25f));
foreach (Entity entity in chunk.entities)
{
//DebugHelper.AddDebugLine(chunkStart, entity.Position, Color.Yellow);
//DebugHelper.AddDebugText(GetChunkForPosition(entity.Position).X.ToString(), entity.Position, c);
}
}
}
}
}
#endif
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Cursor;
using osu.Game.Rulesets;
using osu.Game.Screens.Play;
using osu.Game.Skinning;
using osuTK;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestScenePause : OsuPlayerTestScene
{
protected new PausePlayer Player => (PausePlayer)base.Player;
private readonly Container content;
protected override Container<Drawable> Content => content;
public TestScenePause()
{
base.Content.Add(content = new MenuCursorContainer { RelativeSizeAxes = Axes.Both });
}
[SetUpSteps]
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("resume player", () => Player.GameplayClockContainer.Start());
confirmClockRunning(true);
}
[Test]
public void TestPauseResume()
{
AddStep("move cursor outside", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.TopLeft - new Vector2(10)));
pauseAndConfirm();
resumeAndConfirm();
}
[Test]
public void TestResumeWithResumeOverlay()
{
AddStep("move cursor to center", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.Centre));
AddUntilStep("wait for hitobjects", () => Player.HealthProcessor.Health.Value < 1);
pauseAndConfirm();
resume();
confirmPausedWithNoOverlay();
AddStep("click to resume", () => InputManager.Click(MouseButton.Left));
confirmClockRunning(true);
}
[Test]
public void TestPauseWithResumeOverlay()
{
AddStep("move cursor to center", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.Centre));
AddUntilStep("wait for hitobjects", () => Player.HealthProcessor.Health.Value < 1);
pauseAndConfirm();
resume();
confirmPausedWithNoOverlay();
pauseAndConfirm();
AddUntilStep("resume overlay is not active", () => Player.DrawableRuleset.ResumeOverlay.State.Value == Visibility.Hidden);
confirmPaused();
confirmNotExited();
}
[Test]
public void TestResumeWithResumeOverlaySkipped()
{
AddStep("move cursor to button", () =>
InputManager.MoveMouseTo(Player.HUDOverlay.HoldToQuit.Children.OfType<HoldToConfirmContainer>().First().ScreenSpaceDrawQuad.Centre));
AddUntilStep("wait for hitobjects", () => Player.HealthProcessor.Health.Value < 1);
pauseAndConfirm();
resumeAndConfirm();
}
[Test]
public void TestUserPauseWhenPauseNotAllowed()
{
AddStep("disable pause support", () => Player.Configuration.AllowPause = false);
pauseFromUserExitKey();
confirmExited();
}
[Test]
public void TestUserPauseDuringCooldownTooSoon()
{
AddStep("move cursor outside", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.TopLeft - new Vector2(10)));
pauseAndConfirm();
resume();
pauseFromUserExitKey();
confirmResumed();
confirmNotExited();
}
[Test]
public void TestQuickExitDuringCooldownTooSoon()
{
AddStep("move cursor outside", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.TopLeft - new Vector2(10)));
pauseAndConfirm();
resume();
AddStep("pause via exit key", () => Player.ExitViaQuickExit());
confirmResumed();
AddAssert("exited", () => !Player.IsCurrentScreen());
}
[Test]
public void TestExitSoonAfterResumeSucceeds()
{
AddStep("seek before gameplay", () => Player.GameplayClockContainer.Seek(-5000));
pauseAndConfirm();
resume();
AddStep("exit quick", () => Player.Exit());
confirmResumed();
AddAssert("exited", () => !Player.IsCurrentScreen());
}
[Test]
public void TestPauseAfterFail()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("fail overlay shown", () => Player.FailOverlayVisible);
confirmClockRunning(false);
AddStep("pause via forced pause", () => Player.Pause());
confirmPausedWithNoOverlay();
AddAssert("fail overlay still shown", () => Player.FailOverlayVisible);
exitAndConfirm();
}
[Test]
public void TestExitFromFailedGameplayAfterFailAnimation()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for fail overlay shown", () => Player.FailOverlayVisible);
confirmClockRunning(false);
AddStep("exit via user pause", () => Player.ExitViaPause());
confirmExited();
}
[Test]
public void TestExitFromFailedGameplayDuringFailAnimation()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
// will finish the fail animation and show the fail/pause screen.
AddStep("attempt exit via pause key", () => Player.ExitViaPause());
AddAssert("fail overlay shown", () => Player.FailOverlayVisible);
// will actually exit.
AddStep("exit via pause key", () => Player.ExitViaPause());
confirmExited();
}
[Test]
public void TestQuickRetryFromFailedGameplay()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddStep("quick retry", () => Player.GameplayClockContainer.ChildrenOfType<HotkeyRetryOverlay>().First().Action?.Invoke());
confirmExited();
}
[Test]
public void TestQuickExitFromFailedGameplay()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddStep("quick exit", () => Player.GameplayClockContainer.ChildrenOfType<HotkeyExitOverlay>().First().Action?.Invoke());
confirmExited();
}
[Test]
public void TestExitFromGameplay()
{
// an externally triggered exit should immediately exit, skipping all pause logic.
AddStep("exit", () => Player.Exit());
confirmExited();
}
[Test]
public void TestQuickExitFromGameplay()
{
AddStep("quick exit", () => Player.GameplayClockContainer.ChildrenOfType<HotkeyExitOverlay>().First().Action?.Invoke());
confirmExited();
}
[Test]
public void TestExitViaHoldToExit()
{
AddStep("exit", () =>
{
InputManager.MoveMouseTo(Player.HUDOverlay.HoldToQuit.First(c => c is HoldToConfirmContainer));
InputManager.PressButton(MouseButton.Left);
});
confirmPaused();
AddStep("release", () => InputManager.ReleaseButton(MouseButton.Left));
exitAndConfirm();
}
[Test]
public void TestExitFromPause()
{
pauseAndConfirm();
exitAndConfirm();
}
[Test]
public void TestRestartAfterResume()
{
AddStep("seek before gameplay", () => Player.GameplayClockContainer.Seek(-5000));
pauseAndConfirm();
resumeAndConfirm();
restart();
confirmExited();
}
[Test]
public void TestPauseSoundLoop()
{
AddStep("seek before gameplay", () => Player.GameplayClockContainer.Seek(-5000));
SkinnableSound getLoop() => Player.ChildrenOfType<PauseOverlay>().FirstOrDefault()?.ChildrenOfType<SkinnableSound>().FirstOrDefault();
pauseAndConfirm();
AddAssert("loop is playing", () => getLoop().IsPlaying);
resumeAndConfirm();
AddUntilStep("loop is stopped", () => !getLoop().IsPlaying);
AddUntilStep("pause again", () =>
{
Player.Pause();
return !Player.GameplayClockContainer.GameplayClock.IsRunning;
});
AddAssert("loop is playing", () => getLoop().IsPlaying);
resumeAndConfirm();
AddUntilStep("loop is stopped", () => !getLoop().IsPlaying);
}
private void pauseAndConfirm()
{
pauseFromUserExitKey();
confirmPaused();
}
private void resumeAndConfirm()
{
resume();
confirmResumed();
}
private void exitAndConfirm()
{
confirmNotExited();
AddStep("exit", () => Player.Exit());
confirmExited();
confirmNoTrackAdjustments();
}
private void confirmPaused()
{
confirmClockRunning(false);
confirmNotExited();
AddAssert("player not failed", () => !Player.HasFailed);
AddAssert("pause overlay shown", () => Player.PauseOverlayVisible);
}
private void confirmResumed()
{
confirmClockRunning(true);
confirmPauseOverlayShown(false);
}
private void confirmPausedWithNoOverlay()
{
confirmClockRunning(false);
confirmPauseOverlayShown(false);
}
private void confirmExited() => AddUntilStep("player exited", () => !Player.IsCurrentScreen());
private void confirmNotExited() => AddAssert("player not exited", () => Player.IsCurrentScreen());
private void confirmNoTrackAdjustments()
{
AddAssert("track has no adjustments", () => Beatmap.Value.Track.AggregateFrequency.Value == 1);
}
private void restart() => AddStep("restart", () => Player.Restart());
private void pauseFromUserExitKey() => AddStep("user pause", () => Player.ExitViaPause());
private void resume() => AddStep("resume", () => Player.Resume());
private void confirmPauseOverlayShown(bool isShown) =>
AddAssert("pause overlay " + (isShown ? "shown" : "hidden"), () => Player.PauseOverlayVisible == isShown);
private void confirmClockRunning(bool isRunning) =>
AddUntilStep("clock " + (isRunning ? "running" : "stopped"), () => Player.GameplayClockContainer.GameplayClock.IsRunning == isRunning);
protected override bool AllowFail => true;
protected override TestPlayer CreatePlayer(Ruleset ruleset) => new PausePlayer();
protected class PausePlayer : TestPlayer
{
public bool FailOverlayVisible => FailOverlay.State.Value == Visibility.Visible;
public bool PauseOverlayVisible => PauseOverlay.State.Value == Visibility.Visible;
public void ExitViaPause() => PerformExit(true);
public void ExitViaQuickExit() => PerformExit(false);
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
GameplayClockContainer.Stop();
}
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Config;
namespace NLog.UnitTests.Filters
{
using System;
using Xunit;
public class WhenRepeatedTests : NLogTestBase
{
[Fact]
public void WhenRepeatedIgnoreTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'>
<filters>
<whenRepeated layout='${message}' action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 1);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
}
[Fact]
public void WhenRepeatedIgnoreDualTargetTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug' type='Debug' layout='${message}' />
<target name='debug2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug,debug2'>
<filters>
<whenRepeated layout='${message}' action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 1);
AssertDebugCounter("debug2", 1);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
AssertDebugCounter("debug2", 2);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
AssertDebugCounter("debug2", 2);
}
[Fact]
public void WhenRepeatedLogAfterTimeoutTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'>
<filters>
<whenRepeated layout='${message}' action='Ignore' includeFirst='True' />
</filters>
</logger>
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 0);
logger.Debug("zzz");
AssertDebugCounter("debug", 0);
logger.Debug("zzz");
AssertDebugCounter("debug", 0);
}
[Fact]
public void WhenRepeatedTimeoutIgnoreTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'>
<filters>
<whenRepeated layout='${message}' action='Ignore' timeoutSeconds='10' />
</filters>
</logger>
</rules>
</nlog>");
var defaultTimeSource = Time.TimeSource.Current;
try
{
var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local);
Time.TimeSource.Current = timeSource;
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 1);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(5));
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Debug("b");
AssertDebugCounter("debug", 3);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(10));
logger.Debug("zzz");
AssertDebugCounter("debug", 4);
}
finally
{
Time.TimeSource.Current = defaultTimeSource; // restore default time source
}
}
[Fact]
public void WhenRepeatedTimeoutLogAfterTimeoutTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'>
<filters>
<whenRepeated layout='${message}' action='Ignore' includeFirst='True' timeoutSeconds='10' />
</filters>
</logger>
</rules>
</nlog>");
var defaultTimeSource = Time.TimeSource.Current;
try
{
var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local);
Time.TimeSource.Current = timeSource;
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 0);
logger.Debug("zzz");
AssertDebugCounter("debug", 0);
logger.Debug("zzz");
AssertDebugCounter("debug", 0);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(5));
logger.Debug("zzz");
AssertDebugCounter("debug", 0);
logger.Debug("b");
AssertDebugCounter("debug", 0);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(10));
logger.Debug("zzz");
AssertDebugCounter("debug", 1);
}
finally
{
Time.TimeSource.Current = defaultTimeSource; // restore default time source
}
}
[Fact]
public void WhenRepeatedDefaultFilterCountIgnoreTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'>
<filters>
<whenRepeated layout='${message}' action='Ignore' defaultFilterCacheSize='5' timeoutSeconds='10' />
</filters>
</logger>
</rules>
</nlog>");
var defaultTimeSource = Time.TimeSource.Current;
try
{
var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local);
Time.TimeSource.Current = timeSource;
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 1);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Debug("b");
AssertDebugCounter("debug", 3);
logger.Debug("c");
AssertDebugCounter("debug", 4);
logger.Debug("d");
AssertDebugCounter("debug", 5);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(5));
logger.Debug("e");
AssertDebugCounter("debug", 6);
logger.Debug("f");
AssertDebugCounter("debug", 7);
logger.Debug("zzz");
AssertDebugCounter("debug", 7);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(10));
for (int i = 0; i < 10; ++i)
{
char charCount = (char)('g' + i);
logger.Debug(charCount.ToString());
AssertDebugCounter("debug", 8 + i);
}
logger.Debug("zzz");
AssertDebugCounter("debug", 18);
}
finally
{
Time.TimeSource.Current = defaultTimeSource; // restore default time source
}
}
[Fact]
public void WhenRepeatedMaxCacheSizeIgnoreTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'>
<filters>
<whenRepeated layout='${message}' action='Ignore' maxFilterCacheSize='5' defaultFilterCacheSize='5' timeoutSeconds='10' />
</filters>
</logger>
</rules>
</nlog>");
var defaultTimeSource = Time.TimeSource.Current;
try
{
var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local);
Time.TimeSource.Current = timeSource;
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 1);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Debug("b");
AssertDebugCounter("debug", 3);
logger.Debug("c");
AssertDebugCounter("debug", 4);
logger.Debug("d");
AssertDebugCounter("debug", 5);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(5));
logger.Debug("e");
AssertDebugCounter("debug", 6);
logger.Debug("f");
AssertDebugCounter("debug", 7);
logger.Debug("zzz");
AssertDebugCounter("debug", 7);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(10));
for (int i = 0; i < 10; ++i)
{
char charCount = (char)('g' + i);
logger.Debug(charCount.ToString());
AssertDebugCounter("debug", 8 + i);
}
logger.Debug("zzz");
AssertDebugCounter("debug", 18);
}
finally
{
Time.TimeSource.Current = defaultTimeSource; // restore default time source
}
}
[Fact]
public void WhenRepeatedLevelIgnoreTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'>
<filters>
<whenRepeated layout='${message}' action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 1);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Error("zzz");
AssertDebugCounter("debug", 3);
logger.Error("zzz");
AssertDebugCounter("debug", 3);
logger.Debug("zzz");
AssertDebugCounter("debug", 3);
logger.Fatal("zzz");
AssertDebugCounter("debug", 4);
}
[Fact]
public void WhenRepeatedMaxLengthIgnoreTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'>
<filters>
<whenRepeated layout='${message}' action='Ignore' maxLength='16' optimizeBufferDefaultLength='16' />
</filters>
</logger>
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 1);
logger.Debug("zzzzzzzzzzzzzzzz");
AssertDebugCounter("debug", 2);
logger.Debug("zzzzzzzzzzzzzzzz");
AssertDebugCounter("debug", 2);
logger.Debug("zzzzzzzzzzzzzzzzzzzz");
AssertDebugCounter("debug", 2);
logger.Debug("b");
AssertDebugCounter("debug", 3);
}
[Fact]
public void WhenRepeatedFilterCountPropertyNameIgnoreTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}${event-properties:item=hits}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'>
<filters>
<whenRepeated layout='${message}' action='Ignore' timeoutSeconds='5' filterCountPropertyName='hits' />
</filters>
</logger>
</rules>
</nlog>");
var defaultTimeSource = Time.TimeSource.Current;
try
{
var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local);
Time.TimeSource.Current = timeSource;
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 1);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
AssertDebugLastMessage("debug", "zzz");
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(3));
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Debug("b");
AssertDebugCounter("debug", 3);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(3));
logger.Debug("zzz");
AssertDebugCounter("debug", 4);
AssertDebugLastMessage("debug", "zzz2");
logger.Debug("zzz");
AssertDebugCounter("debug", 4);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(12));
logger.Debug("zzz");
AssertDebugCounter("debug", 5);
AssertDebugLastMessage("debug", "zzz");
}
finally
{
Time.TimeSource.Current = defaultTimeSource; // restore default time source
}
}
[Fact]
public void WhenRepeatedFilterCountAppendFormatIgnoreTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}${event-properties:item=hits}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug'>
<filters>
<whenRepeated layout='${message}' action='Ignore' timeoutSeconds='5' filterCountMessageAppendFormat=' (Hits: {0})' />
</filters>
</logger>
</rules>
</nlog>");
var defaultTimeSource = Time.TimeSource.Current;
try
{
var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local);
Time.TimeSource.Current = timeSource;
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugCounter("debug", 1);
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
AssertDebugLastMessage("debug", "zzz");
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(3));
logger.Debug("zzz");
AssertDebugCounter("debug", 2);
logger.Debug("b");
AssertDebugCounter("debug", 3);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(3));
logger.Debug("zzz");
AssertDebugCounter("debug", 4);
AssertDebugLastMessage("debug", "zzz (Hits: 2)");
logger.Debug("zzz");
AssertDebugCounter("debug", 4);
timeSource.AddToLocalTime(TimeSpan.FromSeconds(12));
logger.Debug("zzz");
AssertDebugCounter("debug", 5);
AssertDebugLastMessage("debug", "zzz");
}
finally
{
Time.TimeSource.Current = defaultTimeSource; // restore default time source
}
}
}
}
| |
using System.Collections.Generic;
using CppSharp.Utils;
using NUnit.Framework;
using CppSharp.Parser;
namespace CppSharp.Generator.Tests
{
[TestFixture]
public class ReadNativeSymbolsTest
{
[Test]
public void TestReadSymbolsWindows()
{
var symbols = GetSymbols("libexpat-windows");
Assert.AreEqual("XML_DefaultCurrent", symbols[0]);
Assert.AreEqual("XML_ErrorString", symbols[1]);
Assert.AreEqual("XML_ExpatVersion", symbols[2]);
Assert.AreEqual("XML_ExpatVersionInfo", symbols[3]);
Assert.AreEqual("XML_ExternalEntityParserCreate", symbols[4]);
Assert.AreEqual("XML_FreeContentModel", symbols[5]);
Assert.AreEqual("XML_GetBase", symbols[6]);
Assert.AreEqual("XML_GetBuffer", symbols[7]);
Assert.AreEqual("XML_GetCurrentByteCount", symbols[8]);
Assert.AreEqual("XML_GetCurrentByteIndex", symbols[9]);
Assert.AreEqual("XML_GetCurrentColumnNumber", symbols[10]);
Assert.AreEqual("XML_GetCurrentLineNumber", symbols[11]);
Assert.AreEqual("XML_GetErrorCode", symbols[12]);
Assert.AreEqual("XML_GetFeatureList", symbols[13]);
Assert.AreEqual("XML_GetIdAttributeIndex", symbols[14]);
Assert.AreEqual("XML_GetInputContext", symbols[15]);
Assert.AreEqual("XML_GetParsingStatus", symbols[16]);
Assert.AreEqual("XML_GetSpecifiedAttributeCount", symbols[17]);
Assert.AreEqual("XML_MemFree", symbols[18]);
Assert.AreEqual("XML_MemMalloc", symbols[19]);
Assert.AreEqual("XML_MemRealloc", symbols[20]);
Assert.AreEqual("XML_Parse", symbols[21]);
Assert.AreEqual("XML_ParseBuffer", symbols[22]);
Assert.AreEqual("XML_ParserCreate", symbols[23]);
Assert.AreEqual("XML_ParserCreateNS", symbols[24]);
Assert.AreEqual("XML_ParserCreate_MM", symbols[25]);
Assert.AreEqual("XML_ParserFree", symbols[26]);
Assert.AreEqual("XML_ParserReset", symbols[27]);
Assert.AreEqual("XML_ResumeParser", symbols[28]);
Assert.AreEqual("XML_SetAttlistDeclHandler", symbols[29]);
Assert.AreEqual("XML_SetBase", symbols[30]);
Assert.AreEqual("XML_SetCdataSectionHandler", symbols[31]);
Assert.AreEqual("XML_SetCharacterDataHandler", symbols[32]);
Assert.AreEqual("XML_SetCommentHandler", symbols[33]);
Assert.AreEqual("XML_SetDefaultHandler", symbols[34]);
Assert.AreEqual("XML_SetDefaultHandlerExpand", symbols[35]);
Assert.AreEqual("XML_SetDoctypeDeclHandler", symbols[36]);
Assert.AreEqual("XML_SetElementDeclHandler", symbols[37]);
Assert.AreEqual("XML_SetElementHandler", symbols[38]);
Assert.AreEqual("XML_SetEncoding", symbols[39]);
Assert.AreEqual("XML_SetEndCdataSectionHandler", symbols[40]);
Assert.AreEqual("XML_SetEndDoctypeDeclHandler", symbols[41]);
Assert.AreEqual("XML_SetEndElementHandler", symbols[42]);
Assert.AreEqual("XML_SetEndNamespaceDeclHandler", symbols[43]);
Assert.AreEqual("XML_SetEntityDeclHandler", symbols[44]);
Assert.AreEqual("XML_SetExternalEntityRefHandler", symbols[45]);
Assert.AreEqual("XML_SetExternalEntityRefHandlerArg", symbols[46]);
Assert.AreEqual("XML_SetHashSalt", symbols[47]);
Assert.AreEqual("XML_SetNamespaceDeclHandler", symbols[48]);
Assert.AreEqual("XML_SetNotStandaloneHandler", symbols[49]);
Assert.AreEqual("XML_SetNotationDeclHandler", symbols[50]);
Assert.AreEqual("XML_SetParamEntityParsing", symbols[51]);
Assert.AreEqual("XML_SetProcessingInstructionHandler", symbols[52]);
Assert.AreEqual("XML_SetReturnNSTriplet", symbols[53]);
Assert.AreEqual("XML_SetSkippedEntityHandler", symbols[54]);
Assert.AreEqual("XML_SetStartCdataSectionHandler", symbols[55]);
Assert.AreEqual("XML_SetStartDoctypeDeclHandler", symbols[56]);
Assert.AreEqual("XML_SetStartElementHandler", symbols[57]);
Assert.AreEqual("XML_SetStartNamespaceDeclHandler", symbols[58]);
Assert.AreEqual("XML_SetUnknownEncodingHandler", symbols[59]);
Assert.AreEqual("XML_SetUnparsedEntityDeclHandler", symbols[60]);
Assert.AreEqual("XML_SetUserData", symbols[61]);
Assert.AreEqual("XML_SetXmlDeclHandler", symbols[62]);
Assert.AreEqual("XML_StopParser", symbols[63]);
Assert.AreEqual("XML_UseForeignDTD", symbols[64]);
Assert.AreEqual("XML_UseParserAsHandlerArg", symbols[65]);
Assert.AreEqual("XmlGetUtf16InternalEncoding", symbols[66]);
Assert.AreEqual("XmlGetUtf16InternalEncodingNS", symbols[67]);
Assert.AreEqual("XmlGetUtf8InternalEncoding", symbols[68]);
Assert.AreEqual("XmlGetUtf8InternalEncodingNS", symbols[69]);
Assert.AreEqual("XmlInitEncoding", symbols[70]);
Assert.AreEqual("XmlInitEncodingNS", symbols[71]);
Assert.AreEqual("XmlInitUnknownEncoding", symbols[72]);
Assert.AreEqual("XmlInitUnknownEncodingNS", symbols[73]);
Assert.AreEqual("XmlParseXmlDecl", symbols[74]);
Assert.AreEqual("XmlParseXmlDeclNS", symbols[75]);
Assert.AreEqual("XmlPrologStateInit", symbols[76]);
Assert.AreEqual("XmlPrologStateInitExternalEntity", symbols[77]);
Assert.AreEqual("XmlSizeOfUnknownEncoding", symbols[78]);
Assert.AreEqual("XmlUtf16Encode", symbols[79]);
Assert.AreEqual("XmlUtf8Encode", symbols[80]);
Assert.AreEqual("align_limit_to_full_utf8_characters", symbols[81]);
}
[Test]
public void TestReadSymbolsLinux()
{
var symbols = GetSymbols("libexpat-linux");
Assert.AreEqual("free", symbols[0]);
Assert.AreEqual("_ITM_deregisterTMCloneTable", symbols[1]);
Assert.AreEqual("getpid", symbols[2]);
Assert.AreEqual("__stack_chk_fail", symbols[3]);
Assert.AreEqual("gettimeofday", symbols[4]);
Assert.AreEqual("__assert_fail", symbols[5]);
Assert.AreEqual("memset", symbols[6]);
Assert.AreEqual("memcmp", symbols[7]);
Assert.AreEqual("__gmon_start__", symbols[8]);
Assert.AreEqual("memcpy", symbols[9]);
Assert.AreEqual("malloc", symbols[10]);
Assert.AreEqual("realloc", symbols[11]);
Assert.AreEqual("memmove", symbols[12]);
Assert.AreEqual("_Jv_RegisterClasses", symbols[13]);
Assert.AreEqual("_ITM_registerTMCloneTable", symbols[14]);
Assert.AreEqual("__cxa_finalize", symbols[15]);
Assert.AreEqual("XmlInitUnknownEncoding", symbols[16]);
Assert.AreEqual("XML_FreeContentModel", symbols[17]);
Assert.AreEqual("XML_SetEndDoctypeDeclHandler", symbols[18]);
Assert.AreEqual("XML_GetParsingStatus", symbols[19]);
Assert.AreEqual("XmlGetUtf16InternalEncoding", symbols[20]);
Assert.AreEqual("XML_MemRealloc", symbols[21]);
Assert.AreEqual("XmlInitEncoding", symbols[22]);
Assert.AreEqual("XML_ExpatVersion", symbols[23]);
Assert.AreEqual("XML_SetHashSalt", symbols[24]);
Assert.AreEqual("XML_SetStartDoctypeDeclHandler", symbols[25]);
Assert.AreEqual("XML_ExternalEntityParserCreate", symbols[26]);
Assert.AreEqual("XML_GetBuffer", symbols[27]);
Assert.AreEqual("XML_GetCurrentColumnNumber", symbols[28]);
Assert.AreEqual("XML_SetEndCdataSectionHandler", symbols[29]);
Assert.AreEqual("XML_SetStartCdataSectionHandler", symbols[30]);
Assert.AreEqual("XML_GetCurrentByteCount", symbols[31]);
Assert.AreEqual("XML_DefaultCurrent", symbols[32]);
Assert.AreEqual("XmlInitUnknownEncodingNS", symbols[33]);
Assert.AreEqual("XML_ExpatVersionInfo", symbols[34]);
Assert.AreEqual("XmlUtf16Encode", symbols[35]);
Assert.AreEqual("XML_GetInputContext", symbols[36]);
Assert.AreEqual("XML_SetExternalEntityRefHandler", symbols[37]);
Assert.AreEqual("XML_GetSpecifiedAttributeCount", symbols[38]);
Assert.AreEqual("XML_SetUserData", symbols[39]);
Assert.AreEqual("XML_ErrorString", symbols[40]);
Assert.AreEqual("XML_SetElementHandler", symbols[41]);
Assert.AreEqual("XML_SetNamespaceDeclHandler", symbols[42]);
Assert.AreEqual("_fini", symbols[43]);
Assert.AreEqual("XmlSizeOfUnknownEncoding", symbols[44]);
Assert.AreEqual("XML_GetIdAttributeIndex", symbols[45]);
Assert.AreEqual("XML_SetAttlistDeclHandler", symbols[46]);
Assert.AreEqual("XML_SetReturnNSTriplet", symbols[47]);
Assert.AreEqual("XML_SetUnknownEncodingHandler", symbols[48]);
Assert.AreEqual("XML_SetCdataSectionHandler", symbols[49]);
Assert.AreEqual("XmlParseXmlDeclNS", symbols[50]);
Assert.AreEqual("XML_SetDoctypeDeclHandler", symbols[51]);
Assert.AreEqual("XML_SetDefaultHandler", symbols[52]);
Assert.AreEqual("_init", symbols[53]);
Assert.AreEqual("XmlPrologStateInitExternalEntity", symbols[54]);
Assert.AreEqual("XML_SetCharacterDataHandler", symbols[55]);
Assert.AreEqual("XML_ParserCreate", symbols[56]);
Assert.AreEqual("XmlGetUtf8InternalEncodingNS", symbols[57]);
Assert.AreEqual("XML_SetParamEntityParsing", symbols[58]);
Assert.AreEqual("XML_MemFree", symbols[59]);
Assert.AreEqual("XML_SetElementDeclHandler", symbols[60]);
Assert.AreEqual("XML_MemMalloc", symbols[61]);
Assert.AreEqual("XML_SetStartNamespaceDeclHandler", symbols[62]);
Assert.AreEqual("XmlGetUtf16InternalEncodingNS", symbols[63]);
Assert.AreEqual("XML_ParseBuffer", symbols[64]);
Assert.AreEqual("XML_UseForeignDTD", symbols[65]);
Assert.AreEqual("XML_SetEncoding", symbols[66]);
Assert.AreEqual("XML_UseParserAsHandlerArg", symbols[67]);
Assert.AreEqual("XML_SetEndNamespaceDeclHandler", symbols[68]);
Assert.AreEqual("XML_SetEndElementHandler", symbols[69]);
Assert.AreEqual("XML_GetCurrentLineNumber", symbols[70]);
Assert.AreEqual("XML_SetXmlDeclHandler", symbols[71]);
Assert.AreEqual("XML_SetProcessingInstructionHandler", symbols[72]);
Assert.AreEqual("XmlUtf8Encode", symbols[73]);
Assert.AreEqual("XML_SetStartElementHandler", symbols[74]);
Assert.AreEqual("XML_SetSkippedEntityHandler", symbols[75]);
Assert.AreEqual("XML_ResumeParser", symbols[76]);
Assert.AreEqual("XML_SetEntityDeclHandler", symbols[77]);
Assert.AreEqual("XML_ParserFree", symbols[78]);
Assert.AreEqual("XML_SetNotStandaloneHandler", symbols[79]);
Assert.AreEqual("XML_ParserCreate_MM", symbols[80]);
Assert.AreEqual("XML_ParserCreateNS", symbols[81]);
Assert.AreEqual("_edata", symbols[82]);
Assert.AreEqual("XML_SetUnparsedEntityDeclHandler", symbols[83]);
Assert.AreEqual("XML_SetBase", symbols[84]);
Assert.AreEqual("XML_GetBase", symbols[85]);
Assert.AreEqual("XmlGetUtf8InternalEncoding", symbols[86]);
Assert.AreEqual("XML_SetExternalEntityRefHandlerArg", symbols[87]);
Assert.AreEqual("XmlPrologStateInit", symbols[88]);
Assert.AreEqual("_end", symbols[89]);
Assert.AreEqual("XML_SetCommentHandler", symbols[90]);
Assert.AreEqual("XmlParseXmlDecl", symbols[91]);
Assert.AreEqual("XML_StopParser", symbols[92]);
Assert.AreEqual("XML_GetErrorCode", symbols[93]);
Assert.AreEqual("XML_GetFeatureList", symbols[94]);
Assert.AreEqual("XML_SetDefaultHandlerExpand", symbols[95]);
Assert.AreEqual("XML_Parse", symbols[96]);
Assert.AreEqual("XmlInitEncodingNS", symbols[97]);
Assert.AreEqual("XML_ParserReset", symbols[98]);
Assert.AreEqual("XML_SetNotationDeclHandler", symbols[99]);
Assert.AreEqual("__bss_start", symbols[100]);
Assert.AreEqual("XML_GetCurrentByteIndex", symbols[101]);
}
[Test]
public void TestReadSymbolsOSX()
{
var symbols = GetSymbols("libexpat-osx");
Assert.AreEqual("_XML_ParserCreate_MM", symbols[0]);
Assert.AreEqual("_XML_ParserCreateNS", symbols[1]);
Assert.AreEqual("_XML_ParserCreate", symbols[2]);
Assert.AreEqual("_XML_ParserReset", symbols[3]);
Assert.AreEqual("_XML_ParserFree", symbols[4]);
Assert.AreEqual("_XML_ParseBuffer", symbols[5]);
Assert.AreEqual("_XML_Parse", symbols[6]);
Assert.AreEqual("_XML_SetEncoding", symbols[7]);
Assert.AreEqual("_XML_SetEndElementHandler", symbols[8]);
Assert.AreEqual("_XML_SetEndCdataSectionHandler", symbols[9]);
Assert.AreEqual("_XML_SetEndDoctypeDeclHandler", symbols[10]);
Assert.AreEqual("_XML_SetEndNamespaceDeclHandler", symbols[11]);
Assert.AreEqual("_XML_SetEntityDeclHandler", symbols[12]);
Assert.AreEqual("_XML_SetElementHandler", symbols[13]);
Assert.AreEqual("_XML_SetElementDeclHandler", symbols[14]);
Assert.AreEqual("_XML_SetExternalEntityRefHandlerArg", symbols[15]);
Assert.AreEqual("_XML_SetExternalEntityRefHandler", symbols[16]);
Assert.AreEqual("_XML_SetReturnNSTriplet", symbols[17]);
Assert.AreEqual("_XML_SetUserData", symbols[18]);
Assert.AreEqual("_XML_SetUnparsedEntityDeclHandler", symbols[19]);
Assert.AreEqual("_XML_SetUnknownEncodingHandler", symbols[20]);
Assert.AreEqual("_XML_SetBase", symbols[21]);
Assert.AreEqual("_XML_SetStartElementHandler", symbols[22]);
Assert.AreEqual("_XML_SetStartCdataSectionHandler", symbols[23]);
Assert.AreEqual("_XML_SetStartDoctypeDeclHandler", symbols[24]);
Assert.AreEqual("_XML_SetStartNamespaceDeclHandler", symbols[25]);
Assert.AreEqual("_XML_SetSkippedEntityHandler", symbols[26]);
Assert.AreEqual("_XML_SetCharacterDataHandler", symbols[27]);
Assert.AreEqual("_XML_SetCommentHandler", symbols[28]);
Assert.AreEqual("_XML_SetCdataSectionHandler", symbols[29]);
Assert.AreEqual("_XML_SetProcessingInstructionHandler", symbols[30]);
Assert.AreEqual("_XML_SetParamEntityParsing", symbols[31]);
Assert.AreEqual("_XML_SetDefaultHandlerExpand", symbols[32]);
Assert.AreEqual("_XML_SetDefaultHandler", symbols[33]);
Assert.AreEqual("_XML_SetDoctypeDeclHandler", symbols[34]);
Assert.AreEqual("_XML_SetNotationDeclHandler", symbols[35]);
Assert.AreEqual("_XML_SetNotStandaloneHandler", symbols[36]);
Assert.AreEqual("_XML_SetNamespaceDeclHandler", symbols[37]);
Assert.AreEqual("_XML_SetAttlistDeclHandler", symbols[38]);
Assert.AreEqual("_XML_SetXmlDeclHandler", symbols[39]);
Assert.AreEqual("_XML_SetHashSalt", symbols[40]);
Assert.AreEqual("_XML_StopParser", symbols[41]);
Assert.AreEqual("_XML_ExternalEntityParserCreate", symbols[42]);
Assert.AreEqual("_XML_ExpatVersionInfo", symbols[43]);
Assert.AreEqual("_XML_ExpatVersion", symbols[44]);
Assert.AreEqual("_XML_ErrorString", symbols[45]);
Assert.AreEqual("_XML_UseParserAsHandlerArg", symbols[46]);
Assert.AreEqual("_XML_UseForeignDTD", symbols[47]);
Assert.AreEqual("_XML_GetBase", symbols[48]);
Assert.AreEqual("_XML_GetBuffer", symbols[49]);
Assert.AreEqual("_XML_GetSpecifiedAttributeCount", symbols[50]);
Assert.AreEqual("_XML_GetIdAttributeIndex", symbols[51]);
Assert.AreEqual("_XML_GetInputContext", symbols[52]);
Assert.AreEqual("_XML_GetParsingStatus", symbols[53]);
Assert.AreEqual("_XML_GetErrorCode", symbols[54]);
Assert.AreEqual("_XML_GetCurrentByteIndex", symbols[55]);
Assert.AreEqual("_XML_GetCurrentByteCount", symbols[56]);
Assert.AreEqual("_XML_GetCurrentLineNumber", symbols[57]);
Assert.AreEqual("_XML_GetCurrentColumnNumber", symbols[58]);
Assert.AreEqual("_XML_GetFeatureList", symbols[59]);
Assert.AreEqual("_XML_ResumeParser", symbols[60]);
Assert.AreEqual("_XML_FreeContentModel", symbols[61]);
Assert.AreEqual("_XML_MemMalloc", symbols[62]);
Assert.AreEqual("_XML_MemRealloc", symbols[63]);
Assert.AreEqual("_XML_MemFree", symbols[64]);
Assert.AreEqual("_XML_DefaultCurrent", symbols[65]);
Assert.AreEqual("_XmlUtf8Encode", symbols[66]);
Assert.AreEqual("_XmlUtf16Encode", symbols[67]);
Assert.AreEqual("_XmlSizeOfUnknownEncoding", symbols[68]);
Assert.AreEqual("_XmlInitUnknownEncodingNS", symbols[69]);
Assert.AreEqual("_XmlInitUnknownEncoding", symbols[70]);
Assert.AreEqual("_XmlInitEncodingNS", symbols[71]);
Assert.AreEqual("_XmlInitEncoding", symbols[72]);
Assert.AreEqual("_XmlGetUtf8InternalEncodingNS", symbols[73]);
Assert.AreEqual("_XmlGetUtf8InternalEncoding", symbols[74]);
Assert.AreEqual("_XmlGetUtf16InternalEncodingNS", symbols[75]);
Assert.AreEqual("_XmlGetUtf16InternalEncoding", symbols[76]);
Assert.AreEqual("_XmlParseXmlDeclNS", symbols[77]);
Assert.AreEqual("_XmlParseXmlDecl", symbols[78]);
Assert.AreEqual("_XmlPrologStateInitExternalEntity", symbols[79]);
Assert.AreEqual("_XmlPrologStateInit", symbols[80]);
}
private static IList<string> GetSymbols(string library)
{
var parserOptions = new ParserOptions();
parserOptions.AddLibraryDirs(GeneratorTest.GetTestsDirectory("Native"));
var driverOptions = new DriverOptions();
var module = driverOptions.AddModule("Test");
module.Libraries.Add(library);
var driver = new Driver(driverOptions)
{
ParserOptions = parserOptions
};
driver.Setup();
Assert.IsTrue(driver.ParseLibraries());
var symbols = driver.Context.Symbols.Libraries[0].Symbols;
return symbols;
}
}
}
| |
namespace Loon.Action.Sprite
{
using System;
using System.Collections.Generic;
using Loon.Core;
using Loon.Utils;
using Loon.Core.Timer;
using Loon.Core.Geom;
using Loon.Core.Graphics;
using Loon.Core.Graphics.Opengl;
using Microsoft.Xna.Framework;
public class Cycle : LObject, ISprite
{
public static Cycle GetSample(int type, float srcWidth,
float srcHeight, float width, float height, float offset,
int padding) {
Cycle cycle = new Cycle();
float s = 1;
if (srcWidth > srcHeight) {
s = MathUtils.Max(srcWidth / width, srcHeight / height);
} else {
s = MathUtils.Min(srcWidth / width, srcHeight / height);
}
float scale = s;
switch (type) {
case 0:
cycle = new Anonymous_C1(scale);
cycle.SetLineWidth(5);
cycle.SetDelay(45);
cycle.SetColor(0xFF2E82);
cycle.SetStepType(4);
cycle.SetStepsPerFrame(1);
cycle.SetTrailLength(1);
cycle.SetPointDistance(0.05f);
cycle.AddPath(Cycle.ARC, 50, 50, 40, 0, 360);
break;
case 1:
cycle.SetColor(0xFF7B24);
cycle.SetStepsPerFrame(1);
cycle.SetTrailLength(1);
cycle.SetPointDistance(0.10f);
cycle.SetMultiplier(2);
cycle.AddPath(Cycle.ARC, 10 * scale, 10 * scale, 10 * scale, -270,
-90);
cycle.AddPath(Cycle.BEZIER, 10 * scale, 0 * scale, 40 * scale,
20 * scale, 20 * scale, 0, 30 * scale, 20 * scale);
cycle.AddPath(Cycle.ARC, 40 * scale, 10 * scale, 10 * scale, 90,
-90);
cycle.AddPath(Cycle.BEZIER, 40 * scale, 0 * scale, 10 * scale,
20 * scale, 30 * scale, 0, 20 * scale, 20 * scale);
break;
case 2:
cycle.SetColor(0xD4FF00);
cycle.SetStepType(1);
cycle.SetDelay(55);
cycle.SetStepsPerFrame(2);
cycle.SetTrailLength(0.3f);
cycle.SetPointDistance(0.1f);
cycle.AddPath(Cycle.LINE, 0, 0, 30 * scale, 0);
cycle.AddPath(Cycle.LINE, 30 * scale, 0 * scale, 30 * scale,
30 * scale);
cycle.AddPath(Cycle.LINE, 30 * scale, 30 * scale, 0, 30 * scale);
cycle.AddPath(Cycle.LINE, 0, 30 * scale, 0, 0);
break;
case 3:
cycle = new Anonymous_C0(scale);
cycle.SetColor(0x05E2FF);
cycle.SetLineWidth(2);
cycle.SetStepType(4);
cycle.SetStepsPerFrame(1);
cycle.SetTrailLength(1);
cycle.SetPointDistance(0.025f);
cycle.AddPath(Cycle.ARC, 50, 50, 40, 0, 360);
break;
case 4:
cycle.SetColor(0xFFA50000);
cycle.SetStepsPerFrame(1);
cycle.SetTrailLength(1);
cycle.SetPointDistance(0.025f);
cycle.AddPath(Cycle.ARC, 50 * scale, 50 * scale, 40 * scale, 0, 360);
break;
case 5:
cycle.SetColor(0xFF2E82);
cycle.SetDelay(60);
cycle.SetStepType(1);
cycle.SetStepsPerFrame(1);
cycle.SetTrailLength(1);
cycle.SetPointDistance(0.1f);
cycle.AddPath(Cycle.LINE, 0, 20 * scale, 100 * scale, 20 * scale);
cycle.AddPath(Cycle.LINE, 100 * scale, 20 * scale, 0, 20 * scale);
break;
case 6:
cycle.SetStepsPerFrame(7);
cycle.SetTrailLength(0.7f);
cycle.SetPointDistance(0.01f);
cycle.SetDelay(35);
cycle.SetLineWidth(10);
cycle.AddPath(Cycle.LINE, 20 * scale, 70 * scale, 50 * scale,
20 * scale);
cycle.AddPath(Cycle.LINE, 50 * scale, 20 * scale, 80 * scale,
70 * scale);
cycle.AddPath(Cycle.LINE, 80 * scale, 70 * scale, 20 * scale,
70 * scale);
break;
case 7:
cycle.SetColor(0xD4FF00);
cycle.SetStepsPerFrame(3);
cycle.SetTrailLength(1);
cycle.SetPointDistance(0.01f);
cycle.SetLineWidth(6);
cycle.SetPadding(0);
cycle.AddPath(Cycle.ARC, 50 * scale, 50 * scale, 20 * scale, 360, 0);
break;
case 8:
cycle.SetColor(0x05E2FF);
cycle.SetStepsPerFrame(1);
cycle.SetTrailLength(1);
cycle.SetPointDistance(0.02f);
cycle.AddPath(Cycle.ARC, 50 * scale, 50 * scale, 30 * scale, 0, 360);
break;
case 9:
cycle.SetStepType(1);
cycle.SetColor(LColor.yellow);
cycle.AddPath(Cycle.LINE, 10 * scale, 10 * scale, 90 * scale,
10 * scale);
cycle.AddPath(Cycle.LINE, 90 * scale, 10 * scale, 90 * scale,
90 * scale);
cycle.AddPath(Cycle.LINE, 90 * scale, 90 * scale, 10 * scale,
90 * scale);
cycle.AddPath(Cycle.LINE, 10 * scale, 90 * scale, 10 * scale,
10 * scale);
break;
}
float size = MathUtils.Min(srcWidth / (1 / cycle.GetPointDistance()),
srcHeight / (1 / cycle.GetPointDistance()));
cycle.SetPadding(padding);
cycle.SetBlockWidth(size + offset);
cycle.SetBlockHeight(size + offset);
cycle.SetWidth(width * scale);
cycle.SetHeight(height * scale);
return cycle;
}
private const long serialVersionUID = -4197405628446701982L;
public const int OTHER = 0, DIM = 1, DEGREE = 2, RADIUS = 3;
public const int BEZIER = 0, ARC = 1, LINE = 2;
protected internal float pointDistance;
protected internal float multiplier;
protected internal int frame, padding;
protected internal int stepType, lineWidth;
protected internal float trailLength, stepsPerFrame;
protected internal bool isUpdate, isVisible, stopped;
protected internal List<object[]> data;
protected static internal Dictionary<Int32, float[]> signatures;
protected internal List<Progress> points;
private LTimer timer;
private Polygon poly;
private LColor color;
private Progress last;
protected internal float scaleX, scaleY;
protected internal float blockWidth, blockHeight, blockHalfWidth, blockHalfHeight;
protected internal float width, height;
public sealed class Anonymous_C1 : Cycle {
private readonly float scale;
private Path path;
public Anonymous_C1(float scale) {
this.scale = scale;
}
public override void Step(GLEx g, float x, float y, float progress,
int index, int frame, LColor color, float alpha) {
float cx = this.padding + 50, cy = this.padding + 50, angle = (MathUtils.PI / 180)
* (progress * 360), innerRadius = (index == 1) ? 10
: 25;
if (path == null) {
path = new Path(GetX() + x * scale, GetY() + y * scale);
} else {
path.Clear();
path.Set(GetX() + x * scale, GetY() + y * scale);
}
path.LineTo(GetX()
+ ((MathUtils.Cos(angle) * innerRadius) + cx)
* scale, GetY()
+ ((MathUtils.Sin(angle) * innerRadius) + cy)
* scale);
path.Close();
g.Draw(path);
}
}
public sealed class Anonymous_C0 : Cycle {
private readonly float scale;
private Path path;
public Anonymous_C0(float scale) {
this.scale = scale;
}
public override void Step(GLEx g, float x, float y, float progress,
int index, int frame, LColor color, float alpha) {
float cx = this.padding + 50, cy = this.padding + 50, angle = (MathUtils.PI / 180)
* (progress * 360);
alpha = MathUtils.Max(0.5f, alpha);
g.SetAlpha(alpha);
if (path == null) {
path = new Path(GetX() + x * scale, GetY() + y * scale);
} else {
path.Clear();
path.Set(GetX() + x * scale, GetY() + y * scale);
}
path.LineTo(GetX() + ((MathUtils.Cos(angle) * 35) + cx)
* scale, GetY()
+ ((MathUtils.Sin(angle) * 35) + cy) * scale);
path.Close();
g.Draw(path);
if (path == null) {
path = new Path(GetX()
+ ((MathUtils.Cos(-angle) * 32) + cx) * scale,
GetY() + ((MathUtils.Sin(-angle) * 32) + cy)
* scale);
} else {
path.Clear();
path.Set(GetX() + ((MathUtils.Cos(-angle) * 32) + cx)
* scale, GetY()
+ ((MathUtils.Sin(-angle) * 32) + cy) * scale);
}
path.LineTo(GetX() + ((MathUtils.Cos(-angle) * 27) + cx)
* scale, GetY()
+ ((MathUtils.Sin(-angle) * 27) + cy) * scale);
path.Close();
g.Draw(path);
g.SetAlpha(1);
}
}
public class Progress {
internal float x;
internal float y;
internal float progress;
public Progress(float x, float y, float p) {
this.x = x;
this.y = y;
this.progress = p;
}
}
public Cycle(): this(0, 0) {
}
public Cycle(int x, int y):this(x, y, 6, 6) {
}
public Cycle(int x, int y, int w, int h):this(null, x, y, w, h) {
}
public Cycle(List<object[]> path, int x, int y, int w, int h) {
if (path != null) {
CollectionUtils.Add(data, CollectionUtils.ToArray(path));
isUpdate = true;
} else {
data = new List<object[]>(10);
}
this.SetLocation(x, y);
this.timer = new LTimer(25);
this.color = LColor.white;
this.points = new List<Progress>();
this.multiplier = 1;
this.pointDistance = 0.05f;
this.padding = 0;
this.stepType = 0;
this.stepsPerFrame = 1;
this.trailLength = 1;
this.scaleX = 1;
this.scaleY = 1;
this.alpha = 1;
this.blockWidth = w;
this.blockHeight = h;
this.blockHalfWidth = w / 2;
this.blockHalfHeight = h / 2;
if (signatures == null) {
signatures = new Dictionary<Int32, float[]>(3);
CollectionUtils.Put(signatures,ARC,new float[] { 1, 1, 3, 2, 2, 0 });
CollectionUtils.Put(signatures,BEZIER,new float[] { 1, 1, 1, 1, 1, 1, 1, 1 });
CollectionUtils.Put(signatures,LINE,new float[] { 1, 1, 1, 1 });
}
this.Setup();
this.isVisible = true;
}
public void Play() {
this.stopped = false;
}
public void IterateFrame() {
this.frame += (int)this.stepsPerFrame;
if (this.frame >= this.points.Count) {
this.frame = 0;
}
}
public void Stop() {
this.stopped = true;
}
public void SetDelay(long delay) {
timer.SetDelay(delay);
}
public long GetDelay() {
return timer.GetDelay();
}
public void AddPath(int type, params float[] f) {
object[] o = new object[2];
o[0] = type;
o[1] = f;
CollectionUtils.Add(data, o);
isUpdate = true;
}
private void Setup() {
if (!isUpdate) {
return;
}
float[] args;
float value_ren;
int index;
foreach (object[] o in data) {
Int32 type = (Int32) o[0];
args = (float[]) o[1];
for (int a = -1, al = args.Length; ++a < al;) {
index = (int)((float[])CollectionUtils.Get(signatures, type))[a];
value_ren = args[a];
switch (index) {
case RADIUS:
value_ren *= this.multiplier;
break;
case DIM:
value_ren *= this.multiplier;
value_ren += this.padding;
break;
case DEGREE:
value_ren *= MathUtils.PI / 180;
break;
}
args[a] = value_ren;
}
CallMethod(type, args);
}
this.isUpdate = false;
}
private void Step(GLEx g, Progress e, int index, int frame,
LColor color, float alpha) {
switch (stepType) {
case 0:
g.FillOval(X() + e.x - blockHalfWidth, Y() + e.y - blockHalfHeight,
blockWidth, blockHeight);
break;
case 1:
g.FillRect(X() + e.x - blockHalfWidth, Y() + e.y - blockHalfHeight,
blockWidth, blockHeight);
break;
case 2:
if (last != null) {
float[] xs = { X() + last.x, X() + e.x };
float[] ys = { Y() + last.y, Y() + e.y };
g.DrawPolygon(xs, ys, 2);
}
last = e;
break;
case 3:
if (last != null) {
g.DrawLine(X() + last.x, Y() + last.y, X() + e.x, Y() + e.y);
}
last = e;
break;
case 4:
Step(g, e.x, e.y, e.progress, index, frame, color, alpha);
break;
}
}
public virtual void Step(GLEx g, float x, float y, float progress, int index,
int frame, LColor color, float alpha) {
}
public override void Update(long elapsedTime) {
if (timer.Action(elapsedTime)) {
this.IterateFrame();
}
}
private void CallMethod(int index, params float[] f) {
float[] result;
for (float pd = this.pointDistance, t = pd; t <= 1; t += pd) {
t = MathUtils.Round(t * 1f / pd) / (1f / pd);
switch (index) {
case BEZIER:
result = Bezier(t, f[0], f[1], f[2], f[3], f[4], f[5], f[6],
f[7]);
break;
case ARC:
result = Arc(t, f[0], f[1], f[2], f[3], f[4]);
break;
case LINE:
result = Line(t, f[0], f[1], f[2], f[3]);
break;
default:
result = new float[] { 0f, 0f };
break;
}
CollectionUtils.Add(points,new Progress(result[0], result[1], t));
}
}
private float[] Bezier(float t, float p0x, float p0y, float p1x,
float p1y, float c0x, float c0y, float c1x, float c1y) {
t = 1 - t;
float i = 1 - t, x = t * t, y = i * i, a = x * t, b = 3 * x * i, c = 3
* t * y, d = y * i;
return new float[] { a * p0x + b * c0x + c * c1x + d * p1x,
a * p0y + b * c0y + c * c1y + d * p1y };
}
private float[] Arc(float t, float cx, float cy, float radius,
float start, float end) {
float point = (end - start) * t + start;
return new float[] { (MathUtils.Cos(point) * radius) + cx,
(MathUtils.Sin(point) * radius) + cy };
}
private float[] Line(float t, float sx, float sy, float ex, float ey) {
return new float[] { (ex - sx) * t + sx, (ey - sy) * t + sy };
}
public void CreateUI(GLEx g) {
if (!isVisible) {
return;
}
this.Setup();
int pointsLength = points.Count;
Progress point;
int index;
int frameD;
int indexD;
float size = (pointsLength * this.trailLength);
for (float i = -1, l = size; ++i < l && !this.stopped;) {
index = (int) (frame + i);
if (index < pointsLength) {
point = points[index];
} else {
point = points[index - pointsLength];
}
this.alpha = (i / (l - 1));
frameD = frame / (pointsLength - 1);
indexD = (int) alpha;
if (lineWidth > 0) {
g.SetLineWidth(lineWidth);
}
if (scaleX != 1 || scaleY != 1) {
g.Scale(scaleX, scaleY);
}
if (alpha > 0 && alpha < 1) {
g.SetAlpha(alpha);
}
g.SetColor(color);
Step(g, point, indexD, frameD, color, alpha);
g.ResetColor();
if (alpha > 0 && alpha < 1) {
g.SetAlpha(1);
}
if (lineWidth > 0) {
g.ResetLineWidth();
}
if (scaleX != 1 || scaleY != 1) {
g.Restore();
}
}
}
public LColor GetColor() {
return color;
}
public void SetColor(LColor color) {
this.color = color;
}
public void SetColor(uint pixel) {
this.color.SetARGB(pixel);
}
public List<object[]> GetData() {
return data;
}
public void SetData(List<object[]> data) {
this.data = data;
}
public int GetFrame() {
return frame;
}
public void SetFrame(int frame) {
this.frame = frame;
}
public bool IsUpdate() {
return isUpdate;
}
public void SetUpdate(bool isUpdate) {
this.isUpdate = isUpdate;
}
public Progress GetLast() {
return last;
}
public void SetLast(Progress last) {
this.last = last;
}
public int GetLineWidth() {
return lineWidth;
}
public void SetLineWidth(int lineWidth) {
this.lineWidth = lineWidth;
}
public float GetMultiplier() {
return multiplier;
}
public void SetMultiplier(float multiplier) {
this.multiplier = multiplier;
}
public int GetPadding() {
return padding;
}
public void SetPadding(int padding) {
this.padding = padding;
}
public float GetPointDistance() {
return pointDistance;
}
public void SetPointDistance(float pointDistance) {
this.pointDistance = pointDistance;
}
public List<Progress> GetPoints() {
return points;
}
public void SetPoints(List<Progress> points) {
this.points = points;
}
public float GetScaleX() {
return scaleX;
}
public void SetScaleX(float scaleX) {
this.scaleX = scaleX;
}
public float GetScaleY() {
return scaleY;
}
public void SetScaleY(float scaleY) {
this.scaleY = scaleY;
}
public float GetStepsPerFrame() {
return stepsPerFrame;
}
public void SetStepsPerFrame(float stepsPerFrame) {
this.stepsPerFrame = stepsPerFrame;
}
public int GetStepType() {
return stepType;
}
public void SetStepType(int stepType) {
this.stepType = stepType;
}
public bool IsStopped() {
return stopped;
}
public float GetTrailLength() {
return trailLength;
}
public void SetTrailLength(float trailLength) {
this.trailLength = trailLength;
}
public int GetBlockHeight() {
return (int) blockHeight;
}
public void SetBlockHeight(float blockHeight) {
this.blockHeight = blockHeight;
this.blockHalfHeight = blockHeight / 2;
}
public int GetBlockWidth() {
return (int) blockWidth;
}
public void SetBlockWidth(float blockWidth) {
this.blockWidth = blockWidth;
this.blockHalfWidth = blockWidth / 2;
}
public LTexture GetBitmap() {
return null;
}
public Shape GetShape() {
if (isUpdate) {
Setup();
poly = new Polygon();
foreach (Progress point in points) {
poly.AddPoint(point.x, point.y);
}
}
return poly;
}
public RectBox GetCollisionBox() {
Shape shape = GetShape();
return GetRect(shape.GetX(), shape.GetY(), shape.GetWidth(),
shape.GetHeight());
}
public void SetWidth(float w) {
this.width = w;
}
public void SetHeight(float h) {
this.height = h;
}
public override int GetWidth() {
return (int) height;
}
public override int GetHeight()
{
return (int) width;
}
public bool IsVisible() {
return isVisible;
}
public void SetVisible(bool visible) {
this.isVisible = visible;
}
public void Dispose() {
}
}
}
| |
using Lucene.Net.Support.IO;
using Lucene.Net.Util;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace Lucene.Net.Store
{
/*
* 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.
*/
/// <summary>
/// Base <see cref="IndexInput"/> implementation that uses an array
/// of <see cref="ByteBuffer"/>s to represent a file.
/// <para/>
/// Because Java's <see cref="ByteBuffer"/> uses an <see cref="int"/> to address the
/// values, it's necessary to access a file greater
/// <see cref="int.MaxValue"/> in size using multiple byte buffers.
/// <para/>
/// For efficiency, this class requires that the buffers
/// are a power-of-two (<c>chunkSizePower</c>).
/// </summary>
public abstract class ByteBufferIndexInput : IndexInput
{
private ByteBuffer[] buffers;
private readonly long chunkSizeMask;
private readonly int chunkSizePower;
private int offset;
private long length;
private string sliceDescription;
private int curBufIndex;
private ByteBuffer curBuf; // redundant for speed: buffers[curBufIndex]
private bool isClone = false;
private readonly WeakIdentityMap<ByteBufferIndexInput, BoolRefWrapper> clones;
private class BoolRefWrapper
{
// .NET port: this is needed as bool is not a reference type
public BoolRefWrapper(bool value)
{
this.Value = value;
}
public bool Value { get; private set; }
}
internal ByteBufferIndexInput(string resourceDescription, ByteBuffer[] buffers, long length, int chunkSizePower, bool trackClones)
: base(resourceDescription)
{
//this.buffers = buffers; // LUCENENET: this is set in SetBuffers()
this.length = length;
this.chunkSizePower = chunkSizePower;
this.chunkSizeMask = (1L << chunkSizePower) - 1L;
this.clones = trackClones ? WeakIdentityMap<ByteBufferIndexInput, BoolRefWrapper>.NewConcurrentHashMap() : null;
Debug.Assert(chunkSizePower >= 0 && chunkSizePower <= 30);
Debug.Assert(((long)((ulong)length >> chunkSizePower)) < int.MaxValue);
// LUCENENET specific: MMapIndexInput calls SetBuffers() to populate
// the buffers, so we need to skip that call if it is null here, and
// do the seek inside SetBuffers()
if (buffers != null)
{
SetBuffers(buffers);
}
}
// LUCENENET specific for encapsulating buffers field.
internal void SetBuffers(ByteBuffer[] buffers) // necessary for MMapIndexInput
{
this.buffers = buffers;
Seek(0L);
}
public override sealed byte ReadByte()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.HasRemaining)
{
return curBuf.Get();
}
do
{
curBufIndex++;
if (curBufIndex >= buffers.Length)
{
throw new EndOfStreamException("read past EOF: " + this);
}
curBuf = buffers[curBufIndex];
curBuf.Position = 0;
} while (!curBuf.HasRemaining);
return curBuf.Get();
}
public override sealed void ReadBytes(byte[] b, int offset, int len)
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
int curAvail = curBuf.Remaining;
if (len <= curAvail)
{
curBuf.Get(b, offset, len);
}
else
{
while (len > curAvail)
{
curBuf.Get(b, offset, curAvail);
len -= curAvail;
offset += curAvail;
curBufIndex++;
if (curBufIndex >= buffers.Length)
{
throw new EndOfStreamException("read past EOF: " + this);
}
curBuf = buffers[curBufIndex];
curBuf.Position = 0;
curAvail = curBuf.Remaining;
}
curBuf.Get(b, offset, len);
}
}
/// <summary>
/// NOTE: this was readShort() in Lucene
/// </summary>
public override sealed short ReadInt16()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.Remaining >= 2)
{
return curBuf.GetInt16();
}
return base.ReadInt16();
}
/// <summary>
/// NOTE: this was readInt() in Lucene
/// </summary>
public override sealed int ReadInt32()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.Remaining >= 4)
{
return curBuf.GetInt32();
}
return base.ReadInt32();
}
/// <summary>
/// NOTE: this was readLong() in Lucene
/// </summary>
public override sealed long ReadInt64()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
if (curBuf.Remaining >= 8)
{
return curBuf.GetInt64();
}
return base.ReadInt64();
}
public override sealed long GetFilePointer()
{
// LUCENENET: Refactored to avoid calls on invalid conditions instead of
// catching and re-throwing exceptions in the normal workflow.
EnsureOpen();
return (((long)curBufIndex) << chunkSizePower) + curBuf.Position - offset;
}
public override sealed void Seek(long pos)
{
// necessary in case offset != 0 and pos < 0, but pos >= -offset
if (pos < 0L)
{
throw new ArgumentException("Seeking to negative position: " + this);
}
pos += offset;
// we use >> here to preserve negative, so we will catch AIOOBE,
// in case pos + offset overflows.
int bi = (int)(pos >> chunkSizePower);
try
{
ByteBuffer b = buffers[bi];
b.Position = ((int)(pos & chunkSizeMask));
// write values, on exception all is unchanged
this.curBufIndex = bi;
this.curBuf = b;
}
catch (IndexOutOfRangeException)
{
throw new EndOfStreamException("seek past EOF: " + this);
}
catch (ArgumentException)
{
throw new EndOfStreamException("seek past EOF: " + this);
}
catch (NullReferenceException)
{
throw new ObjectDisposedException(this.GetType().FullName, "Already closed: " + this);
}
}
public override sealed long Length
{
get { return length; }
}
public override sealed object Clone()
{
ByteBufferIndexInput clone = BuildSlice(0L, this.length);
try
{
clone.Seek(GetFilePointer());
}
catch (IOException ioe)
{
throw new Exception("Should never happen: " + this, ioe);
}
return clone;
}
/// <summary>
/// Creates a slice of this index input, with the given description, offset, and length. The slice is seeked to the beginning.
/// </summary>
public ByteBufferIndexInput Slice(string sliceDescription, long offset, long length)
{
if (isClone) // well we could, but this is stupid
{
throw new InvalidOperationException("cannot slice() " + sliceDescription + " from a cloned IndexInput: " + this);
}
ByteBufferIndexInput clone = BuildSlice(offset, length);
clone.sliceDescription = sliceDescription;
try
{
clone.Seek(0L);
}
catch (IOException ioe)
{
throw new Exception("Should never happen: " + this, ioe);
}
return clone;
}
private ByteBufferIndexInput BuildSlice(long offset, long length)
{
if (buffers == null)
{
throw new ObjectDisposedException(this.GetType().FullName, "Already closed: " + this);
}
if (offset < 0 || length < 0 || offset + length > this.length)
{
throw new ArgumentException("slice() " + sliceDescription + " out of bounds: offset=" + offset + ",length=" + length + ",fileLength=" + this.length + ": " + this);
}
// include our own offset into the final offset:
offset += this.offset;
ByteBufferIndexInput clone = (ByteBufferIndexInput)base.Clone();
clone.isClone = true;
// we keep clone.clones, so it shares the same map with original and we have no additional cost on clones
Debug.Assert(clone.clones == this.clones);
clone.buffers = BuildSlice(buffers, offset, length);
clone.offset = (int)(offset & chunkSizeMask);
clone.length = length;
// register the new clone in our clone list to clean it up on closing:
if (clones != null)
{
this.clones.Put(clone, new BoolRefWrapper(true));
}
return clone;
}
/// <summary>
/// Returns a sliced view from a set of already-existing buffers:
/// the last buffer's <see cref="Support.IO.Buffer.Limit"/> will be correct, but
/// you must deal with <paramref name="offset"/> separately (the first buffer will not be adjusted)
/// </summary>
private ByteBuffer[] BuildSlice(ByteBuffer[] buffers, long offset, long length)
{
long sliceEnd = offset + length;
int startIndex = (int)((long)((ulong)offset >> chunkSizePower));
int endIndex = (int)((long)((ulong)sliceEnd >> chunkSizePower));
// we always allocate one more slice, the last one may be a 0 byte one
ByteBuffer[] slices = new ByteBuffer[endIndex - startIndex + 1];
for (int i = 0; i < slices.Length; i++)
{
slices[i] = buffers[startIndex + i].Duplicate();
}
// set the last buffer's limit for the sliced view.
slices[slices.Length - 1].Limit = ((int)(sliceEnd & chunkSizeMask));
return slices;
}
private void UnsetBuffers()
{
buffers = null;
curBuf = null;
curBufIndex = 0;
}
// LUCENENET specific - rather than using all of this exception catching nonsense
// for control flow, we check whether we are disposed first.
private void EnsureOpen()
{
if (buffers == null || curBuf == null)
{
throw new ObjectDisposedException(this.GetType().FullName, "Already closed: " + this);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
if (buffers == null)
{
return;
}
// make local copy, then un-set early
ByteBuffer[] bufs = buffers;
UnsetBuffers();
if (clones != null)
{
clones.Remove(this);
}
if (isClone)
{
return;
}
// for extra safety unset also all clones' buffers:
if (clones != null)
{
foreach (ByteBufferIndexInput clone in clones.Keys)
{
clone.UnsetBuffers();
}
this.clones.Clear();
}
foreach (ByteBuffer b in bufs)
{
FreeBuffer(b);
}
}
finally
{
UnsetBuffers();
}
}
}
/// <summary>
/// Called when the contents of a buffer will be no longer needed.
/// </summary>
protected abstract void FreeBuffer(ByteBuffer b);
public override sealed string ToString()
{
if (sliceDescription != null)
{
return base.ToString() + " [slice=" + sliceDescription + "]";
}
else
{
return base.ToString();
}
}
}
}
| |
// 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.
//
// These helper methods are known to a NUTC intrinsic used to implement the Comparer<T> class.
// the compiler will instead replace the IL code within get_Default to call one of GetUnknownComparer, GetKnownGenericComparer,
// GetKnownNullableComparer, GetKnownEnumComparer or GetKnownObjectComparer based on what sort of
// type is being compared.
using System;
using System.Collections.Generic;
using System.Runtime;
using Internal.IntrinsicSupport;
using Internal.Runtime.Augments;
namespace Internal.IntrinsicSupport
{
internal static class ComparerHelpers
{
private static bool ImplementsIComparable(RuntimeTypeHandle t)
{
EETypePtr objectType = t.ToEETypePtr();
EETypePtr icomparableType = typeof(IComparable<>).TypeHandle.ToEETypePtr();
int interfaceCount = objectType.Interfaces.Count;
for (int i = 0; i < interfaceCount; i++)
{
EETypePtr interfaceType = objectType.Interfaces[i];
if (!interfaceType.IsGeneric)
continue;
if (interfaceType.GenericDefinition == icomparableType)
{
var instantiation = interfaceType.Instantiation;
if (instantiation.Length != 1)
continue;
if (objectType.IsValueType)
{
if (instantiation[0] == objectType)
{
return true;
}
}
else if (RuntimeImports.AreTypesAssignable(objectType, instantiation[0]))
{
return true;
}
}
}
return false;
}
private static object GetComparer(RuntimeTypeHandle t)
{
RuntimeTypeHandle comparerType;
RuntimeTypeHandle openComparerType = default(RuntimeTypeHandle);
RuntimeTypeHandle comparerTypeArgument = default(RuntimeTypeHandle);
if (RuntimeAugments.IsNullable(t))
{
RuntimeTypeHandle nullableType = RuntimeAugments.GetNullableType(t);
if (ImplementsIComparable(nullableType))
{
openComparerType = typeof(NullableComparer<>).TypeHandle;
comparerTypeArgument = nullableType;
}
}
if (openComparerType.Equals(default(RuntimeTypeHandle)))
{
if (ImplementsIComparable(t))
{
openComparerType = typeof(GenericComparer<>).TypeHandle;
comparerTypeArgument = t;
}
else
{
openComparerType = typeof(ObjectComparer<>).TypeHandle;
comparerTypeArgument = t;
}
}
bool success = RuntimeAugments.TypeLoaderCallbacks.TryGetConstructedGenericTypeForComponents(openComparerType, new RuntimeTypeHandle[] { comparerTypeArgument }, out comparerType);
if (!success)
{
Environment.FailFast("Unable to create comparer");
}
return RuntimeAugments.NewObject(comparerType);
}
internal static Comparer<T> GetUnknownComparer<T>()
{
return (Comparer<T>)GetComparer(typeof(T).TypeHandle);
}
private static Comparer<T> GetKnownGenericComparer<T>() where T : IComparable<T>
{
return new GenericComparer<T>();
}
private static Comparer<Nullable<U>> GetKnownNullableComparer<U>() where U : struct, IComparable<U>
{
return new NullableComparer<U>();
}
private static Comparer<T> GetKnownObjectComparer<T>()
{
return new ObjectComparer<T>();
}
// This routine emulates System.Collection.Comparer.Default.Compare(), which lives in the System.Collections.NonGenerics contract.
// To avoid adding a reference to that contract just for this hack, we'll replicate the implementation here.
internal static int CompareObjects(object x, object y)
{
if (x == y)
return 0;
if (x == null)
return -1;
if (y == null)
return 1;
{
// System.Collection.Comparer.Default.Compare() compares strings using the CurrentCulture.
string sx = x as string;
string sy = y as string;
if (sx != null && sy != null)
return string.Compare(sx, sy, StringComparison.CurrentCulture);
}
IComparable ix = x as IComparable;
if (ix != null)
return ix.CompareTo(y);
IComparable iy = y as IComparable;
if (iy != null)
return -iy.CompareTo(x);
throw new ArgumentException(SR.Argument_ImplementIComparable);
}
}
}
namespace System.Collections.Generic
{
//-----------------------------------------------------------------------
// Implementations of EqualityComparer<T> for the various possible scenarios
// Because these are serializable, they must not be renamed
//-----------------------------------------------------------------------
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T>
{
public sealed override int Compare(T x, T y)
{
if (x != null)
{
if (y != null)
return x.CompareTo(y);
return 1;
}
if (y != null)
return -1;
return 0;
}
// Equals method for the comparer itself.
public sealed override bool Equals(Object obj) => obj != null && GetType() == obj.GetType();
public sealed override int GetHashCode() => GetType().GetHashCode();
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class NullableComparer<T> : Comparer<Nullable<T>> where T : struct, IComparable<T>
{
public sealed override int Compare(Nullable<T> x, Nullable<T> y)
{
if (x.HasValue)
{
if (y.HasValue)
return x.Value.CompareTo(y.Value);
return 1;
}
if (y.HasValue)
return -1;
return 0;
}
// Equals method for the comparer itself.
public sealed override bool Equals(Object obj) => obj != null && GetType() == obj.GetType();
public sealed override int GetHashCode() => GetType().GetHashCode();
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class ObjectComparer<T> : Comparer<T>
{
public sealed override int Compare(T x, T y)
{
return ComparerHelpers.CompareObjects(x, y);
}
// Equals method for the comparer itself.
public sealed override bool Equals(Object obj) => obj != null && GetType() == obj.GetType();
public sealed override int GetHashCode() => GetType().GetHashCode();
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// 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.Collections.Generic;
using System.Text;
using NUnit.Framework;
using gov.va.medora.TOReflection;
using System.Collections.Specialized;
using gov.va.medora.utils;
using gov.va.medora.mdo.exceptions;
namespace gov.va.medora.mdo.dao.vista
{
[TestFixture]
public class VistaUtilsTest
{
[Test]
public void adjustForNameSearch()
{
string target = "hans tischner";
string result = VistaUtils.adjustForNameSearch(target);
Assert.AreEqual("hans tischneq~", result);
target = "sam two toes";
result = VistaUtils.adjustForNameSearch(target);
Assert.AreEqual("sam two toer~", result);
target = "1234";
result = VistaUtils.adjustForNameSearch(target);
Assert.AreEqual("1233~", result);
target = "!@#$%^&*()";
result = VistaUtils.adjustForNameSearch(target);
Assert.AreEqual("!@#$%^&*((~", result);
}
[Test]
public void adjustForNameSearch_Emtpy()
{
string target = "";
string result = VistaUtils.adjustForNameSearch(target);
Assert.AreEqual("", result);
}
[Test]
[ExpectedException("System.NullReferenceException")]
public void adjustForNameSearch_Null()
{
string target = null;
string result = VistaUtils.adjustForNameSearch(target);
Assert.IsNull(result);
}
[Test]
public void adjustForNumericSearch()
{
string target = "404";
string result = VistaUtils.adjustForNumericSearch(target);
Assert.AreEqual("403", result);
}
[Test]
[ExpectedException("System.FormatException")]
public void adjustForNumericSearch_Empty()
{
string target = "";
string result = VistaUtils.adjustForNumericSearch(target);
Assert.IsNull(result);
}
[Test]
[ExpectedException("System.FormatException")]
public void adjustForNumericSearch_NAN()
{
string target = "asdfjk12";
string result = VistaUtils.adjustForNumericSearch(target);
Assert.IsNull(result);
}
[Test]
public void adjustForNumericSearch_Null()
{
string target = null;
string result = VistaUtils.adjustForNumericSearch(target);
Assert.AreEqual("-1", result);
}
[Test]
public void setDirectionParam()
{
string target = null;
string result = VistaUtils.setDirectionParam(target);
Assert.AreEqual("1", result);
target = "";
result = VistaUtils.setDirectionParam(target);
Assert.AreEqual("1", result);
target = "1";
result = VistaUtils.setDirectionParam(target);
Assert.AreEqual("1", result);
target = "-1";
result = VistaUtils.setDirectionParam(target);
Assert.AreEqual("-1", result);
}
[Test]
[ExpectedException(typeof(MdoException), "Invalid direction. Must be 1 or -1.")]
public void setDirectionParam_Not1orMinus1()
{
string target = "left";
VistaUtils.setDirectionParam(target);
}
[Test]
[ExpectedException(typeof(InvalidlyFormedRecordIdException), "Invalidly formed record ID: abcdefg")]
public void buildReportTextRequest_InvalidDfn()
{
VistaUtils.buildReportTextRequest("abcdefg", "20061219.122200", "20071219.122200", 10, "some report");
}
[Test]
[ExpectedException(typeof(InvalidlyFormedRecordIdException), "Invalidly formed record ID: ")]
public void buildReportTextRequest_EmptyDfn()
{
VistaUtils.buildReportTextRequest("", "20061219.122200", "20071219.122200", 10, "some report");
}
[Test]
[ExpectedException(typeof(InvalidlyFormedRecordIdException), "Invalidly formed record ID: ")]
public void buildReportTextRequest_NullDfn()
{
VistaUtils.buildReportTextRequest(null, "20061219.122200", "20071219.122200", 10, "some report");
}
[Test]
[ExpectedException(typeof(InvalidDateRangeException), "Invalid date range")]
public void buildReportTextRequest_InvalidRange()
{
VistaUtils.buildReportTextRequest("1234567", "20071219.122200", "20061219.122200", 10, "some report");
}
[Test]
[ExpectedException(typeof(NullOrEmptyParamException), "Null or empty input parameter: routine name")]
public void buildReportTextRequest_EmptyArg()
{
VistaUtils.buildReportTextRequest("1234567", "20061219.122200", "20071219.122200", 10, "");
}
[Test]
[ExpectedException(typeof(NullOrEmptyParamException), "Null or empty input parameter: routine name")]
public void buildReportTextRequest_NullArg()
{
VistaUtils.buildReportTextRequest("1234567", "20061219.122200", "20071219.122200", 10, null);
}
[Test]
[ExpectedException(typeof(InvalidlyFormedRecordIdException), "Invalidly formed record ID: ")]
public void buildReportTextRequest_AllResults_EmptyDfn()
{
VistaUtils.buildReportTextRequest_AllResults("", "some report");
}
[Test]
[ExpectedException(typeof(InvalidlyFormedRecordIdException), "Invalidly formed record ID: ")]
public void buildReportTextRequest_AllResults_NullDfn()
{
VistaUtils.buildReportTextRequest_AllResults(null, "some report");
}
[Test]
[ExpectedException(typeof(InvalidlyFormedRecordIdException), "Invalidly formed record ID: abcd")]
public void buildReportTextRequest_AllResults_BadDfn()
{
VistaUtils.buildReportTextRequest_AllResults("abcd", "some report");
}
[Test]
[ExpectedException(typeof(NullOrEmptyParamException), "Null or empty input parameter: routine name")]
public void buildReportTextRequest_AllResults_EmptyArg()
{
VistaUtils.buildReportTextRequest_AllResults("1234567", "");
}
[Test]
[ExpectedException(typeof(NullOrEmptyParamException), "Null or empty input parameter: routine name")]
public void buildReportTextRequest_AllResults_NullArg()
{
VistaUtils.buildReportTextRequest_AllResults("1234567", null);
}
[Test]
public void responseOrOk()
{
Assert.AreEqual("OK", VistaUtils.responseOrOk(""));
Assert.AreEqual("special response", VistaUtils.responseOrOk("special response"));
}
[Test]
public void errMsgOrOK()
{
string response = "0^my error^is^not^your error";
Assert.AreEqual("my error", VistaUtils.errMsgOrOK(response));
response = "1^this should be^ok";
Assert.AreEqual("OK", VistaUtils.errMsgOrOK(response));
}
[Test]
[ExpectedException("System.IndexOutOfRangeException","Index was outside the bounds of the array.")]
public void errMsgOrOK_1Field()
{
string response = "no error code";
VistaUtils.errMsgOrOK(response);
}
[Test]
public void errMsgOr0()
{
string response = "1^my error^is^not^your error";
Assert.AreEqual("my error", VistaUtils.errMsgOrZero(response));
response = "0^this should be^ok";
Assert.AreEqual("OK", VistaUtils.errMsgOrZero(response));
}
[Test]
[ExpectedException("System.IndexOutOfRangeException", "Index was outside the bounds of the array.")]
public void errMsgOr0_1Field()
{
string response = "no error code";
VistaUtils.errMsgOrZero(response);
}
[Test]
public void errMsgOrIen()
{
string response = "7008";
Assert.AreEqual(response, VistaUtils.errMsgOrIen(response));
}
[Test]
[ExpectedException("System.ArgumentException", "Non-numeric IEN")]
public void errMsgOrIen_Nan()
{
string response = "no error code";
VistaUtils.errMsgOrIen(response);
}
[Test]
[ExpectedException("System.ArgumentException", "Non-numeric IEN")]
public void errMsgOrIen_Null()
{
VistaUtils.errMsgOrIen(null);
}
[Test]
public void errMsgOrIen_Empty()
{
Assert.AreEqual("", VistaUtils.errMsgOrIen(""));
}
[Test]
public void testRemoveCtlChars()
{
string s = "A\x0009B _~\\1\x000A\x000D2\x0001Cv\x001Aend";
string result = VistaUtils.removeCtlChars(s);
Assert.AreEqual("A\tB _~\\1\n\r2Cvend", result);
}
[Test]
public void testRemoveCtlChars_Null()
{
string result = VistaUtils.removeCtlChars(null);
Assert.AreEqual("", result);
}
[Test]
public void testRemoveCtlChars_Empty()
{
string result = VistaUtils.removeCtlChars("");
Assert.AreEqual("", result);
}
/// <summary>
/// Current functionality only worked up to Int32 -- this caused problems with
/// things like larger DFNS
/// </summary>
[Test]
[Category("unit-only")]
public void TestAdjustForNumericSearchInt64()
{
string longDfn = "5587247575";
string output = VistaUtils.adjustForNumericSearch(longDfn);
Assert.AreEqual("5587247574", output);
}
[Test]
public void getVistaName()
{
Assert.AreEqual("", VistaUtils.getVistaName(""));
Assert.AreEqual("", VistaUtils.getVistaName(null));
Assert.AreEqual("", VistaUtils.getVistaName("joe shmoe"));
Assert.AreEqual("", VistaUtils.getVistaName("shmoe,joe,bob"));
Assert.AreEqual("SHMOE,JOE", VistaUtils.getVistaName("shmoe,joe"));
Assert.AreEqual("", VistaUtils.getVistaName("2shmoe,joe"));
}
[Test]
public void getVistaGender()
{
Assert.AreEqual("", VistaUtils.getVistaGender(""));
Assert.AreEqual("", VistaUtils.getVistaGender(null));
Assert.AreEqual("", VistaUtils.getVistaGender("joe shmoe"));
Assert.AreEqual("", VistaUtils.getVistaGender("shmoe,joe,bob"));
Assert.AreEqual("", VistaUtils.getVistaGender("2shmoe,joe"));
Assert.AreEqual("M", VistaUtils.getVistaGender("mshmoe,joe"));
Assert.AreEqual("M", VistaUtils.getVistaGender("Mshmoe,joe"));
Assert.AreEqual("F", VistaUtils.getVistaGender("fshmoe,jane"));
Assert.AreEqual("F", VistaUtils.getVistaGender("Fshmoe,jane"));
}
[Test]
public void getVisitString()
{
Encounter x = new Encounter();
x.LocationId = "my location id";
x.Timestamp = "20101118.140400";
x.Type = "the third kind";
Assert.AreEqual("my location id;3101118.140400;the third kind", VistaUtils.getVisitString(x));
}
[Test]
[ExpectedException("System.FormatException","Input string was not in a correct format.")]
public void getVisitString_BadTS()
{
Encounter x = new Encounter();
x.LocationId = "my location id";
x.Timestamp = "hubahub";
x.Type = "the third kind";
VistaUtils.getVisitString(x);
}
[Test]
public void toStringDictionary()
{
Assert.IsNull(VistaUtils.toStringDictionary(null));
Assert.IsNull(VistaUtils.toStringDictionary(new String[] {}));
StringDictionary expected = new StringDictionary();
expected.Add("lower1", "lower1value");
expected.Add("lower2", "lower2value");
expected.Add("lower3", "lower3value");
StringDictionary result = VistaUtils.toStringDictionary(
new String[] {
"lower1^lower1value",
"lower2^lower2value",
"lower3^lower3value"
}
);
Assert.AreEqual(new TOEqualizer(expected).HashCode, new TOEqualizer(result).HashCode);
}
[Test]
[ExpectedException("System.IndexOutOfRangeException", "Index was outside the bounds of the array.")]
public void toStringDictionary_BadResponse()
{
VistaUtils.toStringDictionary(
new String[] {
"nokeyvalue"
}
);
}
[Test]
[ExpectedException("System.ArgumentException", "Item has already been added. Key in dictionary: 'lower1' Key being added: 'lower1'")]
public void toStringDictionary_DuplicateKeys()
{
VistaUtils.toStringDictionary(
new String[] {
"lower1^lower1value",
"lower2^lower2value",
"LOWER1^LOWER1value"
}
);
}
[Test]
[ExpectedException(typeof(NullOrEmptyParamException), "Null or empty input parameter: arg")]
public void buildGetVariableValueRequestEmptyArg()
{
string arg = "";
Assert.AreEqual(-1273759458, VistaUtils.buildGetVariableValueRequest(arg).buildMessage().GetHashCode());
}
[Test]
[ExpectedException(typeof(MdoException), "Invalid 'from' date: asdf")]
public void buildFromToDateScreenParam_BadFrom()
{
VistaUtils.buildFromToDateScreenParam("asdf", "", 0, 0);
}
[Test]
public void buildFromToDateScreenParam_EmptyFrom()
{
var result = VistaUtils.buildFromToDateScreenParam("", "20081118.140400", 0, 0);
Assert.IsNotNull(result);
Assert.AreEqual("", result);
}
[Test]
[ExpectedException(typeof(MdoException), "Invalid 'to' date: adf")]
public void buildFromToDateScreenParam_BadTo()
{
VistaUtils.buildFromToDateScreenParam("20101118.140400", "adf", 0, 0);
}
[Test]
[ExpectedException(typeof(MdoException), "Invalid 'from' date: ")]
public void buildFromToDateScreenParam_NullFrom()
{
VistaUtils.buildFromToDateScreenParam(null, "", 0, 0);
}
[Test]
public void encrypt()
{
string[] ss = {"12345abcd", "", "%!@*\"#$^@!"};
foreach (string s in ss)
{
string result = VistaUtils.encrypt(s);
Assert.IsNotNull(result);
Assert.AreNotEqual(result, s);
Assert.AreEqual(result.Length, s.Length + 2);
}
}
[Test]
[ExpectedException("System.NullReferenceException","Object reference not set to an instance of an object.")]
public void encrypt_null()
{
VistaUtils.encrypt(null);
}
[Test]
public void isWellFormedDuz()
{
Assert.IsFalse(VistaUtils.isWellFormedDuz(null));
Assert.IsFalse(VistaUtils.isWellFormedDuz("basdf12"));
Assert.IsFalse(VistaUtils.isWellFormedDuz(""));
Assert.IsFalse(VistaUtils.isWellFormedDuz("!@#$%"));
Assert.IsTrue(VistaUtils.isWellFormedDuz("12354"));
}
[Test]
public void reverseKeyValue()
{
StringDictionary sd = new StringDictionary();
sd.Add("1","one");
sd.Add("2","two");
StringDictionary ds = VistaUtils.reverseKeyValue(sd);
foreach (string key in ds.Keys)
{
Assert.IsNotNull(sd[ds[key]]);
}
Assert.IsTrue(ds.ContainsKey("one"));
Assert.IsTrue(ds.ContainsKey("two"));
Assert.AreEqual(ds.Count, sd.Count);
//Hash Code is not stable acrosss .Net Versions
//Assert.AreEqual(1995535015, new TOEqualizer(ds).HashCode);
}
[Test]
[ExpectedException("System.ArgumentException", "Item has already been added. Key in dictionary: 'one' Key being added: 'one'")]
public void reverseKeyValue_ReverseCausesDuplicates()
{
StringDictionary sd = new StringDictionary();
sd.Add("1", "one");
sd.Add("2", "ONE");
VistaUtils.reverseKeyValue(sd);
}
[Test]
[ExpectedException("System.NullReferenceException")]
public void reverseKeyValue_null()
{
VistaUtils.reverseKeyValue(null);
}
[Test]
public void checkValidDFN_EmptyString()
{
string dfn = "";
Assert.IsFalse(VistaUtils.isWellFormedIen(dfn));
}
[Test]
public void checkValidDFN_Decimal()
{
string dfn = "123.234";
Assert.IsTrue(VistaUtils.isWellFormedIen(dfn));
}
[Test]
public void checkValidDFN_Integer()
{
string dfn = "123";
Assert.IsTrue(VistaUtils.isWellFormedIen(dfn));
}
[Test]
public void checkValidDFN_Zero()
{
string dfn = "0";
Assert.IsFalse(VistaUtils.isWellFormedIen(dfn));
}
[Test]
public void checkValidDFN_AlphaNumeric()
{
string dfn = "asdf234234";
Assert.IsFalse(VistaUtils.isWellFormedIen(dfn));
}
[Test]
public void checkValidDFN_Null()
{
string dfn = null;
Assert.IsFalse(VistaUtils.isWellFormedIen(dfn));
}
[Test]
[ExpectedException("gov.va.medora.mdo.exceptions.NullOrEmptyParamException")]
public void testCheckVisitStringEmptyString()
{
VistaUtils.CheckVisitString("");
}
[Test]
[ExpectedException("gov.va.medora.mdo.exceptions.MdoException","Invalid visit string (need 3 semi-colon delimited pieces): 123;456;789;abc;def")]
public void testCheckVisitStringTooManyPiecesString()
{
VistaUtils.CheckVisitString("123;456;789;abc;def");
}
[Test]
[ExpectedException("gov.va.medora.mdo.exceptions.MdoException", "Invalid visit string (need 3 semi-colon delimited pieces): 123456789;abcdef")]
public void testCheckVisitStringTooFewPiecesString()
{
VistaUtils.CheckVisitString("123456789;abcdef");
}
[Test]
[ExpectedException("gov.va.medora.mdo.exceptions.MdoException","Invalid visit string (need 3 semi-colon delimited pieces): 123456789abcdef")]
public void testCheckVisitStringNoPiecesString()
{
VistaUtils.CheckVisitString("123456789abcdef");
}
[Test]
[ExpectedException("gov.va.medora.mdo.exceptions.MdoException", "Invalid visit string (invalid VistA timestamp): 123456789;abcdef;H")]
public void testCheckVisitStringValidMidPieceString()
{
VistaUtils.CheckVisitString("123456789;abcdef;H");
}
[Test]
public void testCheckVisitStringValidString()
{
VistaUtils.CheckVisitString("70;3110502.195436;H");
}
[Test]
[ExpectedException("gov.va.medora.mdo.exceptions.MdoException", "Invalid visit string (type must be 'A', 'H' or 'E'): 70;3110502.195436;Y")]
public void testCheckVisitStringInvalidVisitString()
{
VistaUtils.CheckVisitString("70;3110502.195436;Y");
}
[Test]
[ExpectedException("gov.va.medora.mdo.exceptions.MdoException", "Invalid visit string (invalid location IEN): 70A;3110502.195436;H")]
public void testCheckVisitStringInvalidLocationString()
{
VistaUtils.CheckVisitString("70A;3110502.195436;H");
}
}
}
| |
using System;
using System.Collections;
namespace PhotoManage.MethodTwo
{
/// <summary>
/// Summary description for translation.
/// </summary>
public class translation : Hashtable
{
/// <summary>
///
/// </summary>
public translation()
{
//this.Add(0x8769, "Exif IFD");
//this.Add(0x8825, "Gps IFD");
//this.Add(0xFE, "New Subfile Type");
//this.Add(0xFF, "Subfile Type");
this.Add(0x100, "Image Width");
this.Add(0x101, "Image Height");
//this.Add(0x102, "Bits Per Sample");
// this.Add(0x103, "Compression");
//this.Add(0x106, "Photometric Interp");
//this.Add(0x107, "Thresh Holding");
//this.Add(0x108, "Cell Width");
//this.Add(0x109, "Cell Height");
//this.Add(0x10A, "Fill Order");
//this.Add(0x10D, "Document Name");
//this.Add(0x10E, "Image Description");
this.Add(0x10F, "Equip Make");
//this.Add(0x110, "Equip Model");
//this.Add(0x111, "Strip Offsets");
this.Add(0x112, "Orientation");
this.Add(0x115, "Samples PerPixel");
this.Add(0x116, "Rows Per Strip");
this.Add(0x117, "Strip Bytes Count");
//this.Add(0x118, "Min Sample Value");
//this.Add(0x119, "Max Sample Value");
this.Add(0x11A, "X Resolution");
this.Add(0x11B, "Y Resolution");
//this.Add(0x11C, "Planar Config");
//this.Add(0x11D, "Page Name");
this.Add(0x11E, "X Position");
this.Add(0x11F, "Y Position");
//this.Add(0x120, "Free Offset");
//this.Add(0x121, "Free Byte Counts");
//this.Add(0x122, "Gray Response Unit");
//this.Add(0x123, "Gray Response Curve");
//this.Add(0x124, "T4 Option");
//this.Add(0x125, "T6 Option");
//this.Add(0x128, "Resolution Unit");
//this.Add(0x129, "Page Number");
//this.Add(0x12D, "Transfer Funcition");
//this.Add(0x131, "Software Used");
this.Add(0x132, "Date Time");
//this.Add(0x13B, "Artist");
//this.Add(0x13C, "Host Computer");
//this.Add(0x13D, "Predictor");
//this.Add(0x13E, "White Point");
//this.Add(0x13F, "Primary Chromaticities");
//this.Add(0x140, "ColorMap");
//this.Add(0x141, "Halftone Hints");
//this.Add(0x142, "Tile Width");
//this.Add(0x143, "Tile Length");
//this.Add(0x144, "Tile Offset");
//this.Add(0x145, "Tile ByteCounts");
//this.Add(0x14C, "InkSet");
//this.Add(0x14D, "Ink Names");
//this.Add(0x14E, "Number Of Inks");
//this.Add(0x150, "Dot Range");
//this.Add(0x151, "Target Printer");
//this.Add(0x152, "Extra Samples");
//this.Add(0x153, "Sample Format");
//this.Add(0x154, "S Min Sample Value");
//this.Add(0x155, "S Max Sample Value");
//this.Add(0x156, "Transfer Range");
//this.Add(0x200, "JPEG Proc");
//this.Add(0x201, "JPEG InterFormat");
//this.Add(0x202, "JPEG InterLength");
//this.Add(0x203, "JPEG RestartInterval");
//this.Add(0x205, "JPEG LosslessPredictors");
//this.Add(0x206, "JPEG PointTransforms");
//this.Add(0x207, "JPEG QTables");
//this.Add(0x208, "JPEG DCTables");
//this.Add(0x209, "JPEG ACTables");
//this.Add(0x211, "YCbCr Coefficients");
//this.Add(0x212, "YCbCr Subsampling");
//this.Add(0x213, "YCbCr Positioning");
//this.Add(0x214, "REF Black White");
//this.Add(0x8773, "ICC Profile");
//this.Add(0x301, "Gamma");
//this.Add(0x302, "ICC Profile Descriptor");
//this.Add(0x303, "SRGB RenderingIntent");
this.Add(0x320, "Image Title");
this.Add(0x8298, "Copyright");
//this.Add(0x5001, "Resolution X Unit");
//this.Add(0x5002, "Resolution Y Unit");
//this.Add(0x5003, "Resolution X LengthUnit");
//this.Add(0x5004, "Resolution Y LengthUnit");
//this.Add(0x5005, "Print Flags");
//this.Add(0x5006, "Print Flags Version");
//this.Add(0x5007, "Print Flags Crop");
//this.Add(0x5008, "Print Flags Bleed Width");
//this.Add(0x5009, "Print Flags Bleed Width Scale");
//this.Add(0x500A, "Halftone LPI");
//this.Add(0x500B, "Halftone LPIUnit");
//this.Add(0x500C, "Halftone Degree");
//this.Add(0x500D, "Halftone Shape");
//this.Add(0x500E, "Halftone Misc");
//this.Add(0x500F, "Halftone Screen");
this.Add(0x5010, "JPEG Quality");
//this.Add(0x5011, "Grid Size");
//this.Add(0x5012, "Thumbnail Format");
//this.Add(0x5013, "Thumbnail Width");
//this.Add(0x5014, "Thumbnail Height");
//this.Add(0x5015, "Thumbnail ColorDepth");
//this.Add(0x5016, "Thumbnail Planes");
//this.Add(0x5017, "Thumbnail RawBytes");
//this.Add(0x5018, "Thumbnail Size");
//this.Add(0x5019, "Thumbnail CompressedSize");
//this.Add(0x501A, "Color Transfer Function");
//this.Add(0x501B, "Thumbnail Data");
//this.Add(0x5020, "Thumbnail ImageWidth");
//this.Add(0x502, "Thumbnail ImageHeight");
//this.Add(0x5022, "Thumbnail BitsPerSample");
//this.Add(0x5023, "Thumbnail Compression");
//this.Add(0x5024, "Thumbnail PhotometricInterp");
//this.Add(0x5025, "Thumbnail ImageDescription");
//this.Add(0x5026, "Thumbnail EquipMake");
//this.Add(0x5027, "Thumbnail EquipModel");
//this.Add(0x5028, "Thumbnail StripOffsets");
//this.Add(0x5029, "Thumbnail Orientation");
//this.Add(0x502A, "Thumbnail SamplesPerPixel");
//this.Add(0x502B, "Thumbnail RowsPerStrip");
//this.Add(0x502C, "Thumbnail StripBytesCount");
//this.Add(0x502D, "Thumbnail ResolutionX");
//this.Add(0x502E, "Thumbnail ResolutionY");
//this.Add(0x502F, "Thumbnail PlanarConfig");
//this.Add(0x5030, "Thumbnail ResolutionUnit");
//this.Add(0x5031, "Thumbnail TransferFunction");
//this.Add(0x5032, "Thumbnail SoftwareUsed");
//this.Add(0x5033, "Thumbnail DateTime");
//this.Add(0x5034, "Thumbnail Artist");
//this.Add(0x5035, "Thumbnail WhitePoint");
//this.Add(0x5036, "Thumbnail PrimaryChromaticities");
//this.Add(0x5037, "Thumbnail YCbCrCoefficients");
//this.Add(0x5038, "Thumbnail YCbCrSubsampling");
//this.Add(0x5039, "Thumbnail YCbCrPositioning");
//this.Add(0x503A, "Thumbnail RefBlackWhite");
//this.Add(0x503B, "Thumbnail CopyRight");
//this.Add(0x5090, "Luminance Table");
//this.Add(0x5091, "Chrominance Table");
//this.Add(0x5100, "Frame Delay");
//this.Add(0x5101, "Loop Count");
//this.Add(0x5110, "Pixel Unit");
//this.Add(0x5111, "Pixel PerUnit X");
//this.Add(0x5112, "Pixel PerUnit Y");
//this.Add(0x5113, "Palette Histogram");
//this.Add(0x829A, "Exposure Time");
//this.Add(0x829D, "F-Number");
//this.Add(0x8822, "Exposure Prog");
//this.Add(0x8824, "Spectral Sense");
//this.Add(0x8827, "ISO Speed");
//this.Add(0x8828, "OECF");
//this.Add(0x9000, "Ver");
//this.Add(0x9003, "DTOrig");
//this.Add(0x9004, "DTDigitized");
//this.Add(0x9101, "CompConfig");
//this.Add(0x9102, "CompBPP");
//this.Add(0x9201, "Shutter Speed");
//this.Add(0x9202, "Aperture");
//this.Add(0x9203, "Brightness");
//this.Add(0x9204, "Exposure Bias");
//this.Add(0x9205, "MaxAperture");
//this.Add(0x9206, "SubjectDist");
//this.Add(0x9207, "Metering Mode");
//this.Add(0x9208, "LightSource");
//this.Add(0x9209, "Flash");
//this.Add(0x920A, "FocalLength");
//this.Add(0x927C, "Maker Note");
//this.Add(0x9286, "User Comment");
//this.Add(0x9290, "DTSubsec");
//this.Add(0x9291, "DTOrigSS");
//this.Add(0x9292, "DTDigSS");
//this.Add(0xA000, "FPXVer");
//this.Add(0xA001, "ColorSpace");
//this.Add(0xA002, "PixXDim");
//this.Add(0xA003, "PixYDim");
//this.Add(0xA004, "RelatedWav");
//this.Add(0xA005, "Interop");
//this.Add(0xA20B, "FlashEnergy");
//this.Add(0xA20C, "SpatialFR");
//this.Add(0xA20E, "FocalXRes");
//this.Add(0xA20F, "FocalYRes");
//this.Add(0xA210, "FocalResUnit");
//this.Add(0xA214, "Subject Loc");
//this.Add(0xA215, "Exposure Index");
//this.Add(0xA217, "Sensing Method");
//this.Add(0xA300, "FileSource");
//this.Add(0xA301, "SceneType");
//this.Add(0xA302, "CfaPattern");
//this.Add(0x0, "Gps Ver");
//this.Add(0x1, "Gps LatitudeRef");
//this.Add(0x2, "Gps Latitude");
//this.Add(0x3, "Gps LongitudeRef");
//this.Add(0x4, "Gps Longitude");
//this.Add(0x5, "Gps AltitudeRef");
//this.Add(0x6, "Gps Altitude");
//this.Add(0x7, "Gps GpsTime");
//this.Add(0x8, "Gps GpsSatellites");
//this.Add(0x9, "Gps GpsStatus");
//this.Add(0xA, "Gps GpsMeasureMode");
//this.Add(0xB, "Gps GpsDop");
//this.Add(0xC, "Gps SpeedRef");
//this.Add(0xD, "Gps Speed");
//this.Add(0xE, "Gps TrackRef");
//this.Add(0xF, "Gps Track");
//this.Add(0x10, "Gps ImgDirRef");
//this.Add(0x11, "Gps ImgDir");
//this.Add(0x12, "Gps MapDatum");
//this.Add(0x13, "Gps DestLatRef");
//this.Add(0x14, "Gps DestLat");
//this.Add(0x15, "Gps DestLongRef");
//this.Add(0x16, "Gps DestLong");
//this.Add(0x17, "Gps DestBearRef");
//this.Add(0x18, "Gps DestBear");
//this.Add(0x19, "Gps DestDistRef");
//this.Add(0x1A, "Gps DestDist");
}
}
/// <summary>
/// private class
/// </summary>
internal class Rational
{
private int n;
private int d;
public Rational(int n, int d)
{
this.n = n;
this.d = d;
simplify(ref this.n, ref this.d);
}
public Rational(uint n, uint d)
{
this.n = Convert.ToInt32(n);
this.d = Convert.ToInt32(d);
simplify(ref this.n, ref this.d);
}
public Rational()
{
this.n = this.d = 0;
}
public string ToString(string sp)
{
if (sp == null) sp = "/";
return n.ToString() + sp + d.ToString();
}
public double ToDouble()
{
if (d == 0)
return 0.0;
return Math.Round(Convert.ToDouble(n) / Convert.ToDouble(d), 2);
}
private void simplify(ref int a, ref int b)
{
if (a == 0 || b == 0)
return;
int gcd = euclid(a, b);
a /= gcd;
b /= gcd;
}
private int euclid(int a, int b)
{
if (b == 0)
return a;
else
return euclid(b, a % b);
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.14.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google Cloud Billing API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/billing/'>Google Cloud Billing API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20151222 (355)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/billing/'>
* https://cloud.google.com/billing/</a>
* <tr><th>Discovery Name<td>cloudbilling
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google Cloud Billing API can be found at
* <a href='https://cloud.google.com/billing/'>https://cloud.google.com/billing/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Cloudbilling.v1
{
/// <summary>The Cloudbilling Service.</summary>
public class CloudbillingService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudbillingService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudbillingService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
billingAccounts = new BillingAccountsResource(this);
projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "cloudbilling"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://cloudbilling.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
/// <summary>Available OAuth 2.0 scopes for use with the Google Cloud Billing API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
private readonly BillingAccountsResource billingAccounts;
/// <summary>Gets the BillingAccounts resource.</summary>
public virtual BillingAccountsResource BillingAccounts
{
get { return billingAccounts; }
}
private readonly ProjectsResource projects;
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects
{
get { return projects; }
}
}
///<summary>A base abstract class for Cloudbilling requests.</summary>
public abstract class CloudbillingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new CloudbillingBaseServiceRequest instance.</summary>
protected CloudbillingBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Xgafv { get; set; }
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Alt { get; set; }
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Cloudbilling parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "billingAccounts" collection of methods.</summary>
public class BillingAccountsResource
{
private const string Resource = "billingAccounts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public BillingAccountsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
projects = new ProjectsResource(service);
}
private readonly ProjectsResource projects;
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects
{
get { return projects; }
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Lists the projects associated with a billing account. The current authenticated user must be an
/// [owner of the billing account](https://support.google.com/cloud/answer/4430947).</summary>
/// <param name="name">The resource name of the billing account associated with the projects that you want to list. For
/// example, `billingAccounts/012345-567890-ABCDEF`.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>Lists the projects associated with a billing account. The current authenticated user must be an
/// [owner of the billing account](https://support.google.com/cloud/answer/4430947).</summary>
public class ListRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ListProjectBillingInfoResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource name of the billing account associated with the projects that you want to
/// list. For example, `billingAccounts/012345-567890-ABCDEF`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Requested page size. The maximum page size is 100; this is also the default.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>A token identifying a page of results to be returned. This should be a `next_page_token`
/// value returned from a previous `ListProjectBillingInfo` call. If unspecified, the first page of
/// results is returned.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}/projects"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^billingAccounts/[^/]*$",
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets information about a billing account. The current authenticated user must be an [owner of the
/// billing account](https://support.google.com/cloud/answer/4430947).</summary>
/// <param name="name">The resource name of the billing account to retrieve. For example,
/// `billingAccounts/012345-567890-ABCDEF`.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets information about a billing account. The current authenticated user must be an [owner of the
/// billing account](https://support.google.com/cloud/answer/4430947).</summary>
public class GetRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.BillingAccount>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource name of the billing account to retrieve. For example,
/// `billingAccounts/012345-567890-ABCDEF`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^billingAccounts/[^/]*$",
});
}
}
/// <summary>Lists the billing accounts that the current authenticated user
/// [owns](https://support.google.com/cloud/answer/4430947).</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists the billing accounts that the current authenticated user
/// [owns](https://support.google.com/cloud/answer/4430947).</summary>
public class ListRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ListBillingAccountsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>Requested page size. The maximum page size is 100; this is also the default.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>A token identifying a page of results to return. This should be a `next_page_token` value
/// returned from a previous `ListBillingAccounts` call. If unspecified, the first page of results is
/// returned.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/billingAccounts"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Gets the billing information for a project. The current authenticated user must have [permission to
/// view the project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ).</summary>
/// <param name="name">The resource name of the project for which billing information is retrieved. For example,
/// `projects/tokyo-rain-123`.</param>
public virtual GetBillingInfoRequest GetBillingInfo(string name)
{
return new GetBillingInfoRequest(service, name);
}
/// <summary>Gets the billing information for a project. The current authenticated user must have [permission to
/// view the project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ).</summary>
public class GetBillingInfoRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo>
{
/// <summary>Constructs a new GetBillingInfo request.</summary>
public GetBillingInfoRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource name of the project for which billing information is retrieved. For example,
/// `projects/tokyo-rain-123`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "getBillingInfo"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}/billingInfo"; }
}
/// <summary>Initializes GetBillingInfo parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]*$",
});
}
}
/// <summary>Sets or updates the billing account associated with a project. You specify the new billing account
/// by setting the `billing_account_name` in the `ProjectBillingInfo` resource to the resource name of a billing
/// account. Associating a project with an open billing account enables billing on the project and allows
/// charges for resource usage. If the project already had a billing account, this method changes the billing
/// account used for resource usage charges. *Note:* Incurred charges that have not yet been reported in the
/// transaction history of the Google Developers Console may be billed to the new billing account, even if the
/// charge occurred before the new billing account was assigned to the project. The current authenticated user
/// must have ownership privileges for both the [project](https://cloud.google.com/docs/permissions-
/// overview#h.bgs0oxofvnoo ) and the [billing account](https://support.google.com/cloud/answer/4430947). You
/// can disable billing on the project by setting the `billing_account_name` field to empty. This action
/// disassociates the current billing account from the project. Any billable activity of your in-use services
/// will stop, and your application could stop functioning as expected. Any unbilled charges to date will be
/// billed to the previously associated account. The current authenticated user must be either an owner of the
/// project or an owner of the billing account for the project. Note that associating a project with a *closed*
/// billing account will have much the same effect as disabling billing on the project: any paid resources used
/// by the project will be shut down. Thus, unless you wish to disable billing, you should always call this
/// method with the name of an *open* billing account.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The resource name of the project associated with the billing information that you want to update.
/// For example, `projects/tokyo-rain-123`.</param>
public virtual UpdateBillingInfoRequest UpdateBillingInfo(Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo body, string name)
{
return new UpdateBillingInfoRequest(service, body, name);
}
/// <summary>Sets or updates the billing account associated with a project. You specify the new billing account
/// by setting the `billing_account_name` in the `ProjectBillingInfo` resource to the resource name of a billing
/// account. Associating a project with an open billing account enables billing on the project and allows
/// charges for resource usage. If the project already had a billing account, this method changes the billing
/// account used for resource usage charges. *Note:* Incurred charges that have not yet been reported in the
/// transaction history of the Google Developers Console may be billed to the new billing account, even if the
/// charge occurred before the new billing account was assigned to the project. The current authenticated user
/// must have ownership privileges for both the [project](https://cloud.google.com/docs/permissions-
/// overview#h.bgs0oxofvnoo ) and the [billing account](https://support.google.com/cloud/answer/4430947). You
/// can disable billing on the project by setting the `billing_account_name` field to empty. This action
/// disassociates the current billing account from the project. Any billable activity of your in-use services
/// will stop, and your application could stop functioning as expected. Any unbilled charges to date will be
/// billed to the previously associated account. The current authenticated user must be either an owner of the
/// project or an owner of the billing account for the project. Note that associating a project with a *closed*
/// billing account will have much the same effect as disabling billing on the project: any paid resources used
/// by the project will be shut down. Thus, unless you wish to disable billing, you should always call this
/// method with the name of an *open* billing account.</summary>
public class UpdateBillingInfoRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo>
{
/// <summary>Constructs a new UpdateBillingInfo request.</summary>
public UpdateBillingInfoRequest(Google.Apis.Services.IClientService service, Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The resource name of the project associated with the billing information that you want to
/// update. For example, `projects/tokyo-rain-123`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "updateBillingInfo"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PUT"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}/billingInfo"; }
}
/// <summary>Initializes UpdateBillingInfo parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]*$",
});
}
}
}
}
namespace Google.Apis.Cloudbilling.v1.Data
{
/// <summary>A billing account in [Google Developers Console](https://console.developers.google.com/). You can
/// assign a billing account to one or more projects.</summary>
public class BillingAccount : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The display name given to the billing account, such as `My Billing Account`. This name is displayed
/// in the Google Developers Console.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>The resource name of the billing account. The resource name has the form
/// `billingAccounts/{billing_account_id}`. For example, `billingAccounts/012345-567890-ABCDEF` would be the
/// resource name for billing account `012345-567890-ABCDEF`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>True if the billing account is open, and will therefore be charged for any usage on associated
/// projects. False if the billing account is closed, and therefore projects associated with it will be unable
/// to use paid services.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("open")]
public virtual System.Nullable<bool> Open { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for `ListBillingAccounts`.</summary>
public class ListBillingAccountsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A list of billing accounts.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("billingAccounts")]
public virtual System.Collections.Generic.IList<BillingAccount> BillingAccounts { get; set; }
/// <summary>A token to retrieve the next page of results. To retrieve the next page, call `ListBillingAccounts`
/// again with the `page_token` field set to this value. This field is empty if there are no more results to
/// retrieve.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `ListProjectBillingInfoResponse`.</summary>
public class ListProjectBillingInfoResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A token to retrieve the next page of results. To retrieve the next page, call
/// `ListProjectBillingInfo` again with the `page_token` field set to this value. This field is empty if there
/// are no more results to retrieve.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of `ProjectBillingInfo` resources representing the projects associated with the billing
/// account.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("projectBillingInfo")]
public virtual System.Collections.Generic.IList<ProjectBillingInfo> ProjectBillingInfo { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Encapsulation of billing information for a Developers Console project. A project has at most one
/// associated billing account at a time (but a billing account can be assigned to multiple projects).</summary>
public class ProjectBillingInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The resource name of the billing account associated with the project, if any. For example,
/// `billingAccounts/012345-567890-ABCDEF`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("billingAccountName")]
public virtual string BillingAccountName { get; set; }
/// <summary>True if the project is associated with an open billing account, to which usage on the project is
/// charged. False if the project is associated with a closed billing account, or no billing account at all, and
/// therefore cannot use paid services. This field is read-only.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("billingEnabled")]
public virtual System.Nullable<bool> BillingEnabled { get; set; }
/// <summary>The resource name for the `ProjectBillingInfo`; has the form `projects/{project_id}/billingInfo`.
/// For example, the resource name for the billing information for project `tokyo-rain-123` would be `projects
/// /tokyo-rain-123/billingInfo`. This field is read-only.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ID of the project that this `ProjectBillingInfo` represents, such as `tokyo-rain-123`. This is
/// a convenience field so that you don't need to parse the `name` field to obtain a project ID. This field is
/// read-only.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("projectId")]
public virtual string ProjectId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="InstantPreview.cs" company="Google Inc.">
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
using UnityEngine;
using System.Runtime.InteropServices;
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
namespace Gvr.Internal
{
[HelpURL("https://developers.google.com/vr/unity/reference/class/InstantPreview")]
public class InstantPreview : MonoBehaviour
{
private const string NoDevicesFoundAdbResult = "error: no devices/emulators found";
internal static InstantPreview Instance { get; set; }
internal const string dllName = "instant_preview_unity_plugin";
public enum Resolutions : int
{
Big,
Regular,
WindowSized,
}
struct ResolutionSize
{
public int width;
public int height;
}
[Tooltip("Resolution of video stream. Higher = more expensive / better visual quality.")]
public Resolutions OutputResolution = Resolutions.Big;
public enum MultisampleCounts
{
One,
Two,
Four,
Eight,
}
[Tooltip("Anti-aliasing for video preview. Higher = more expensive / better visual quality.")]
public MultisampleCounts MultisampleCount = MultisampleCounts.One;
public enum BitRates
{
_2000,
_4000,
_8000,
_16000,
_24000,
_32000,
}
[Tooltip("Video codec streaming bit rate. Higher = more expensive / better visual quality.")]
public BitRates BitRate = BitRates._16000;
[Tooltip("Installs the Instant Preview app if it isn't found on the connected device.")]
public bool InstallApkOnRun = true;
public UnityEngine.Object InstantPreviewApk;
struct UnityRect
{
public float right;
public float left;
public float top;
public float bottom;
}
struct UnityEyeViews
{
public Matrix4x4 leftEyePose;
public Matrix4x4 rightEyePose;
public UnityRect leftEyeViewSize;
public UnityRect rightEyeViewSize;
}
public struct UnityFloatAtom
{
public float value;
public bool isValid;
}
public struct UnityIntAtom
{
public int value;
public bool isValid;
}
public struct UnityGvrMat4fAtom
{
public Matrix4x4 value;
public bool isValid;
}
struct UnityGlobalGvrProperties
{
internal UnityFloatAtom floorHeight;
internal UnityGvrMat4fAtom recenterTransform;
internal UnityIntAtom safetyRegionType;
internal UnityFloatAtom safetyCylinderEnterRadius;
internal UnityFloatAtom safetyCylinderExitRadius;
}
public enum GvrEventType
{
GVR_EVENT_NONE,
GVR_EVENT_RECENTER,
GVR_EVENT_SAFETY_REGION_EXIT,
GVR_EVENT_SAFETY_REGION_ENTER,
GVR_EVENT_HEAD_TRACKING_RESUMED,
GVR_EVENT_HEAD_TRACKING_PAUSED,
}
public enum GvrRecenterEventType
{
GVR_RECENTER_EVENT_NONE,
GVR_RECENTER_EVENT_RESTART,
GVR_RECENTER_EVENT_ALIGNED,
GVR_RECENTER_EVENT_DON,
}
internal struct UnityGvrRecenterEventData
{
internal GvrRecenterEventType recenter_type;
internal uint recenter_event_flags;
internal Matrix4x4 start_space_from_tracking_space_transform;
}
internal struct UnityGvrEvent
{
// Timestamp in nanos.
internal long timestamp;
internal GvrEventType type;
internal uint flags;
// Not null iff event type is GVR_EVENT_RECENTER.
internal UnityGvrRecenterEventData gvr_recenter_event_data;
}
#if UNITY_EDITOR
static ResolutionSize[] resolutionSizes = new ResolutionSize[]
{
new ResolutionSize()
{
// ResolutionSize.Big
width = 2560, height = 1440,
},
new ResolutionSize()
{
// ResolutionSize.Regular
width = 1920, height = 1080,
},
// ResolutionSize.WindowSized
new ResolutionSize(),
};
private static readonly int[] multisampleCounts = new int[]
{
1, // MultisampleCounts.One
2, // MultisampleCounts.Two
4, // MultisampleCounts.Four
8, // MultisampleCounts.Eight
};
private static readonly int[] bitRates = new int[]
{
2000, // BitRates._2000
4000, // BitRates._4000
8000, // BitRates._8000
16000, // BitRates._16000
24000, // BitRates._24000
32000, // BitRates._32000
};
[DllImport(dllName)]
private static extern bool IsConnected();
[DllImport(dllName)]
private static extern bool GetHeadPose(out Matrix4x4 pose, out double timestamp);
[DllImport(dllName)]
private static extern bool GetEyeViews(out UnityEyeViews outputEyeViews);
[DllImport(dllName)]
private static extern bool GetGlobalGvrProperties(ref UnityGlobalGvrProperties outputProperties);
[DllImport(dllName)]
private static extern bool GetGvrEvent(ref UnityGvrEvent outputEvent);
[DllImport(dllName)]
private static extern IntPtr GetRenderEventFunc();
[DllImport(dllName)]
private static extern void SendFrame(IntPtr renderTexture, ref Matrix4x4 pose, double timestamp, int bitRate);
[DllImport(dllName)]
private static extern void GetVersionString(StringBuilder dest, uint n);
public bool IsCurrentlyConnected
{
get { return connected; }
}
private IntPtr renderEventFunc;
private RenderTexture renderTexture;
private Matrix4x4 headPose = Matrix4x4.identity;
private double timestamp;
private class EyeCamera
{
public Camera leftEyeCamera = null;
public Camera rightEyeCamera = null;
}
Dictionary<Camera, EyeCamera> eyeCameras = new Dictionary<Camera, EyeCamera>();
List<Camera> camerasLastFrame = new List<Camera>();
private bool connected;
public UnityFloatAtom floorHeight { get; private set; }
public UnityGvrMat4fAtom recenterTransform { get; private set; }
public UnityIntAtom safetyRegionType { get; private set; }
public UnityFloatAtom safetyCylinderEnterRadius { get; private set; }
public UnityFloatAtom safetyCylinderExitRadius { get; private set; }
internal Queue<UnityGvrEvent> events = new Queue<UnityGvrEvent>();
void Awake()
{
renderEventFunc = GetRenderEventFunc();
if (Instance != null)
{
Destroy(gameObject);
gameObject.SetActive(false);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
void Start()
{
// Gets local version name and prints it out.
var sb = new StringBuilder(256);
GetVersionString(sb, (uint)sb.Capacity);
var pluginIPVersionName = sb.ToString();
Debug.Log("Instant Preview Version: " + pluginIPVersionName);
// Tries to install Instant Preview apk if set to do so.
if (InstallApkOnRun)
{
// Early outs if set to install but the apk can't be found.
if (InstantPreviewApk == null)
{
Debug.LogError("Trying to install Instant Preview apk but reference to InstantPreview.apk is broken.");
return;
}
// Gets the apk path and installs it on a separate thread.
var apkPath = Path.GetFullPath(UnityEditor.AssetDatabase.GetAssetPath(InstantPreviewApk));
if (File.Exists(apkPath))
{
new Thread(
() =>
{
string output;
string errors;
string deviceIPVersionName = null;
string unityAPKVersionName = null;
// Gets version of apk installed on device (to remove, if dated).
RunCommand(InstantPreviewHelper.AdbPath,
"shell dumpsys package com.google.instantpreview | grep versionName",
out output, out errors);
if (!string.IsNullOrEmpty(output) && string.IsNullOrEmpty(errors))
{
deviceIPVersionName = output.Substring(output.IndexOf('=') + 1);
}
// Early outs if no device is connected.
if (string.Compare(errors, NoDevicesFoundAdbResult) == 0)
{
return;
}
// Prints errors and exits on failure.
if (!string.IsNullOrEmpty(errors))
{
Debug.LogError(errors);
return;
}
// Gets version of Unity's local .apk version (to install, if needed).
RunCommand(InstantPreviewHelper.AaptPath,
string.Format("dump badging {0}", apkPath),
out output, out errors);
if (!string.IsNullOrEmpty(output) && string.IsNullOrEmpty(errors))
{
string unityAPKVersionInfoDump = output;
// Finds (versionName='), captures any alphaNumerics separated by periods, and selects them until (').
System.Text.RegularExpressions.Match unityAPKVersionNameRegex = Regex.Match(
unityAPKVersionInfoDump, "versionName=\'([^']*)\'");
if (unityAPKVersionNameRegex.Groups.Count > 1)
{
unityAPKVersionName = unityAPKVersionNameRegex.Groups[1].Value;
}
else
{
Debug.Log(string.Format("Failed to extract version from: {0}", unityAPKVersionInfoDump));
}
}
else
{
Debug.Log(string.Format("Failed to run: {0} dump badging {1}", InstantPreviewHelper.AaptPath, apkPath));
}
// Determines if Unity plugin and Unity's local .apk IP file are the same version, and exits if not.
if (pluginIPVersionName != unityAPKVersionName)
{
Debug.LogWarning(string.Format(
"Unity Instant Preview plugin version ({0}) does not match Unity Instant Preview .apk version ({1})."
+ " This may cause unpredictable behavior.",
pluginIPVersionName, unityAPKVersionName));
}
// Determines if app is installed, and installs it if not.
if (deviceIPVersionName != unityAPKVersionName)
{
if (deviceIPVersionName == null)
{
Debug.Log(string.Format(
"Instant Preview: app not found on device, attempting to install it from {0}.",
apkPath));
}
else
{
Debug.Log(string.Format(
"Instant Preview: installed version \"{0}\" does not match local version \"{1}\", attempting upgrade.",
deviceIPVersionName, unityAPKVersionName));
}
RunCommand(InstantPreviewHelper.AdbPath,
string.Format("uninstall com.google.instantpreview", apkPath),
out output, out errors);
RunCommand(InstantPreviewHelper.AdbPath,
string.Format("install \"{0}\"", apkPath),
out output, out errors);
// Prints any output from trying to install.
if (!string.IsNullOrEmpty(output))
{
Debug.Log(output);
}
if (!string.IsNullOrEmpty(errors))
{
if (string.Equals(errors.Trim(), "Success"))
{
Debug.Log("Successfully installed Instant Preview app.");
}
else
{
Debug.LogError(errors);
}
}
}
StartInstantPreviewActivity(InstantPreviewHelper.AdbPath);
}).Start();
}
}
else
{
new Thread(() => { StartInstantPreviewActivity(InstantPreviewHelper.AdbPath); }).Start();
}
}
void UpdateCamera(Camera camera)
{
EyeCamera eyeCamera;
if (!eyeCameras.TryGetValue(camera, out eyeCamera))
{
return;
}
if (connected)
{
if (GetHeadPose(out headPose, out timestamp))
{
SetEditorEmulatorsEnabled(false);
camera.transform.localRotation = Quaternion.LookRotation(headPose.GetColumn(2), headPose.GetColumn(1));
camera.transform.localPosition = camera.transform.localRotation * headPose.GetRow(3) * -1;
}
else
{
SetEditorEmulatorsEnabled(true);
}
var eyeViews = new UnityEyeViews();
if (GetEyeViews(out eyeViews))
{
SetTransformFromMatrix(eyeCamera.leftEyeCamera.gameObject.transform, eyeViews.leftEyePose);
SetTransformFromMatrix(eyeCamera.rightEyeCamera.gameObject.transform, eyeViews.rightEyePose);
var near = Camera.main.nearClipPlane;
var far = Camera.main.farClipPlane;
eyeCamera.leftEyeCamera.projectionMatrix =
PerspectiveMatrixFromUnityRect(eyeViews.leftEyeViewSize, near, far);
eyeCamera.rightEyeCamera.projectionMatrix =
PerspectiveMatrixFromUnityRect(eyeViews.rightEyeViewSize, near, far);
bool multisampleChanged = multisampleCounts[(int)MultisampleCount] != renderTexture.antiAliasing;
// Adjusts render texture size.
if (OutputResolution != Resolutions.WindowSized)
{
var selectedResolutionSize = resolutionSizes[(int)OutputResolution];
if (selectedResolutionSize.width != renderTexture.width ||
selectedResolutionSize.height != renderTexture.height ||
multisampleChanged)
{
ResizeRenderTexture(selectedResolutionSize.width, selectedResolutionSize.height);
}
}
else
{
// OutputResolution == Resolutions.WindowSized
var screenAspectRatio = (float)Screen.width / Screen.height;
var eyeViewsWidth =
-eyeViews.leftEyeViewSize.left +
eyeViews.leftEyeViewSize.right +
-eyeViews.rightEyeViewSize.left +
eyeViews.rightEyeViewSize.right;
var eyeViewsHeight =
eyeViews.leftEyeViewSize.top +
-eyeViews.leftEyeViewSize.bottom;
if (eyeViewsHeight > 0f)
{
int renderTextureHeight;
int renderTextureWidth;
var eyeViewsAspectRatio = eyeViewsWidth / eyeViewsHeight;
if (screenAspectRatio > eyeViewsAspectRatio)
{
renderTextureHeight = Screen.height;
renderTextureWidth = (int)(Screen.height * eyeViewsAspectRatio);
}
else
{
renderTextureWidth = Screen.width;
renderTextureHeight = (int)(Screen.width / eyeViewsAspectRatio);
}
renderTextureWidth = renderTextureWidth & ~0x3;
renderTextureHeight = renderTextureHeight & ~0x3;
if (multisampleChanged ||
renderTexture.width != renderTextureWidth ||
renderTexture.height != renderTextureHeight)
{
ResizeRenderTexture(renderTextureWidth, renderTextureHeight);
}
}
}
}
}
else
{
// !connected
SetEditorEmulatorsEnabled(true);
if (renderTexture.width != Screen.width || renderTexture.height != Screen.height)
{
ResizeRenderTexture(Screen.width, Screen.height);
}
}
}
void UpdateProperties()
{
UnityGlobalGvrProperties unityGlobalGvrProperties = new UnityGlobalGvrProperties();
if (GetGlobalGvrProperties(ref unityGlobalGvrProperties))
{
floorHeight = unityGlobalGvrProperties.floorHeight;
recenterTransform = unityGlobalGvrProperties.recenterTransform;
safetyRegionType = unityGlobalGvrProperties.safetyRegionType;
safetyCylinderEnterRadius = unityGlobalGvrProperties.safetyCylinderEnterRadius;
safetyCylinderExitRadius = unityGlobalGvrProperties.safetyCylinderExitRadius;
}
}
void UpdateEvents()
{
UnityGvrEvent unityGvrEvent = new UnityGvrEvent();
while (GetGvrEvent(ref unityGvrEvent))
{
events.Enqueue(unityGvrEvent);
}
}
void Update()
{
if (!EnsureCameras())
{
return;
}
var newConnectionState = IsConnected();
if (connected && !newConnectionState)
{
Debug.Log("Disconnected from Instant Preview.");
}
else if (!connected && newConnectionState)
{
Debug.Log("Connected to Instant Preview.");
}
connected = newConnectionState;
foreach (KeyValuePair<Camera, EyeCamera> eyeCamera in eyeCameras)
{
UpdateCamera(eyeCamera.Key);
}
UpdateProperties();
UpdateEvents();
}
void OnPostRender()
{
if (connected && renderTexture != null)
{
var nativeTexturePtr = renderTexture.GetNativeTexturePtr();
SendFrame(nativeTexturePtr, ref headPose, timestamp, bitRates[(int)BitRate]);
GL.IssuePluginEvent(renderEventFunc, 69);
}
}
void EnsureCamera(Camera camera)
{
// renderTexture might still be null so this creates and assigns it.
if (renderTexture == null)
{
if (OutputResolution != Resolutions.WindowSized)
{
var selectedResolutionSize = resolutionSizes[(int)OutputResolution];
ResizeRenderTexture(selectedResolutionSize.width, selectedResolutionSize.height);
}
else
{
ResizeRenderTexture(Screen.width, Screen.height);
}
}
EyeCamera eyeCamera;
if (!eyeCameras.TryGetValue(camera, out eyeCamera))
{
eyeCamera = new EyeCamera();
eyeCameras.Add(camera, eyeCamera);
}
EnsureEyeCamera(camera, ":Instant Preview Left", new Rect(0.0f, 0.0f, 0.5f, 1.0f), ref eyeCamera.leftEyeCamera);
EnsureEyeCamera(camera, ":Instant Preview Right", new Rect(0.5f, 0.0f, 0.5f, 1.0f), ref eyeCamera.rightEyeCamera);
}
private void CheckRemoveCameras(List<Camera> cameras)
{
// Any cameras that were here last frame and not here this frame need removing from eyeCameras.
foreach (Camera oldCamera in camerasLastFrame)
{
if (!cameras.Contains(oldCamera))
{
// Destroys the eye cameras.
EyeCamera curEyeCamera;
if (eyeCameras.TryGetValue(oldCamera, out curEyeCamera))
{
if (curEyeCamera.leftEyeCamera != null)
{
Destroy(curEyeCamera.leftEyeCamera.gameObject);
}
if (curEyeCamera.rightEyeCamera != null)
{
Destroy(curEyeCamera.rightEyeCamera.gameObject);
}
}
// Removes eye camera entry from dictionary.
eyeCameras.Remove(oldCamera);
}
}
camerasLastFrame = cameras;
}
bool EnsureCameras()
{
var mainCamera = Camera.main;
if (!mainCamera)
{
// If the main camera doesn't exist, destroys a remaining render texture and exits.
if (renderTexture != null)
{
Destroy(renderTexture);
renderTexture = null;
}
return false;
}
// Find all the cameras and make sure any non-Instant Preview cameras have left/right eyes attached.
var cameras = new List<Camera>(ValidCameras());
CheckRemoveCameras(cameras);
// Now go and make sure that all cameras that are to be driven by Instant Preview have the correct setup.
foreach (Camera camera in cameras)
{
// Skips the Instant Preview camera, which is used for a
// convenience preview.
if (camera.gameObject == gameObject)
{
continue;
}
EnsureCamera(camera);
}
return true;
}
void EnsureEyeCamera(Camera mainCamera, String eyeCameraName, Rect rect, ref Camera eyeCamera)
{
// Creates eye camera object if it doesn't exist.
if (eyeCamera == null)
{
var eyeCameraObject = new GameObject(mainCamera.gameObject.name + eyeCameraName);
eyeCamera = eyeCameraObject.AddComponent<Camera>();
eyeCameraObject.transform.SetParent(mainCamera.gameObject.transform, false);
}
eyeCamera.CopyFrom(mainCamera);
eyeCamera.rect = rect;
eyeCamera.targetTexture = renderTexture;
// Match child camera's skyboxes to main camera.
Skybox monoCameraSkybox = mainCamera.gameObject.GetComponent<Skybox>();
Skybox customSkybox = eyeCamera.GetComponent<Skybox>();
if (monoCameraSkybox != null)
{
if (customSkybox == null)
{
customSkybox = eyeCamera.gameObject.AddComponent<Skybox>();
}
customSkybox.material = monoCameraSkybox.material;
}
else if (customSkybox != null)
{
Destroy(customSkybox);
}
}
void ResizeRenderTexture(int width, int height)
{
var newRenderTexture = new RenderTexture(width, height, 16);
newRenderTexture.antiAliasing = multisampleCounts[(int)MultisampleCount];
if (renderTexture != null)
{
foreach (KeyValuePair<Camera, EyeCamera> camera in eyeCameras)
{
if (camera.Value.leftEyeCamera != null)
{
camera.Value.leftEyeCamera.targetTexture = null;
}
if (camera.Value.rightEyeCamera != null)
{
camera.Value.rightEyeCamera.targetTexture = null;
}
}
Destroy(renderTexture);
}
renderTexture = newRenderTexture;
}
private static void SetEditorEmulatorsEnabled(bool enabled)
{
foreach (var editorEmulator in FindObjectsOfType<GvrEditorEmulator>())
{
editorEmulator.enabled = enabled;
}
}
private static Matrix4x4 PerspectiveMatrixFromUnityRect(UnityRect rect, float near, float far)
{
if (rect.left == rect.right || rect.bottom == rect.top || near == far ||
near <= 0f || far <= 0f)
{
return Matrix4x4.identity;
}
rect.left *= near;
rect.right *= near;
rect.top *= near;
rect.bottom *= near;
var X = (2 * near) / (rect.right - rect.left);
var Y = (2 * near) / (rect.top - rect.bottom);
var A = (rect.right + rect.left) / (rect.right - rect.left);
var B = (rect.top + rect.bottom) / (rect.top - rect.bottom);
var C = (near + far) / (near - far);
var D = (2 * near * far) / (near - far);
var perspectiveMatrix = new Matrix4x4();
perspectiveMatrix[0, 0] = X;
perspectiveMatrix[0, 2] = A;
perspectiveMatrix[1, 1] = Y;
perspectiveMatrix[1, 2] = B;
perspectiveMatrix[2, 2] = C;
perspectiveMatrix[2, 3] = D;
perspectiveMatrix[3, 2] = -1f;
return perspectiveMatrix;
}
private static void SetTransformFromMatrix(Transform transform, Matrix4x4 matrix)
{
var position = matrix.GetRow(3);
position.x *= -1;
transform.localPosition = position;
transform.localRotation = Quaternion.LookRotation(matrix.GetColumn(2), matrix.GetColumn(1));
}
private static void StartInstantPreviewActivity(string adbPath)
{
string output;
string errors;
RunCommand(adbPath, "shell monkey -p com.google.instantpreview -c android.intent.category.LAUNCHER 1", out output, out errors);
// Early outs if no device is connected.
if (string.Compare(errors, NoDevicesFoundAdbResult) == 0)
{
return;
}
}
private static void RunCommand(string fileName, string arguments, out string output, out string errors)
{
using (var process = new System.Diagnostics.Process())
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(fileName, arguments);
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
process.StartInfo = startInfo;
var outputBuilder = new StringBuilder();
var errorBuilder = new StringBuilder();
process.OutputDataReceived += (o, ef) => outputBuilder.AppendLine(ef.Data);
process.ErrorDataReceived += (o, ef) => errorBuilder.AppendLine(ef.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
process.Close();
// Trims the output strings to make comparison easier.
output = outputBuilder.ToString().Trim();
errors = errorBuilder.ToString().Trim();
}
}
// Gets active, stereo, non-eye cameras in the scene.
private IEnumerable<Camera> ValidCameras()
{
foreach (var camera in Camera.allCameras)
{
if (!camera.enabled || camera.stereoTargetEye == StereoTargetEyeMask.None)
{
continue;
}
// Skips camera if it is determined to be an eye camera.
var parent = camera.transform.parent;
if (parent != null)
{
var parentCamera = parent.GetComponent<Camera>();
if (parentCamera != null)
{
EyeCamera parentEyeCamera;
if (eyeCameras.TryGetValue(parentCamera, out parentEyeCamera))
{
if (camera == parentEyeCamera.leftEyeCamera || camera == parentEyeCamera.rightEyeCamera)
{
continue;
}
}
}
}
yield return camera;
}
}
#else
public bool IsCurrentlyConnected
{
get { return false; }
}
#endif
}
}
| |
namespace Epi.Windows.Analysis.Dialogs
{
partial class SetDialog
{
/// <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 Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SetDialog));
this.btnHelp = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.btnSaveOnly = new System.Windows.Forms.Button();
this.lblPrecision = new System.Windows.Forms.Label();
this.numericUpDownPrecision = new System.Windows.Forms.NumericUpDown();
this.gbxHTMLOutput = new System.Windows.Forms.GroupBox();
this.cbxShowPrompt = new System.Windows.Forms.CheckBox();
this.cbxTablesOutput = new System.Windows.Forms.CheckBox();
this.cbxPercents = new System.Windows.Forms.CheckBox();
this.cbxGraphics = new System.Windows.Forms.CheckBox();
this.cbxSelectCriteria = new System.Windows.Forms.CheckBox();
this.cbxHyperlinks = new System.Windows.Forms.CheckBox();
this.gbxRepresentBooleans = new System.Windows.Forms.GroupBox();
this.lblYesAs = new System.Windows.Forms.Label();
this.cmbYesAs = new System.Windows.Forms.ComboBox();
this.lblNoAs = new System.Windows.Forms.Label();
this.cmbNoAs = new System.Windows.Forms.ComboBox();
this.lblMissingAs = new System.Windows.Forms.Label();
this.cmbMissingAs = new System.Windows.Forms.ComboBox();
this.gbxStatistics = new System.Windows.Forms.GroupBox();
this.rdbAdvanced = new System.Windows.Forms.RadioButton();
this.rdbMinimal = new System.Windows.Forms.RadioButton();
this.rdbIntermediate = new System.Windows.Forms.RadioButton();
this.rdbNone = new System.Windows.Forms.RadioButton();
this.cbxIncludeMissing = new System.Windows.Forms.CheckBox();
this.gbxProcessRecords = new System.Windows.Forms.GroupBox();
this.rdbDeleted = new System.Windows.Forms.RadioButton();
this.rdbBoth = new System.Windows.Forms.RadioButton();
this.rdbNormal = new System.Windows.Forms.RadioButton();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownPrecision)).BeginInit();
this.gbxHTMLOutput.SuspendLayout();
this.gbxRepresentBooleans.SuspendLayout();
this.gbxStatistics.SuspendLayout();
this.gbxProcessRecords.SuspendLayout();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
//
// btnHelp
//
resources.ApplyResources(this.btnHelp, "btnHelp");
this.btnHelp.Name = "btnHelp";
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
//
// btnClear
//
resources.ApplyResources(this.btnClear, "btnClear");
this.btnClear.Name = "btnClear";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// btnSaveOnly
//
resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly");
this.btnSaveOnly.Name = "btnSaveOnly";
//
// lblPrecision
//
resources.ApplyResources(this.lblPrecision, "lblPrecision");
this.lblPrecision.Name = "lblPrecision";
//
// numericUpDownPrecision
//
resources.ApplyResources(this.numericUpDownPrecision, "numericUpDownPrecision");
this.numericUpDownPrecision.Maximum = new decimal(new int[] {
9,
0,
0,
0});
this.numericUpDownPrecision.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownPrecision.Name = "numericUpDownPrecision";
this.numericUpDownPrecision.Value = new decimal(new int[] {
2,
0,
0,
0});
//
// gbxHTMLOutput
//
this.gbxHTMLOutput.Controls.Add(this.cbxShowPrompt);
this.gbxHTMLOutput.Controls.Add(this.cbxTablesOutput);
this.gbxHTMLOutput.Controls.Add(this.cbxPercents);
this.gbxHTMLOutput.Controls.Add(this.cbxGraphics);
this.gbxHTMLOutput.Controls.Add(this.cbxSelectCriteria);
this.gbxHTMLOutput.Controls.Add(this.cbxHyperlinks);
resources.ApplyResources(this.gbxHTMLOutput, "gbxHTMLOutput");
this.gbxHTMLOutput.Name = "gbxHTMLOutput";
this.gbxHTMLOutput.TabStop = false;
//
// cbxShowPrompt
//
resources.ApplyResources(this.cbxShowPrompt, "cbxShowPrompt");
this.cbxShowPrompt.Name = "cbxShowPrompt";
this.cbxShowPrompt.CheckedChanged += new System.EventHandler(this.cbxShowPrompt_CheckedChanged);
//
// cbxTablesOutput
//
resources.ApplyResources(this.cbxTablesOutput, "cbxTablesOutput");
this.cbxTablesOutput.Name = "cbxTablesOutput";
this.cbxTablesOutput.CheckedChanged += new System.EventHandler(this.cbxTablesOutput_CheckedChanged);
//
// cbxPercents
//
resources.ApplyResources(this.cbxPercents, "cbxPercents");
this.cbxPercents.Name = "cbxPercents";
this.cbxPercents.CheckedChanged += new System.EventHandler(this.cbxPercents_CheckedChanged);
//
// cbxGraphics
//
resources.ApplyResources(this.cbxGraphics, "cbxGraphics");
this.cbxGraphics.Name = "cbxGraphics";
this.cbxGraphics.CheckedChanged += new System.EventHandler(this.cbxGraphics_CheckedChanged);
//
// cbxSelectCriteria
//
resources.ApplyResources(this.cbxSelectCriteria, "cbxSelectCriteria");
this.cbxSelectCriteria.Name = "cbxSelectCriteria";
this.cbxSelectCriteria.CheckedChanged += new System.EventHandler(this.cbxSelectCriteria_CheckedChanged);
//
// cbxHyperlinks
//
resources.ApplyResources(this.cbxHyperlinks, "cbxHyperlinks");
this.cbxHyperlinks.Name = "cbxHyperlinks";
this.cbxHyperlinks.CheckedChanged += new System.EventHandler(this.cbxHyperlinks_CheckedChanged);
//
// gbxRepresentBooleans
//
this.gbxRepresentBooleans.Controls.Add(this.lblYesAs);
this.gbxRepresentBooleans.Controls.Add(this.cmbYesAs);
this.gbxRepresentBooleans.Controls.Add(this.lblNoAs);
this.gbxRepresentBooleans.Controls.Add(this.cmbNoAs);
this.gbxRepresentBooleans.Controls.Add(this.lblMissingAs);
this.gbxRepresentBooleans.Controls.Add(this.cmbMissingAs);
resources.ApplyResources(this.gbxRepresentBooleans, "gbxRepresentBooleans");
this.gbxRepresentBooleans.Name = "gbxRepresentBooleans";
this.gbxRepresentBooleans.TabStop = false;
//
// lblYesAs
//
resources.ApplyResources(this.lblYesAs, "lblYesAs");
this.lblYesAs.Name = "lblYesAs";
//
// cmbYesAs
//
resources.ApplyResources(this.cmbYesAs, "cmbYesAs");
this.cmbYesAs.Name = "cmbYesAs";
this.cmbYesAs.SelectedIndexChanged += new System.EventHandler(this.cmbYesAs_SelectedIndexChanged);
this.cmbYesAs.TextChanged += new System.EventHandler(this.cmbYesAs_TextChanged);
//
// lblNoAs
//
resources.ApplyResources(this.lblNoAs, "lblNoAs");
this.lblNoAs.Name = "lblNoAs";
//
// cmbNoAs
//
resources.ApplyResources(this.cmbNoAs, "cmbNoAs");
this.cmbNoAs.Name = "cmbNoAs";
this.cmbNoAs.SelectedIndexChanged += new System.EventHandler(this.cmbNoAs_SelectedIndexChanged);
this.cmbNoAs.TextChanged += new System.EventHandler(this.cmbNoAs_TextChanged);
//
// lblMissingAs
//
resources.ApplyResources(this.lblMissingAs, "lblMissingAs");
this.lblMissingAs.Name = "lblMissingAs";
//
// cmbMissingAs
//
resources.ApplyResources(this.cmbMissingAs, "cmbMissingAs");
this.cmbMissingAs.Name = "cmbMissingAs";
this.cmbMissingAs.SelectedIndexChanged += new System.EventHandler(this.cmbMissingAs_SelectedIndexChanged);
this.cmbMissingAs.TextChanged += new System.EventHandler(this.cmbMissingAs_TextChanged);
//
// gbxStatistics
//
this.gbxStatistics.Controls.Add(this.rdbAdvanced);
this.gbxStatistics.Controls.Add(this.rdbMinimal);
this.gbxStatistics.Controls.Add(this.rdbIntermediate);
this.gbxStatistics.Controls.Add(this.rdbNone);
resources.ApplyResources(this.gbxStatistics, "gbxStatistics");
this.gbxStatistics.Name = "gbxStatistics";
this.gbxStatistics.TabStop = false;
//
// rdbAdvanced
//
this.rdbAdvanced.Checked = true;
resources.ApplyResources(this.rdbAdvanced, "rdbAdvanced");
this.rdbAdvanced.Name = "rdbAdvanced";
this.rdbAdvanced.TabStop = true;
this.rdbAdvanced.Tag = "4";
this.rdbAdvanced.Click += new System.EventHandler(this.StatisticsRadioButtonClick);
//
// rdbMinimal
//
resources.ApplyResources(this.rdbMinimal, "rdbMinimal");
this.rdbMinimal.Name = "rdbMinimal";
this.rdbMinimal.Tag = "2";
this.rdbMinimal.Click += new System.EventHandler(this.StatisticsRadioButtonClick);
//
// rdbIntermediate
//
resources.ApplyResources(this.rdbIntermediate, "rdbIntermediate");
this.rdbIntermediate.Name = "rdbIntermediate";
this.rdbIntermediate.Tag = "3";
this.rdbIntermediate.Click += new System.EventHandler(this.StatisticsRadioButtonClick);
//
// rdbNone
//
resources.ApplyResources(this.rdbNone, "rdbNone");
this.rdbNone.Name = "rdbNone";
this.rdbNone.Tag = "1";
this.rdbNone.Click += new System.EventHandler(this.StatisticsRadioButtonClick);
//
// cbxIncludeMissing
//
resources.ApplyResources(this.cbxIncludeMissing, "cbxIncludeMissing");
this.cbxIncludeMissing.Name = "cbxIncludeMissing";
this.cbxIncludeMissing.CheckedChanged += new System.EventHandler(this.cbxIncludeMissing_CheckedChanged);
//
// gbxProcessRecords
//
this.gbxProcessRecords.Controls.Add(this.rdbDeleted);
this.gbxProcessRecords.Controls.Add(this.rdbBoth);
this.gbxProcessRecords.Controls.Add(this.rdbNormal);
resources.ApplyResources(this.gbxProcessRecords, "gbxProcessRecords");
this.gbxProcessRecords.Name = "gbxProcessRecords";
this.gbxProcessRecords.TabStop = false;
//
// rdbDeleted
//
resources.ApplyResources(this.rdbDeleted, "rdbDeleted");
this.rdbDeleted.Name = "rdbDeleted";
this.rdbDeleted.Tag = "2";
this.rdbDeleted.Click += new System.EventHandler(this.ProcessRecordsRadioButtonClick);
//
// rdbBoth
//
resources.ApplyResources(this.rdbBoth, "rdbBoth");
this.rdbBoth.Name = "rdbBoth";
this.rdbBoth.Tag = "3";
this.rdbBoth.Click += new System.EventHandler(this.ProcessRecordsRadioButtonClick);
//
// rdbNormal
//
resources.ApplyResources(this.rdbNormal, "rdbNormal");
this.rdbNormal.Name = "rdbNormal";
this.rdbNormal.Tag = "1";
this.rdbNormal.Click += new System.EventHandler(this.ProcessRecordsRadioButtonClick);
//
// SetDialog
//
this.AcceptButton = this.btnOK;
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.lblPrecision);
this.Controls.Add(this.numericUpDownPrecision);
this.Controls.Add(this.gbxHTMLOutput);
this.Controls.Add(this.gbxRepresentBooleans);
this.Controls.Add(this.gbxStatistics);
this.Controls.Add(this.cbxIncludeMissing);
this.Controls.Add(this.gbxProcessRecords);
this.Controls.Add(this.btnSaveOnly);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.btnClear);
this.HelpButton = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SetDialog";
this.Load += new System.EventHandler(this.Set_Load);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownPrecision)).EndInit();
this.gbxHTMLOutput.ResumeLayout(false);
this.gbxRepresentBooleans.ResumeLayout(false);
this.gbxStatistics.ResumeLayout(false);
this.gbxProcessRecords.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Button btnSaveOnly;
private System.Windows.Forms.Label lblPrecision;
private System.Windows.Forms.NumericUpDown numericUpDownPrecision;
private System.Windows.Forms.GroupBox gbxHTMLOutput;
private System.Windows.Forms.CheckBox cbxShowPrompt;
private System.Windows.Forms.CheckBox cbxTablesOutput;
private System.Windows.Forms.CheckBox cbxPercents;
private System.Windows.Forms.CheckBox cbxGraphics;
private System.Windows.Forms.CheckBox cbxSelectCriteria;
private System.Windows.Forms.CheckBox cbxHyperlinks;
private System.Windows.Forms.GroupBox gbxRepresentBooleans;
private System.Windows.Forms.Label lblYesAs;
private System.Windows.Forms.ComboBox cmbYesAs;
private System.Windows.Forms.Label lblNoAs;
private System.Windows.Forms.ComboBox cmbNoAs;
private System.Windows.Forms.Label lblMissingAs;
private System.Windows.Forms.ComboBox cmbMissingAs;
private System.Windows.Forms.GroupBox gbxStatistics;
private System.Windows.Forms.RadioButton rdbAdvanced;
private System.Windows.Forms.RadioButton rdbMinimal;
private System.Windows.Forms.RadioButton rdbIntermediate;
private System.Windows.Forms.RadioButton rdbNone;
private System.Windows.Forms.CheckBox cbxIncludeMissing;
private System.Windows.Forms.GroupBox gbxProcessRecords;
private System.Windows.Forms.RadioButton rdbDeleted;
private System.Windows.Forms.RadioButton rdbBoth;
private System.Windows.Forms.RadioButton rdbNormal;
}
}
| |
using System;
using System.Linq;
using System.Numerics;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.Test.Extensions;
using Neo.Test.Helpers;
using Neo.VM;
namespace Neo.Test
{
[TestClass]
public class UtScriptBuilder
{
[TestMethod]
public void TestEmit()
{
using (var script = new ScriptBuilder())
{
Assert.AreEqual(0, script.Offset);
script.Emit(OpCode.NOP);
Assert.AreEqual(1, script.Offset);
CollectionAssert.AreEqual(new byte[] { 0x21 }, script.ToArray());
}
using (var script = new ScriptBuilder())
{
script.Emit(OpCode.NOP, new byte[] { 0x66 });
CollectionAssert.AreEqual(new byte[] { 0x21, 0x66 }, script.ToArray());
}
}
[TestMethod]
public void TestEmitSysCall()
{
using (var script = new ScriptBuilder())
{
script.EmitSysCall(0xE393C875);
CollectionAssert.AreEqual(new byte[] { (byte)OpCode.SYSCALL, 0x75, 0xC8, 0x93, 0xE3 }.ToArray(), script.ToArray());
}
}
[TestMethod]
public void TestEmitCall()
{
using (var script = new ScriptBuilder())
{
script.EmitCall(0);
CollectionAssert.AreEqual(new[] { (byte)OpCode.CALL, (byte)0 }, script.ToArray());
}
using (var script = new ScriptBuilder())
{
script.EmitCall(12345);
CollectionAssert.AreEqual(new[] { (byte)OpCode.CALL_L }.Concat(BitConverter.GetBytes(12345)).ToArray(), script.ToArray());
}
using (var script = new ScriptBuilder())
{
script.EmitCall(-12345);
CollectionAssert.AreEqual(new[] { (byte)OpCode.CALL_L }.Concat(BitConverter.GetBytes(-12345)).ToArray(), script.ToArray());
}
}
[TestMethod]
public void TestEmitJump()
{
var offset_i8 = sbyte.MaxValue;
var offset_i32 = int.MaxValue;
foreach (OpCode op in Enum.GetValues(typeof(OpCode)))
{
using (var script = new ScriptBuilder())
{
if (op < OpCode.JMP || op > OpCode.JMPLE_L)
{
Assert.ThrowsException<ArgumentOutOfRangeException>(() => script.EmitJump(op, offset_i8));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => script.EmitJump(op, offset_i32));
}
else
{
script.EmitJump(op, offset_i8);
script.EmitJump(op, offset_i32);
if ((int)op % 2 == 0)
CollectionAssert.AreEqual(new[] { (byte)op, (byte)offset_i8, (byte)(op + 1) }.Concat(BitConverter.GetBytes(offset_i32)).ToArray(), script.ToArray());
else
CollectionAssert.AreEqual(new[] { (byte)op }.Concat(BitConverter.GetBytes((int)offset_i8)).Concat(new[] { (byte)op }).Concat(BitConverter.GetBytes(offset_i32)).ToArray(), script.ToArray());
}
}
}
offset_i8 = sbyte.MinValue;
offset_i32 = int.MinValue;
foreach (OpCode op in Enum.GetValues(typeof(OpCode)))
{
using (var script = new ScriptBuilder())
{
if (op < OpCode.JMP || op > OpCode.JMPLE_L)
{
Assert.ThrowsException<ArgumentOutOfRangeException>(() => script.EmitJump(op, offset_i8));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => script.EmitJump(op, offset_i32));
}
else
{
script.EmitJump(op, offset_i8);
script.EmitJump(op, offset_i32);
if ((int)op % 2 == 0)
CollectionAssert.AreEqual(new[] { (byte)op, (byte)offset_i8, (byte)(op + 1) }.Concat(BitConverter.GetBytes(offset_i32)).ToArray(), script.ToArray());
else
CollectionAssert.AreEqual(new[] { (byte)op }.Concat(BitConverter.GetBytes((int)offset_i8)).Concat(new[] { (byte)op }).Concat(BitConverter.GetBytes(offset_i32)).ToArray(), script.ToArray());
}
}
}
}
[TestMethod]
public void TestEmitPushBigInteger()
{
using (var script = new ScriptBuilder())
{
script.EmitPush(BigInteger.MinusOne);
CollectionAssert.AreEqual(new byte[] { 0x0F }, script.ToArray());
}
using (var script = new ScriptBuilder())
{
script.EmitPush(BigInteger.Zero);
CollectionAssert.AreEqual(new byte[] { 0x10 }, script.ToArray());
}
for (byte x = 1; x <= 16; x++)
{
using (var script = new ScriptBuilder())
{
script.EmitPush(new BigInteger(x));
CollectionAssert.AreEqual(new byte[] { (byte)(OpCode.PUSH0 + x) }, script.ToArray());
}
}
CollectionAssert.AreEqual("0080".FromHexString(), new ScriptBuilder().EmitPush(sbyte.MinValue).ToArray());
CollectionAssert.AreEqual("007f".FromHexString(), new ScriptBuilder().EmitPush(sbyte.MaxValue).ToArray());
CollectionAssert.AreEqual("01ff00".FromHexString(), new ScriptBuilder().EmitPush(byte.MaxValue).ToArray());
CollectionAssert.AreEqual("010080".FromHexString(), new ScriptBuilder().EmitPush(short.MinValue).ToArray());
CollectionAssert.AreEqual("01ff7f".FromHexString(), new ScriptBuilder().EmitPush(short.MaxValue).ToArray());
CollectionAssert.AreEqual("02ffff0000".FromHexString(), new ScriptBuilder().EmitPush(ushort.MaxValue).ToArray());
CollectionAssert.AreEqual("0200000080".FromHexString(), new ScriptBuilder().EmitPush(int.MinValue).ToArray());
CollectionAssert.AreEqual("02ffffff7f".FromHexString(), new ScriptBuilder().EmitPush(int.MaxValue).ToArray());
CollectionAssert.AreEqual("03ffffffff00000000".FromHexString(), new ScriptBuilder().EmitPush(uint.MaxValue).ToArray());
CollectionAssert.AreEqual("030000000000000080".FromHexString(), new ScriptBuilder().EmitPush(long.MinValue).ToArray());
CollectionAssert.AreEqual("03ffffffffffffff7f".FromHexString(), new ScriptBuilder().EmitPush(long.MaxValue).ToArray());
CollectionAssert.AreEqual("04ffffffffffffffff0000000000000000".FromHexString(), new ScriptBuilder().EmitPush(ulong.MaxValue).ToArray());
CollectionAssert.AreEqual("050100000000000000feffffffffffffff00000000000000000000000000000000".FromHexString(), new ScriptBuilder().EmitPush(new BigInteger(ulong.MaxValue) * new BigInteger(ulong.MaxValue)).ToArray());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => new ScriptBuilder().EmitPush(
new BigInteger("050100000000000000feffffffffffffff0100000000000000feffffffffffffff00000000000000000000000000000000".FromHexString())));
}
[TestMethod]
public void TestEmitPushBool()
{
using (var script = new ScriptBuilder())
{
script.EmitPush(true);
CollectionAssert.AreEqual(new byte[] { (byte)OpCode.PUSH1 }, script.ToArray());
}
using (var script = new ScriptBuilder())
{
script.EmitPush(false);
CollectionAssert.AreEqual(new byte[] { (byte)OpCode.PUSH0 }, script.ToArray());
}
}
[TestMethod]
public void TestEmitPushByteArray()
{
using (var script = new ScriptBuilder())
{
Assert.ThrowsException<ArgumentNullException>(() => script.EmitPush((byte[])null));
}
using (var script = new ScriptBuilder())
{
var data = RandomHelper.RandBuffer(0x4C);
script.EmitPush(data);
CollectionAssert.AreEqual(new byte[] { (byte)OpCode.PUSHDATA1, (byte)data.Length }.Concat(data).ToArray(), script.ToArray());
}
using (var script = new ScriptBuilder())
{
var data = RandomHelper.RandBuffer(0x100);
script.EmitPush(data);
CollectionAssert.AreEqual(new byte[] { (byte)OpCode.PUSHDATA2 }.Concat(BitConverter.GetBytes((short)data.Length)).Concat(data).ToArray(), script.ToArray());
}
using (var script = new ScriptBuilder())
{
var data = RandomHelper.RandBuffer(0x10000);
script.EmitPush(data);
CollectionAssert.AreEqual(new byte[] { (byte)OpCode.PUSHDATA4 }.Concat(BitConverter.GetBytes(data.Length)).Concat(data).ToArray(), script.ToArray());
}
}
[TestMethod]
public void TestEmitPushString()
{
using (var script = new ScriptBuilder())
{
Assert.ThrowsException<ArgumentNullException>(() => script.EmitPush((string)null));
}
using (var script = new ScriptBuilder())
{
var data = RandomHelper.RandString(0x4C);
script.EmitPush(data);
CollectionAssert.AreEqual(new byte[] { (byte)OpCode.PUSHDATA1, (byte)data.Length }.Concat(Encoding.UTF8.GetBytes(data)).ToArray(), script.ToArray());
}
using (var script = new ScriptBuilder())
{
var data = RandomHelper.RandString(0x100);
script.EmitPush(data);
CollectionAssert.AreEqual(new byte[] { (byte)OpCode.PUSHDATA2 }.Concat(BitConverter.GetBytes((short)data.Length)).Concat(Encoding.UTF8.GetBytes(data)).ToArray(), script.ToArray());
}
using (var script = new ScriptBuilder())
{
var data = RandomHelper.RandString(0x10000);
script.EmitPush(data);
CollectionAssert.AreEqual(new byte[] { (byte)OpCode.PUSHDATA4 }.Concat(BitConverter.GetBytes(data.Length)).Concat(Encoding.UTF8.GetBytes(data)).ToArray(), script.ToArray());
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PublicIPAddressesOperations operations.
/// </summary>
internal partial class PublicIPAddressesOperations : IServiceOperations<NetworkClient>, IPublicIPAddressesOperations
{
/// <summary>
/// Initializes a new instance of the PublicIPAddressesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PublicIPAddressesOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified public IP address in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PublicIPAddress>> GetWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (publicIpAddressName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("publicIpAddressName", publicIpAddressName);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{publicIpAddressName}", System.Uri.EscapeDataString(publicIpAddressName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PublicIPAddress>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a static or dynamic public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP address.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update public IP address operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<PublicIPAddress>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<PublicIPAddress> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the public IP addresses in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PublicIPAddress>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all public IP addresses in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PublicIPAddress>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the subnet.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (publicIpAddressName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("publicIpAddressName", publicIpAddressName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{publicIpAddressName}", System.Uri.EscapeDataString(publicIpAddressName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a static or dynamic public IP address.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='publicIpAddressName'>
/// The name of the public IP address.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update public IP address operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PublicIPAddress>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (publicIpAddressName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("publicIpAddressName", publicIpAddressName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{publicIpAddressName}", System.Uri.EscapeDataString(publicIpAddressName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PublicIPAddress>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the public IP addresses in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PublicIPAddress>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all public IP addresses in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<PublicIPAddress>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------
//------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
namespace System.Runtime.Serialization.Json
{
internal class JavaScriptSerializer
{
private Stream _outputStream;
public JavaScriptSerializer(Stream stream)
{
_outputStream = stream;
}
public void SerializeObject(object obj)
{
StringBuilder sb = new StringBuilder();
SerializeValue(obj, sb, 0, null);
byte[] encodedBytes = Encoding.UTF8.GetBytes(sb.ToString());
_outputStream.Write(encodedBytes, 0, encodedBytes.Length);
}
private static void SerializeBoolean(bool o, StringBuilder sb)
{
if (o)
{
sb.Append(Globals.True);
}
else
{
sb.Append(Globals.False);
}
}
private static void SerializeUri(Uri uri, StringBuilder sb)
{
SerializeString(uri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped), sb);
}
private static void SerializeGuid(Guid guid, StringBuilder sb)
{
sb.Append("\"").Append(guid.ToString()).Append("\"");
}
private static void SerializeDateTime(DateTime value, StringBuilder sb)
{
sb.Append(@"""\/Date(");
DateTime valueUtc = value.ToUniversalTime();
sb.Append((valueUtc.Ticks - JsonGlobals.unixEpochTicks) / 10000);
switch (value.Kind)
{
case DateTimeKind.Unspecified:
case DateTimeKind.Local:
TimeSpan ts = DateTime.SpecifyKind(value, DateTimeKind.Utc).Subtract(valueUtc);
if (ts.Ticks < 0)
{
sb.Append("-");
}
else
{
sb.Append("+");
}
int hours = Math.Abs(ts.Hours);
sb.Append((hours < 10) ? "0" + hours : hours.ToString(CultureInfo.InvariantCulture));
int minutes = Math.Abs(ts.Minutes);
sb.Append((minutes < 10) ? "0" + minutes : minutes.ToString(CultureInfo.InvariantCulture));
break;
case DateTimeKind.Utc:
break;
}
sb.Append(@")\/""");
}
private void SerializeDictionary(IDictionary o, StringBuilder sb, int depth, Dictionary<object, bool> objectsInUse)
{
sb.Append('{');
bool isFirstElement = true;
foreach (DictionaryEntry entry in (IDictionary)o)
{
if (!isFirstElement)
{
sb.Append(',');
}
string key = entry.Key as string;
if (key == null)
{
throw new SerializationException(SR.Format(SR.ObjectSerializer_DictionaryNotSupported, o.GetType().FullName));
}
SerializeString((string)entry.Key, sb);
sb.Append(':');
SerializeValue(entry.Value, sb, depth, objectsInUse);
isFirstElement = false;
}
sb.Append('}');
}
private void SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, int depth, Dictionary<object, bool> objectsInUse)
{
sb.Append('[');
bool isFirstElement = true;
foreach (object o in enumerable)
{
if (!isFirstElement)
{
sb.Append(',');
}
SerializeValue(o, sb, depth, objectsInUse);
isFirstElement = false;
}
sb.Append(']');
}
private static void SerializeString(string input, StringBuilder sb)
{
sb.Append('"');
sb.Append(JavaScriptString.QuoteString(input));
sb.Append('"');
}
private void SerializeValue(object o, StringBuilder sb, int depth, Dictionary<object, bool> objectsInUse)
{
SerializeValueInternal(o, sb, depth, objectsInUse);
}
private class ReferenceComparer : IEqualityComparer<object>
{
bool IEqualityComparer<object>.Equals(object x, object y)
{
return x == y;
}
int IEqualityComparer<object>.GetHashCode(object obj)
{
return obj.GetHashCode();
}
}
private void SerializeValueInternal(object o, StringBuilder sb, int depth, Dictionary<object, bool> objectsInUse)
{
if (o == null || Globals.IsDBNullValue(o))
{
sb.Append("null");
return;
}
string os = o as String;
if (os != null)
{
SerializeString(os, sb);
return;
}
if (o is Char)
{
SerializeString(XmlConvert.ToString((char)o), sb);
return;
}
if (o is bool)
{
SerializeBoolean((bool)o, sb);
return;
}
if (o is DateTime)
{
SerializeDateTime((DateTime)o, sb);
return;
}
if (o is Guid)
{
SerializeGuid((Guid)o, sb);
return;
}
Uri uri = o as Uri;
if (uri != null)
{
SerializeUri(uri, sb);
return;
}
if (o is double)
{
double d = (double)o;
if (double.IsInfinity(d))
{
if (double.IsNegativeInfinity(d))
sb.Append(JsonGlobals.NegativeInf);
else
sb.Append(JsonGlobals.PositiveInf);
}
else
{
sb.Append(d.ToString("r", CultureInfo.InvariantCulture));
}
return;
}
if (o is float)
{
float f = (float)o;
if (float.IsInfinity(f))
{
if (float.IsNegativeInfinity(f))
sb.Append(JsonGlobals.NegativeInf);
else
sb.Append(JsonGlobals.PositiveInf);
}
else
{
sb.Append(f.ToString("r", CultureInfo.InvariantCulture));
}
return;
}
if (o.GetType().GetTypeInfo().IsPrimitive || o is Decimal)
{
sb.Append(Convert.ToString(o, CultureInfo.InvariantCulture));
return;
}
if (o.GetType() == typeof(object))
{
sb.Append("{}");
return;
}
Type type = o.GetType();
if (type.GetTypeInfo().IsEnum)
{
sb.Append((int)o);
return;
}
try
{
if (objectsInUse == null)
{
objectsInUse = new Dictionary<object, bool>(new ReferenceComparer());
}
else if (objectsInUse.ContainsKey(o))
{
throw new InvalidOperationException(SR.Format(SR.JsonCircularReferenceDetected, type.FullName));
}
objectsInUse.Add(o, true);
IDictionary od = o as IDictionary;
if (od != null)
{
SerializeDictionary(od, sb, depth, objectsInUse);
return;
}
IEnumerable oenum = o as IEnumerable;
if (oenum != null)
{
SerializeEnumerable(oenum, sb, depth, objectsInUse);
return;
}
//SerializeCustomObject(o, sb, depth, objectsInUse);
}
finally
{
if (objectsInUse != null)
{
objectsInUse.Remove(o);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsCustomBaseUri
{
using Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PathsOperations operations.
/// </summary>
internal partial class PathsOperations : IServiceOperations<AutoRestParameterizedHostTestClient>, IPathsOperations
{
/// <summary>
/// Initializes a new instance of the PathsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PathsOperations(AutoRestParameterizedHostTestClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestParameterizedHostTestClient
/// </summary>
public AutoRestParameterizedHostTestClient Client { get; private set; }
/// <summary>
/// Get a 200 to test a valid base uri
/// </summary>
/// <param name='accountName'>
/// Account Name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetEmptyWithHttpMessagesAsync(string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (Client.Host == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.Host");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "customuri";
_url = _url.Replace("{accountName}", accountName);
_url = _url.Replace("{host}", Client.Host);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using Razorvine.Pickle.Objects;
namespace Razorvine.Pickle
{
/// <summary>
/// Unpickles an object graph from a pickle data inputstream.
/// Maps the python objects on the corresponding java equivalents or similar types.
/// See the README.txt for a table with the type mappings.
/// </summary>
public class Unpickler : IDisposable {
private const int HIGHEST_PROTOCOL = 3;
private PickleUtils pu;
private IDictionary<int, object> memo;
private UnpickleStack stack;
private static IDictionary<string, IObjectConstructor> objectConstructors;
static Unpickler() {
objectConstructors = new Dictionary<string, IObjectConstructor>();
objectConstructors["__builtin__.complex"] = new AnyClassConstructor(typeof(ComplexNumber));
objectConstructors["builtins.complex"] = new AnyClassConstructor(typeof(ComplexNumber));
objectConstructors["array.array"] = new ArrayConstructor();
objectConstructors["array._array_reconstructor"] = new ArrayConstructor();
objectConstructors["__builtin__.bytearray"] = new ByteArrayConstructor();
objectConstructors["builtins.bytearray"] =new ByteArrayConstructor();
objectConstructors["__builtin__.bytes"] = new ByteArrayConstructor();
objectConstructors["__builtin__.set"] = new SetConstructor();
objectConstructors["builtins.set"] = new SetConstructor();
objectConstructors["datetime.datetime"] = new DateTimeConstructor(DateTimeConstructor.PythonType.DATETIME);
objectConstructors["datetime.time"] = new DateTimeConstructor(DateTimeConstructor.PythonType.TIME);
objectConstructors["datetime.date"] = new DateTimeConstructor(DateTimeConstructor.PythonType.DATE);
objectConstructors["datetime.timedelta"] = new DateTimeConstructor(DateTimeConstructor.PythonType.TIMEDELTA);
objectConstructors["decimal.Decimal"] = new DecimalConstructor();
}
/**
* Create an unpickler.
*/
public Unpickler() {
memo = new Dictionary<int, object>();
}
/**
* Register additional object constructors for custom classes.
*/
public static void registerConstructor(string module, string classname, IObjectConstructor constructor) {
objectConstructors[module + "." + classname]=constructor;
}
/**
* Read a pickled object representation from the given input stream.
*
* @return the reconstituted object hierarchy specified in the file.
*/
public object load(Stream stream) {
pu = new PickleUtils(stream);
stack = new UnpickleStack();
try {
while (true) {
byte key = pu.readbyte();
dispatch(key);
}
} catch (StopException x) {
return x.value;
}
}
/**
* Read a pickled object representation from the given pickle data bytes.
*
* @return the reconstituted object hierarchy specified in the file.
*/
public object loads(byte[] pickledata) {
return load(new MemoryStream(pickledata));
}
/**
* Close the unpickler and frees the resources such as the unpickle stack and memo table.
*/
public void close() {
if(stack!=null) stack.clear();
if(memo!=null) memo.Clear();
}
private class StopException : Exception {
public StopException(object value) {
this.value = value;
}
public object value;
}
/**
* Process a single pickle stream opcode.
*/
protected void dispatch(short key) {
switch (key) {
case Opcodes.MARK:
load_mark();
break;
case Opcodes.STOP:
object value = stack.pop();
stack.clear();
throw new StopException(value);
case Opcodes.POP:
load_pop();
break;
case Opcodes.POP_MARK:
load_pop_mark();
break;
case Opcodes.DUP:
load_dup();
break;
case Opcodes.FLOAT:
load_float();
break;
case Opcodes.INT:
load_int();
break;
case Opcodes.BININT:
load_binint();
break;
case Opcodes.BININT1:
load_binint1();
break;
case Opcodes.LONG:
load_long();
break;
case Opcodes.BININT2:
load_binint2();
break;
case Opcodes.NONE:
load_none();
break;
case Opcodes.PERSID:
throw new InvalidOpcodeException("opcode not implemented: PERSID");
case Opcodes.BINPERSID:
throw new InvalidOpcodeException("opcode not implemented: BINPERSID");
case Opcodes.REDUCE:
load_reduce();
break;
case Opcodes.STRING:
load_string();
break;
case Opcodes.BINSTRING:
load_binstring();
break;
case Opcodes.SHORT_BINSTRING:
load_short_binstring();
break;
case Opcodes.UNICODE:
load_unicode();
break;
case Opcodes.BINUNICODE:
load_binunicode();
break;
case Opcodes.APPEND:
load_append();
break;
case Opcodes.BUILD:
load_build();
break;
case Opcodes.GLOBAL:
load_global();
break;
case Opcodes.DICT:
load_dict();
break;
case Opcodes.EMPTY_DICT:
load_empty_dictionary();
break;
case Opcodes.APPENDS:
load_appends();
break;
case Opcodes.GET:
load_get();
break;
case Opcodes.BINGET:
load_binget();
break;
case Opcodes.INST:
throw new InvalidOpcodeException("opcode not implemented: INST");
case Opcodes.LONG_BINGET:
load_long_binget();
break;
case Opcodes.LIST:
load_list();
break;
case Opcodes.EMPTY_LIST:
load_empty_list();
break;
case Opcodes.OBJ:
throw new InvalidOpcodeException("opcode not implemented: OBJ");
case Opcodes.PUT:
load_put();
break;
case Opcodes.BINPUT:
load_binput();
break;
case Opcodes.LONG_BINPUT:
load_long_binput();
break;
case Opcodes.SETITEM:
load_setitem();
break;
case Opcodes.TUPLE:
load_tuple();
break;
case Opcodes.EMPTY_TUPLE:
load_empty_tuple();
break;
case Opcodes.SETITEMS:
load_setitems();
break;
case Opcodes.BINFLOAT:
load_binfloat();
break;
// protocol 2
case Opcodes.PROTO:
load_proto();
break;
case Opcodes.NEWOBJ:
load_newobj();
break;
case Opcodes.EXT1:
throw new InvalidOpcodeException("opcode not implemented: EXT1");
case Opcodes.EXT2:
throw new InvalidOpcodeException("opcode not implemented: EXT2");
case Opcodes.EXT4:
throw new InvalidOpcodeException("opcode not implemented: EXT4");
case Opcodes.TUPLE1:
load_tuple1();
break;
case Opcodes.TUPLE2:
load_tuple2();
break;
case Opcodes.TUPLE3:
load_tuple3();
break;
case Opcodes.NEWTRUE:
load_true();
break;
case Opcodes.NEWFALSE:
load_false();
break;
case Opcodes.LONG1:
load_long1();
break;
case Opcodes.LONG4:
load_long4();
break;
// Protocol 3 (Python 3.x)
case Opcodes.BINBYTES:
load_binbytes();
break;
case Opcodes.SHORT_BINBYTES:
load_short_binbytes();
break;
default:
throw new InvalidOpcodeException("invalid pickle opcode: " + key);
}
}
void load_build() {
object args=stack.pop();
object target=stack.peek();
object[] arguments=new object[] {args};
Type[] argumentTypes=new Type[] {args.GetType()};
// call the __setstate__ method with the given arguments
try {
MethodInfo setStateMethod=target.GetType().GetMethod("__setstate__", argumentTypes);
if(setStateMethod==null) {
throw new PickleException(string.Format("no __setstate__() found in type {0} with argument type {1}", target.GetType(), args.GetType()));
}
setStateMethod.Invoke(target, arguments);
} catch(Exception e) {
throw new PickleException("failed to __setstate__()",e);
}
}
void load_proto() {
byte proto = pu.readbyte();
if (proto > HIGHEST_PROTOCOL)
throw new PickleException("unsupported pickle protocol: " + proto);
}
void load_none() {
stack.add(null);
}
void load_false() {
stack.add(false);
}
void load_true() {
stack.add(true);
}
void load_int() {
string data = pu.readline(true);
object val;
if (data==Opcodes.FALSE.Substring(1))
val = false;
else if (data==Opcodes.TRUE.Substring(1))
val = true;
else {
string number=data.Substring(0, data.Length - 1);
try {
val=int.Parse(number);
} catch (OverflowException) {
// hmm, integer didnt' work.. is it perhaps an int from a 64-bit python? so try long:
val = long.Parse(number);
}
}
stack.add(val);
}
void load_binint() {
int integer = PickleUtils.bytes_to_integer(pu.readbytes(4));
stack.add(integer);
}
void load_binint1() {
stack.add((int)pu.readbyte());
}
void load_binint2() {
int integer = PickleUtils.bytes_to_integer(pu.readbytes(2));
stack.add(integer);
}
void load_long() {
string val = pu.readline();
if (val.EndsWith("L")) {
val = val.Substring(0, val.Length - 1);
}
long longvalue;
if(long.TryParse(val, out longvalue)) {
stack.add(longvalue);
} else {
throw new PickleException("long too large in load_long (need BigInt)");
}
}
void load_long1() {
byte n = pu.readbyte();
byte[] data = pu.readbytes(n);
stack.add(pu.decode_long(data));
}
void load_long4() {
int n = PickleUtils.bytes_to_integer(pu.readbytes(4));
byte[] data = pu.readbytes(n);
stack.add(pu.decode_long(data));
}
void load_float() {
string val = pu.readline(true);
double d=double.Parse(val, NumberStyles.Float|NumberStyles.AllowDecimalPoint|NumberStyles.AllowLeadingSign, NumberFormatInfo.InvariantInfo);
stack.add(d);
}
void load_binfloat() {
double val = PickleUtils.bytes_to_double(pu.readbytes(8),0);
stack.add(val);
}
void load_string() {
string rep = pu.readline();
bool quotesOk = false;
foreach (string q in new string[] { "\"", "'" }) // double or single quote
{
if (rep.StartsWith(q)) {
if (!rep.EndsWith(q)) {
throw new PickleException("insecure string pickle");
}
rep = rep.Substring(1, rep.Length - 2); // strip quotes
quotesOk = true;
break;
}
}
if (!quotesOk)
throw new PickleException("insecure string pickle");
stack.add(pu.decode_escaped(rep));
}
void load_binstring() {
int len = PickleUtils.bytes_to_integer(pu.readbytes(4));
byte[] data = pu.readbytes(len);
stack.add(PickleUtils.rawStringFromBytes(data));
}
void load_binbytes() {
int len = PickleUtils.bytes_to_integer(pu.readbytes(4));
stack.add(pu.readbytes(len));
}
void load_unicode() {
string str=pu.decode_unicode_escaped(pu.readline());
stack.add(str);
}
void load_binunicode() {
int len = PickleUtils.bytes_to_integer(pu.readbytes(4));
byte[] data = pu.readbytes(len);
stack.add(Encoding.UTF8.GetString(data));
}
void load_short_binstring() {
byte len = pu.readbyte();
byte[] data = pu.readbytes(len);
stack.add(PickleUtils.rawStringFromBytes(data));
}
void load_short_binbytes() {
byte len = pu.readbyte();
stack.add(pu.readbytes(len));
}
void load_tuple() {
ArrayList top=stack.pop_all_since_marker();
stack.add(top.ToArray());
}
void load_empty_tuple() {
stack.add(new object[0]);
}
void load_tuple1() {
stack.add(new object[] { stack.pop() });
}
void load_tuple2() {
object o2 = stack.pop();
object o1 = stack.pop();
stack.add(new object[] { o1, o2 });
}
void load_tuple3() {
object o3 = stack.pop();
object o2 = stack.pop();
object o1 = stack.pop();
stack.add(new object[] { o1, o2, o3 });
}
void load_empty_list() {
stack.add(new ArrayList(5));
}
void load_empty_dictionary() {
stack.add(new Hashtable(5));
}
void load_list() {
ArrayList top = stack.pop_all_since_marker();
stack.add(top); // simply add the top items as a list to the stack again
}
void load_dict() {
ArrayList top = stack.pop_all_since_marker();
Hashtable map=new Hashtable(top.Count);
for (int i = 0; i < top.Count; i += 2) {
object key = top[i];
object value = top[i+1];
map[key]=value;
}
stack.add(map);
}
void load_global() {
IObjectConstructor constructor;
string module = pu.readline();
string name = pu.readline();
string key=module+"."+name;
if(objectConstructors.ContainsKey(key)) {
constructor = objectConstructors[module + "." + name];
} else {
// check if it is an exception
if(module=="exceptions") {
constructor=new AnyClassConstructor(typeof(PythonException));
} else {
throw new PickleException("unsupported class: " + module + "." + name);
}
}
stack.add(constructor);
}
void load_pop() {
stack.pop();
}
void load_pop_mark() {
object o = null;
do {
o = stack.pop();
} while (o != stack.MARKER);
stack.trim();
}
void load_dup() {
stack.add(stack.peek());
}
void load_get() {
int i = int.Parse(pu.readline());
if(!memo.ContainsKey(i)) throw new PickleException("invalid memo key");
stack.add(memo[i]);
}
void load_binget() {
byte i = pu.readbyte();
if(!memo.ContainsKey(i)) throw new PickleException("invalid memo key");
stack.add(memo[(int)i]);
}
void load_long_binget() {
int i = PickleUtils.bytes_to_integer(pu.readbytes(4));
if(!memo.ContainsKey(i)) throw new PickleException("invalid memo key");
stack.add(memo[i]);
}
void load_put() {
int i = int.Parse(pu.readline());
memo[i]=stack.peek();
}
void load_binput() {
byte i = pu.readbyte();
memo[(int)i]=stack.peek();
}
void load_long_binput() {
int i = PickleUtils.bytes_to_integer(pu.readbytes(4));
memo[i]=stack.peek();
}
void load_append() {
object value = stack.pop();
ArrayList list = (ArrayList) stack.peek();
list.Add(value);
}
void load_appends() {
ArrayList top = stack.pop_all_since_marker();
ArrayList list = (ArrayList) stack.peek();
list.AddRange(top);
list.TrimToSize();
}
void load_setitem() {
object value = stack.pop();
object key = stack.pop();
Hashtable dict=(Hashtable)stack.peek();
dict[key]=value;
}
void load_setitems() {
var newitems=new List<KeyValuePair<object,object>>();
object value = stack.pop();
while (value != stack.MARKER) {
object key = stack.pop();
newitems.Add(new KeyValuePair<object,object>(key,value));
value = stack.pop();
}
Hashtable dict=(Hashtable)stack.peek();
foreach(var item in newitems) {
dict[item.Key]=item.Value;
}
}
void load_mark() {
stack.add_mark();
}
void load_reduce() {
object[] args = (object[]) stack.pop();
IObjectConstructor constructor = (IObjectConstructor) stack.pop();
stack.add(constructor.construct(args));
}
void load_newobj() {
load_reduce(); // for Java we just do the same as class(*args) instead
// of class.__new__(class,*args)
}
public void Dispose()
{
this.close();
}
}
}
| |
//
// HttpRequestHeaders.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
//
// Copyright (C) 2011 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace System.Net.Http.Headers
{
public sealed class HttpRequestHeaders : HttpHeaders
{
bool? expectContinue;
internal HttpRequestHeaders ()
: base (HttpHeaderKind.Request)
{
}
public HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> Accept {
get {
return GetValues<MediaTypeWithQualityHeaderValue> ("Accept");
}
}
public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptCharset {
get {
return GetValues<StringWithQualityHeaderValue> ("Accept-Charset");
}
}
public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptEncoding {
get {
return GetValues<StringWithQualityHeaderValue> ("Accept-Encoding");
}
}
public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptLanguage {
get {
return GetValues<StringWithQualityHeaderValue> ("Accept-Language");
}
}
public AuthenticationHeaderValue Authorization {
get {
return GetValue<AuthenticationHeaderValue> ("Authorization");
}
set {
AddOrRemove ("Authorization", value);
}
}
public CacheControlHeaderValue CacheControl {
get {
return GetValue<CacheControlHeaderValue> ("Cache-Control");
}
set {
AddOrRemove ("Cache-Control", value);
}
}
public HttpHeaderValueCollection<string> Connection {
get {
return GetValues<string> ("Connection");
}
}
public bool? ConnectionClose {
get {
if (connectionclose == true || Connection.Find (l => string.Equals (l, "close", StringComparison.OrdinalIgnoreCase)) != null)
return true;
return connectionclose;
}
set {
if (connectionclose == value)
return;
Connection.Remove ("close");
if (value == true)
Connection.Add ("close");
connectionclose = value;
}
}
internal bool ConnectionKeepAlive {
get {
return Connection.Find (l => string.Equals (l, "Keep-Alive", StringComparison.OrdinalIgnoreCase)) != null;
}
}
public DateTimeOffset? Date {
get {
return GetValue<DateTimeOffset?> ("Date");
}
set {
AddOrRemove ("Date", value, Parser.DateTime.ToString);
}
}
public HttpHeaderValueCollection<NameValueWithParametersHeaderValue> Expect {
get {
return GetValues<NameValueWithParametersHeaderValue> ("Expect");
}
}
public bool? ExpectContinue {
get {
if (expectContinue.HasValue)
return expectContinue;
var found = TransferEncoding.Find (l => string.Equals (l.Value, "100-continue", StringComparison.OrdinalIgnoreCase));
return found != null ? true : (bool?) null;
}
set {
if (expectContinue == value)
return;
Expect.Remove (l => l.Name == "100-continue");
if (value == true)
Expect.Add (new NameValueWithParametersHeaderValue ("100-continue"));
expectContinue = value;
}
}
public string From {
get {
return GetValue<string> ("From");
}
set {
if (!string.IsNullOrEmpty (value) && !Parser.EmailAddress.TryParse (value, out value))
throw new FormatException ();
AddOrRemove ("From", value);
}
}
public string Host {
get {
return GetValue<string> ("Host");
}
set {
AddOrRemove ("Host", value);
}
}
public HttpHeaderValueCollection<EntityTagHeaderValue> IfMatch {
get {
return GetValues<EntityTagHeaderValue> ("If-Match");
}
}
public DateTimeOffset? IfModifiedSince {
get {
return GetValue<DateTimeOffset?> ("If-Modified-Since");
}
set {
AddOrRemove ("If-Modified-Since", value, Parser.DateTime.ToString);
}
}
public HttpHeaderValueCollection<EntityTagHeaderValue> IfNoneMatch {
get {
return GetValues<EntityTagHeaderValue> ("If-None-Match");
}
}
public RangeConditionHeaderValue IfRange {
get {
return GetValue<RangeConditionHeaderValue> ("If-Range");
}
set {
AddOrRemove ("If-Range", value);
}
}
public DateTimeOffset? IfUnmodifiedSince {
get {
return GetValue<DateTimeOffset?> ("If-Unmodified-Since");
}
set {
AddOrRemove ("If-Unmodified-Since", value, Parser.DateTime.ToString);
}
}
public int? MaxForwards {
get {
return GetValue<int?> ("Max-Forwards");
}
set {
AddOrRemove ("Max-Forwards", value);
}
}
public HttpHeaderValueCollection<NameValueHeaderValue> Pragma {
get {
return GetValues<NameValueHeaderValue> ("Pragma");
}
}
public AuthenticationHeaderValue ProxyAuthorization {
get {
return GetValue<AuthenticationHeaderValue> ("Proxy-Authorization");
}
set {
AddOrRemove ("Proxy-Authorization", value);
}
}
public RangeHeaderValue Range {
get {
return GetValue<RangeHeaderValue> ("Range");
}
set {
AddOrRemove ("Range", value);
}
}
public Uri Referrer {
get {
return GetValue<Uri> ("Referer");
}
set {
AddOrRemove ("Referer", value);
}
}
public HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue> TE {
get {
return GetValues<TransferCodingWithQualityHeaderValue> ("TE");
}
}
public HttpHeaderValueCollection<string> Trailer {
get {
return GetValues<string> ("Trailer");
}
}
public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding {
get {
return GetValues<TransferCodingHeaderValue> ("Transfer-Encoding");
}
}
public bool? TransferEncodingChunked {
get {
if (transferEncodingChunked.HasValue)
return transferEncodingChunked;
var found = TransferEncoding.Find (l => string.Equals (l.Value, "chunked", StringComparison.OrdinalIgnoreCase));
return found != null ? true : (bool?) null;
}
set {
if (value == transferEncodingChunked)
return;
TransferEncoding.Remove (l => l.Value == "chunked");
if (value == true)
TransferEncoding.Add (new TransferCodingHeaderValue ("chunked"));
transferEncodingChunked = value;
}
}
public HttpHeaderValueCollection<ProductHeaderValue> Upgrade {
get {
return GetValues<ProductHeaderValue> ("Upgrade");
}
}
public HttpHeaderValueCollection<ProductInfoHeaderValue> UserAgent {
get {
return GetValues<ProductInfoHeaderValue> ("User-Agent");
}
}
public HttpHeaderValueCollection<ViaHeaderValue> Via {
get {
return GetValues<ViaHeaderValue> ("Via");
}
}
public HttpHeaderValueCollection<WarningHeaderValue> Warning {
get {
return GetValues<WarningHeaderValue> ("Warning");
}
}
internal void AddHeaders (HttpRequestHeaders headers)
{
foreach (var header in headers) {
TryAddWithoutValidation (header.Key, header.Value);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Internal.Cryptography;
using ErrorCode = Interop.NCrypt.ErrorCode;
using KeyBlobMagicNumber = Interop.BCrypt.KeyBlobMagicNumber;
using BCRYPT_RSAKEY_BLOB = Interop.BCrypt.BCRYPT_RSAKEY_BLOB;
namespace System.Security.Cryptography
{
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
internal static partial class RSAImplementation
{
#endif
public sealed partial class RSACng : RSA
{
/// <summary>
/// <para>
/// ImportParameters will replace the existing key that RSACng is working with by creating a
/// new CngKey for the parameters structure. If the parameters structure contains only an
/// exponent and modulus, then only a public key will be imported. If the parameters also
/// contain P and Q values, then a full key pair will be imported.
/// </para>
/// </summary>
/// <exception cref="ArgumentException">
/// if <paramref name="parameters" /> contains neither an exponent nor a modulus.
/// </exception>
/// <exception cref="CryptographicException">
/// if <paramref name="parameters" /> is not a valid RSA key or if <paramref name="parameters"
/// /> is a full key pair and the default KSP is used.
/// </exception>
public override void ImportParameters(RSAParameters parameters)
{
unsafe
{
if (parameters.Exponent == null || parameters.Modulus == null)
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
bool includePrivate;
if (parameters.D == null)
{
includePrivate = false;
if (parameters.P != null || parameters.DP != null || parameters.Q != null || parameters.DQ != null || parameters.InverseQ != null)
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
}
else
{
includePrivate = true;
if (parameters.P == null || parameters.DP == null || parameters.Q == null || parameters.DQ == null || parameters.InverseQ == null)
throw new CryptographicException(SR.Cryptography_InvalidRsaParameters);
}
//
// We need to build a key blob structured as follows:
//
// BCRYPT_RSAKEY_BLOB header
// byte[cbPublicExp] publicExponent - Exponent
// byte[cbModulus] modulus - Modulus
// -- Only if "includePrivate" is true --
// byte[cbPrime1] prime1 - P
// byte[cbPrime2] prime2 - Q
// ------------------
//
int blobSize = sizeof(BCRYPT_RSAKEY_BLOB) +
parameters.Exponent.Length +
parameters.Modulus.Length;
if (includePrivate)
{
blobSize += parameters.P.Length +
parameters.Q.Length;
}
byte[] rsaBlob = new byte[blobSize];
fixed (byte* pRsaBlob = rsaBlob)
{
// Build the header
BCRYPT_RSAKEY_BLOB* pBcryptBlob = (BCRYPT_RSAKEY_BLOB*)pRsaBlob;
pBcryptBlob->Magic = includePrivate ? KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC : KeyBlobMagicNumber.BCRYPT_RSAPUBLIC_MAGIC;
pBcryptBlob->BitLength = parameters.Modulus.Length * 8;
pBcryptBlob->cbPublicExp = parameters.Exponent.Length;
pBcryptBlob->cbModulus = parameters.Modulus.Length;
if (includePrivate)
{
pBcryptBlob->cbPrime1 = parameters.P.Length;
pBcryptBlob->cbPrime2 = parameters.Q.Length;
}
int offset = sizeof(BCRYPT_RSAKEY_BLOB);
Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Exponent);
Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Modulus);
if (includePrivate)
{
Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.P);
Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Q);
}
// We better have computed the right allocation size above!
Debug.Assert(offset == blobSize, "offset == blobSize");
}
ImportKeyBlob(rsaBlob, includePrivate);
}
}
/// <summary>
/// Exports the key used by the RSA object into an RSAParameters object.
/// </summary>
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
byte[] rsaBlob = ExportKeyBlob(includePrivateParameters);
RSAParameters rsaParams = new RSAParameters();
ExportParameters(ref rsaParams, rsaBlob, includePrivateParameters);
return rsaParams;
}
private static void ExportParameters(ref RSAParameters rsaParams, byte[] rsaBlob, bool includePrivateParameters)
{
//
// We now have a buffer laid out as follows:
// BCRYPT_RSAKEY_BLOB header
// byte[cbPublicExp] publicExponent - Exponent
// byte[cbModulus] modulus - Modulus
// -- Private only --
// byte[cbPrime1] prime1 - P
// byte[cbPrime2] prime2 - Q
// byte[cbPrime1] exponent1 - DP
// byte[cbPrime2] exponent2 - DQ
// byte[cbPrime1] coefficient - InverseQ
// byte[cbModulus] privateExponent - D
//
KeyBlobMagicNumber magic = (KeyBlobMagicNumber)BitConverter.ToInt32(rsaBlob, 0);
// Check the magic value in the key blob header. If the blob does not have the required magic,
// then throw a CryptographicException.
CheckMagicValueOfKey(magic, includePrivateParameters);
unsafe
{
// Fail-fast if a rogue provider gave us a blob that isn't even the size of the blob header.
if (rsaBlob.Length < sizeof(BCRYPT_RSAKEY_BLOB))
throw ErrorCode.E_FAIL.ToCryptographicException();
fixed (byte* pRsaBlob = rsaBlob)
{
BCRYPT_RSAKEY_BLOB* pBcryptBlob = (BCRYPT_RSAKEY_BLOB*)pRsaBlob;
int offset = sizeof(BCRYPT_RSAKEY_BLOB);
// Read out the exponent
rsaParams.Exponent = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPublicExp);
rsaParams.Modulus = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbModulus);
if (includePrivateParameters)
{
rsaParams.P = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPrime1);
rsaParams.Q = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPrime2);
rsaParams.DP = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPrime1);
rsaParams.DQ = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPrime2);
rsaParams.InverseQ = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbPrime1);
rsaParams.D = Interop.BCrypt.Consume(rsaBlob, ref offset, pBcryptBlob->cbModulus);
}
}
}
}
/// <summary>
/// This function checks the magic value in the key blob header
/// </summary>
/// <param name="includePrivateParameters">Private blob if true else public key blob</param>
private static void CheckMagicValueOfKey(KeyBlobMagicNumber magic, bool includePrivateParameters)
{
if (includePrivateParameters)
{
if (magic != KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC && magic != KeyBlobMagicNumber.BCRYPT_RSAFULLPRIVATE_MAGIC)
{
throw new CryptographicException(SR.Cryptography_NotValidPrivateKey);
}
}
else
{
if (magic != KeyBlobMagicNumber.BCRYPT_RSAPUBLIC_MAGIC)
{
// Private key magic is permissible too since the public key can be derived from the private key blob.
if (magic != KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC && magic != KeyBlobMagicNumber.BCRYPT_RSAFULLPRIVATE_MAGIC)
{
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
}
}
}
}
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
}
#endif
}
| |
namespace MVC5EFCodeFirst.Migrations
{
using Models;
using DAL;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<SchoolContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(SchoolContext context)
{
var students = new List<Student>
{
new Student { FirstMidName = "Carson", LastName = "Alexander",
EnrollmentDate = DateTime.Parse("2010-09-01") },
new Student { FirstMidName = "Meredith", LastName = "Alonso",
EnrollmentDate = DateTime.Parse("2012-09-01") },
new Student { FirstMidName = "Arturo", LastName = "Anand",
EnrollmentDate = DateTime.Parse("2013-09-01") },
new Student { FirstMidName = "Gytis", LastName = "Barzdukas",
EnrollmentDate = DateTime.Parse("2012-09-01") },
new Student { FirstMidName = "Yan", LastName = "Li",
EnrollmentDate = DateTime.Parse("2012-09-01") },
new Student { FirstMidName = "Peggy", LastName = "Justice",
EnrollmentDate = DateTime.Parse("2011-09-01") },
new Student { FirstMidName = "Laura", LastName = "Norman",
EnrollmentDate = DateTime.Parse("2013-09-01") },
new Student { FirstMidName = "Nino", LastName = "Olivetto",
EnrollmentDate = DateTime.Parse("2005-09-01") }
};
students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
context.SaveChanges();
var instructors = new List<Instructor>
{
new Instructor { FirstMidName = "Kim", LastName = "Abercrombie",
HireDate = DateTime.Parse("1995-03-11") },
new Instructor { FirstMidName = "Fadi", LastName = "Fakhouri",
HireDate = DateTime.Parse("2002-07-06") },
new Instructor { FirstMidName = "Roger", LastName = "Harui",
HireDate = DateTime.Parse("1998-07-01") },
new Instructor { FirstMidName = "Candace", LastName = "Kapoor",
HireDate = DateTime.Parse("2001-01-15") },
new Instructor { FirstMidName = "Roger", LastName = "Zheng",
HireDate = DateTime.Parse("2004-02-12") }
};
instructors.ForEach(s => context.Instructors.AddOrUpdate(p => p.LastName, s));
context.SaveChanges();
var departments = new List<Department>
{
new Department { Name = "English", Budget = 350000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Abercrombie").ID },
new Department { Name = "Mathematics", Budget = 100000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID },
new Department { Name = "Engineering", Budget = 350000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Harui").ID },
new Department { Name = "Economics", Budget = 100000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID }
};
departments.ForEach(s => context.Departments.AddOrUpdate(p => p.Name, s));
context.SaveChanges();
var courses = new List<Course>
{
new Course {CourseID = 1050, Title = "Chemistry", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Engineering").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 1045, Title = "Calculus", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 3141, Title = "Trigonometry", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 2021, Title = "Composition", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "English").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 2042, Title = "Literature", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "English").DepartmentID,
Instructors = new List<Instructor>()
}
};
courses.ForEach(s => context.Courses.AddOrUpdate(p => p.CourseID, s));
context.SaveChanges();
var officeAssignments = new List<OfficeAssignment>
{
new OfficeAssignment {
InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID,
Location = "Smith 17" },
new OfficeAssignment {
InstructorID = instructors.Single( i => i.LastName == "Harui").ID,
Location = "Gowan 27" },
new OfficeAssignment {
InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID,
Location = "Thompson 304" },
};
officeAssignments.ForEach(s => context.OfficeAssignments.AddOrUpdate(p => p.InstructorID, s));
context.SaveChanges();
AddOrUpdateInstructor(context, "Chemistry", "Kapoor");
AddOrUpdateInstructor(context, "Chemistry", "Harui");
AddOrUpdateInstructor(context, "Microeconomics", "Zheng");
AddOrUpdateInstructor(context, "Macroeconomics", "Zheng");
AddOrUpdateInstructor(context, "Calculus", "Fakhouri");
AddOrUpdateInstructor(context, "Trigonometry", "Harui");
AddOrUpdateInstructor(context, "Composition", "Abercrombie");
AddOrUpdateInstructor(context, "Literature", "Abercrombie");
context.SaveChanges();
var enrollments = new List<Enrollment>
{
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alexander").ID,
CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID,
Grade = Grade.A
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alexander").ID,
CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID,
Grade = Grade.C
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alexander").ID,
CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alonso").ID,
CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alonso").ID,
CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alonso").ID,
CourseID = courses.Single(c => c.Title == "Composition" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Anand").ID,
CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Anand").ID,
CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Barzdukas").ID,
CourseID = courses.Single(c => c.Title == "Chemistry").CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Li").ID,
CourseID = courses.Single(c => c.Title == "Composition").CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Justice").ID,
CourseID = courses.Single(c => c.Title == "Literature").CourseID,
Grade = Grade.B
}
};
foreach (Enrollment e in enrollments)
{
var enrollmentInDataBase = context.Enrollments.Where(
s =>
s.Student.ID == e.StudentID &&
s.Course.CourseID == e.CourseID).SingleOrDefault();
if (enrollmentInDataBase == null)
{
context.Enrollments.Add(e);
}
}
context.SaveChanges();
}
void AddOrUpdateInstructor(SchoolContext context, string courseTitle, string instructorName)
{
var crs = context.Courses.Include(c => c.Instructors).SingleOrDefault(c => c.Title == courseTitle);
var inst = crs.Instructors.SingleOrDefault(i => i.LastName == instructorName);
if (inst == null)
crs.Instructors.Add(context.Instructors.Single(i => i.LastName == instructorName));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ServiceModel.Syndication
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
[XmlRoot(ElementName = Rss20Constants.RssTag, Namespace = Rss20Constants.Rss20Namespace)]
public class Rss20FeedFormatter : SyndicationFeedFormatter
{
private static readonly XmlQualifiedName s_rss20Domain = new XmlQualifiedName(Rss20Constants.DomainTag, string.Empty);
private static readonly XmlQualifiedName s_rss20Length = new XmlQualifiedName(Rss20Constants.LengthTag, string.Empty);
private static readonly XmlQualifiedName s_rss20Type = new XmlQualifiedName(Rss20Constants.TypeTag, string.Empty);
private static readonly XmlQualifiedName s_rss20Url = new XmlQualifiedName(Rss20Constants.UrlTag, string.Empty);
private static List<string> s_acceptedDays = new List<string> { "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday" };
private const string Rfc822OutputLocalDateTimeFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
private const string Rfc822OutputUtcDateTimeFormat = "ddd, dd MMM yyyy HH:mm:ss Z";
private Atom10FeedFormatter _atomSerializer;
private Type _feedType;
private int _maxExtensionSize;
private bool _preserveAttributeExtensions;
private bool _preserveElementExtensions;
private bool _serializeExtensionsAsAtom;
//Custom Parsers
// value, localname , ns , result
public Func<string, string, string, string> StringParser { get; set; } = DefaultStringParser;
public Func<string, string, string, DateTimeOffset> DateParser { get; set; } = DefaultDateParser;
public Func<string, string, string, Uri> UriParser { get; set; } = DefaultUriParser;
static private string DefaultStringParser(string value, string localName, string ns)
{
return value;
}
static private Uri DefaultUriParser(string value, string localName, string ns)
{
return new Uri(value, UriKind.RelativeOrAbsolute);
}
private async Task<bool> OnReadImage(XmlReaderWrapper reader, SyndicationFeed result)
{
await reader.ReadStartElementAsync();
string localName = string.Empty;
while (await reader.IsStartElementAsync())
{
if (await reader.IsStartElementAsync(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace))
{
result.ImageUrl = UriParser(await reader.ReadElementStringAsync(), Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace);
}
else if (await reader.IsStartElementAsync(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace))
{
result.ImageLink = UriParser(await reader.ReadElementStringAsync(), Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace);
}
else if (await reader.IsStartElementAsync(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace))
{
result.ImageTitle = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace));
}
}
await reader.ReadEndElementAsync(); // image
return true;
}
public Rss20FeedFormatter()
: this(typeof(SyndicationFeed))
{
}
public Rss20FeedFormatter(Type feedTypeToCreate)
: base()
{
if (feedTypeToCreate == null)
{
throw new ArgumentNullException(nameof(feedTypeToCreate));
}
if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate))
{
throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(feedTypeToCreate), nameof(SyndicationFeed)));
}
_serializeExtensionsAsAtom = true;
_maxExtensionSize = int.MaxValue;
_preserveElementExtensions = true;
_preserveAttributeExtensions = true;
_atomSerializer = new Atom10FeedFormatter(feedTypeToCreate);
_feedType = feedTypeToCreate;
}
public Rss20FeedFormatter(SyndicationFeed feedToWrite)
: this(feedToWrite, true)
{
}
public Rss20FeedFormatter(SyndicationFeed feedToWrite, bool serializeExtensionsAsAtom)
: base(feedToWrite)
{
// No need to check that the parameter passed is valid - it is checked by the c'tor of the base class
_serializeExtensionsAsAtom = serializeExtensionsAsAtom;
_maxExtensionSize = int.MaxValue;
_preserveElementExtensions = true;
_preserveAttributeExtensions = true;
_atomSerializer = new Atom10FeedFormatter(this.Feed);
_feedType = feedToWrite.GetType();
}
public bool PreserveAttributeExtensions
{
get { return _preserveAttributeExtensions; }
set { _preserveAttributeExtensions = value; }
}
public bool PreserveElementExtensions
{
get { return _preserveElementExtensions; }
set { _preserveElementExtensions = value; }
}
public bool SerializeExtensionsAsAtom
{
get { return _serializeExtensionsAsAtom; }
set { _serializeExtensionsAsAtom = value; }
}
public override string Version
{
get { return SyndicationVersions.Rss20; }
}
protected Type FeedType
{
get
{
return _feedType;
}
}
public override bool CanRead(XmlReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
return reader.IsStartElement(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace);
}
public override Task ReadFromAsync(XmlReader reader, CancellationToken ct)
{
if (!CanRead(reader))
{
throw new XmlException(string.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI));
}
SetFeed(CreateFeedInstance());
return ReadXmlAsync(XmlReaderWrapper.CreateFromReader(reader), this.Feed);
}
private Task WriteXmlAsync(XmlWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
return WriteFeedAsync(writer);
}
public override async Task WriteToAsync(XmlWriter writer, CancellationToken ct)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
writer = XmlWriterWrapper.CreateFromWriter(writer);
await writer.WriteStartElementAsync(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace);
await WriteFeedAsync(writer);
await writer.WriteEndElementAsync();
}
protected internal override void SetFeed(SyndicationFeed feed)
{
base.SetFeed(feed);
_atomSerializer.SetFeed(this.Feed);
}
private async Task ReadItemFromAsync(XmlReaderWrapper reader, SyndicationItem result, Uri feedBaseUri)
{
result.BaseUri = feedBaseUri;
await reader.MoveToContentAsync();
bool isEmpty = reader.IsEmptyElement;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (name == "base" && ns == Atom10FeedFormatter.XmlNs)
{
result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, await reader.GetValueAsync());
continue;
}
if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
{
continue;
}
string val = await reader.GetValueAsync();
if (!TryParseAttribute(name, ns, val, result, this.Version))
{
if (_preserveAttributeExtensions)
{
result.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
}
}
}
}
await reader.ReadStartElementAsync();
if (!isEmpty)
{
string fallbackAlternateLink = null;
XmlDictionaryWriter extWriter = null;
bool readAlternateLink = false;
try
{
XmlBuffer buffer = null;
while (await reader.IsStartElementAsync())
{
bool notHandled = false;
if (await reader.MoveToContentAsync() == XmlNodeType.Element && reader.NamespaceURI == Rss20Constants.Rss20Namespace)
{
switch (reader.LocalName)
{
case Rss20Constants.TitleTag:
result.Title = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace));
break;
case Rss20Constants.LinkTag:
result.Links.Add(await ReadAlternateLinkAsync(reader, result.BaseUri));
readAlternateLink = true;
break;
case Rss20Constants.DescriptionTag:
result.Summary = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace));
break;
case Rss20Constants.AuthorTag:
result.Authors.Add(await ReadPersonAsync(reader, result));
break;
case Rss20Constants.CategoryTag:
result.Categories.Add(await ReadCategoryAsync(reader, result));
break;
case Rss20Constants.EnclosureTag:
result.Links.Add(await ReadMediaEnclosureAsync(reader, result.BaseUri));
break;
case Rss20Constants.GuidTag:
{
bool isPermalink = true;
string permalinkString = reader.GetAttribute(Rss20Constants.IsPermaLinkTag, Rss20Constants.Rss20Namespace);
if (permalinkString != null && permalinkString.Equals("false", StringComparison.OrdinalIgnoreCase))
{
isPermalink = false;
}
string localName = reader.LocalName;
string namespaceUri = reader.NamespaceURI;
result.Id = StringParser(await reader.ReadElementStringAsync(), localName, namespaceUri);
if (isPermalink)
{
fallbackAlternateLink = result.Id;
}
break;
}
case Rss20Constants.PubDateTag:
{
bool canReadContent = !reader.IsEmptyElement;
await reader.ReadStartElementAsync();
if (canReadContent)
{
string str = await reader.ReadStringAsync();
if (!string.IsNullOrEmpty(str))
{
result.PublishDate = DateParser(str, reader.LocalName, reader.NamespaceURI);
}
await reader.ReadEndElementAsync();
}
break;
}
case Rss20Constants.SourceTag:
{
SyndicationFeed feed = new SyndicationFeed();
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (FeedUtils.IsXmlns(name, ns))
{
continue;
}
string val = await reader.GetValueAsync();
if (name == Rss20Constants.UrlTag && ns == Rss20Constants.Rss20Namespace)
{
feed.Links.Add(SyndicationLink.CreateSelfLink(UriParser(val, Rss20Constants.UrlTag, ns)));
}
else if (!FeedUtils.IsXmlns(name, ns))
{
if (_preserveAttributeExtensions)
{
feed.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
}
}
}
}
string localName = reader.LocalName;
string namespaceUri = reader.NamespaceURI;
string feedTitle = StringParser(await reader.ReadElementStringAsync(), localName, namespaceUri);
feed.Title = new TextSyndicationContent(feedTitle);
result.SourceFeed = feed;
break;
}
default:
notHandled = true;
break;
}
}
else
{
notHandled = true;
}
if (notHandled)
{
bool parsedExtension = _serializeExtensionsAsAtom && _atomSerializer.TryParseItemElementFromAsync(reader, result).Result;
if (!parsedExtension)
{
parsedExtension = TryParseElement(reader, result, this.Version);
}
if (!parsedExtension)
{
if (_preserveElementExtensions)
{
if (buffer == null)
{
buffer = new XmlBuffer(_maxExtensionSize);
extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
}
await XmlReaderWrapper.WriteNodeAsync(extWriter, reader, false);
}
else
{
await reader.SkipAsync();
}
}
}
}
LoadElementExtensions(buffer, extWriter, result);
}
finally
{
if (extWriter != null)
{
((IDisposable)extWriter).Dispose();
}
}
await reader.ReadEndElementAsync(); // item
if (!readAlternateLink && fallbackAlternateLink != null)
{
result.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(fallbackAlternateLink, UriKind.RelativeOrAbsolute)));
readAlternateLink = true;
}
// if there's no content and no alternate link set the summary as the item content
if (result.Content == null && !readAlternateLink)
{
result.Content = result.Summary;
result.Summary = null;
}
}
}
internal Task ReadItemFromAsync(XmlReaderWrapper reader, SyndicationItem result)
{
return ReadItemFromAsync(reader, result, null);
}
internal Task WriteItemContentsAsync(XmlWriter writer, SyndicationItem item)
{
writer = XmlWriterWrapper.CreateFromWriter(writer);
return WriteItemContentsAsync(writer, item, null);
}
protected override SyndicationFeed CreateFeedInstance()
{
return SyndicationFeedFormatter.CreateFeedInstance(_feedType);
}
protected virtual async Task<SyndicationItem> ReadItemAsync(XmlReader reader, SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
SyndicationItem item = CreateItem(feed);
XmlReaderWrapper readerWrapper = XmlReaderWrapper.CreateFromReader(reader);
await ReadItemFromAsync(readerWrapper, item, feed.BaseUri); // delegate => ItemParser(reader,item,feed.BaseUri);//
return item;
}
protected virtual async Task WriteItemAsync(XmlWriter writer, SyndicationItem item, Uri feedBaseUri)
{
writer = XmlWriterWrapper.CreateFromWriter(writer);
await writer.WriteStartElementAsync(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace);
await WriteItemContentsAsync(writer, item, feedBaseUri);
await writer.WriteEndElementAsync();
}
protected virtual async Task WriteItemsAsync(XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri)
{
if (items == null)
{
return;
}
foreach (SyndicationItem item in items)
{
await this.WriteItemAsync(writer, item, feedBaseUri);
}
}
private static string NormalizeTimeZone(string rfc822TimeZone, out bool isUtc)
{
isUtc = false;
// return a string in "-08:00" format
if (rfc822TimeZone[0] == '+' || rfc822TimeZone[0] == '-')
{
// the time zone is supposed to be 4 digits but some feeds omit the initial 0
StringBuilder result = new StringBuilder(rfc822TimeZone);
if (result.Length == 4)
{
// the timezone is +/-HMM. Convert to +/-HHMM
result.Insert(1, '0');
}
result.Insert(3, ':');
return result.ToString();
}
switch (rfc822TimeZone)
{
case "UT":
case "Z":
isUtc = true;
return "-00:00";
case "GMT":
return "-00:00";
case "A":
return "-01:00";
case "B":
return "-02:00";
case "C":
return "-03:00";
case "D":
case "EDT":
return "-04:00";
case "E":
case "EST":
case "CDT":
return "-05:00";
case "F":
case "CST":
case "MDT":
return "-06:00";
case "G":
case "MST":
case "PDT":
return "-07:00";
case "H":
case "PST":
return "-08:00";
case "I":
return "-09:00";
case "K":
return "-10:00";
case "L":
return "-11:00";
case "M":
return "-12:00";
case "N":
return "+01:00";
case "O":
return "+02:00";
case "P":
return "+03:00";
case "Q":
return "+04:00";
case "R":
return "+05:00";
case "S":
return "+06:00";
case "T":
return "+07:00";
case "U":
return "+08:00";
case "V":
return "+09:00";
case "W":
return "+10:00";
case "X":
return "+11:00";
case "Y":
return "+12:00";
default:
return "";
}
}
private async Task ReadSkipHoursAsync(XmlReaderWrapper reader, SyndicationFeed result)
{
await reader.ReadStartElementAsync();
while (await reader.IsStartElementAsync())
{
if (reader.LocalName == Rss20Constants.HourTag)
{
string val = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.HourTag, Rss20Constants.Rss20Namespace);
int hour = int.Parse(val);
bool parsed = false;
parsed = int.TryParse(val, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out hour);
if (parsed == false)
{
throw new ArgumentException("The number on skip hours must be an integer betwen 0 and 23.");
}
if (hour < 0 || hour > 23)
{
throw new ArgumentException("The hour can't be lower than 0 or greater than 23.");
}
result.SkipHours.Add(hour);
}
else
{
await reader.SkipAsync();
}
}
await reader.ReadEndElementAsync();
}
private bool checkDay(string day)
{
if (s_acceptedDays.Contains(day.ToLower()))
{
return true;
}
return false;
}
private async Task ReadSkipDaysAsync(XmlReaderWrapper reader, SyndicationFeed result)
{
await reader.ReadStartElementAsync();
while (await reader.IsStartElementAsync())
{
if (reader.LocalName == Rss20Constants.DayTag)
{
string day = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.DayTag, Rss20Constants.Rss20Namespace);
//Check if the day is actually an accepted day.
if (checkDay(day))
{
result.SkipDays.Add(day);
}
}
else
{
await reader.SkipAsync();
}
}
await reader.ReadEndElementAsync();
}
internal static void RemoveExtraWhiteSpaceAtStart(StringBuilder stringBuilder)
{
int i = 0;
while (i < stringBuilder.Length)
{
if (!char.IsWhiteSpace(stringBuilder[i]))
{
break;
}
++i;
}
if (i > 0)
{
stringBuilder.Remove(0, i);
}
}
private static void ReplaceMultipleWhiteSpaceWithSingleWhiteSpace(StringBuilder builder)
{
int index = 0;
int whiteSpaceStart = -1;
while (index < builder.Length)
{
if (char.IsWhiteSpace(builder[index]))
{
if (whiteSpaceStart < 0)
{
whiteSpaceStart = index;
// normalize all white spaces to be ' ' so that the date time parsing works
builder[index] = ' ';
}
}
else if (whiteSpaceStart >= 0)
{
if (index > whiteSpaceStart + 1)
{
// there are at least 2 spaces... replace by 1
builder.Remove(whiteSpaceStart, index - whiteSpaceStart - 1);
index = whiteSpaceStart + 1;
}
whiteSpaceStart = -1;
}
++index;
}
// we have already trimmed the start and end so there cannot be a trail of white spaces in the end
Debug.Assert(builder.Length == 0 || builder[builder.Length - 1] != ' ', "The string builder doesnt end in a white space");
}
private string AsString(DateTimeOffset dateTime)
{
if (dateTime.Offset == Atom10FeedFormatter.zeroOffset)
{
return dateTime.ToUniversalTime().ToString(Rfc822OutputUtcDateTimeFormat, CultureInfo.InvariantCulture);
}
else
{
StringBuilder sb = new StringBuilder(dateTime.ToString(Rfc822OutputLocalDateTimeFormat, CultureInfo.InvariantCulture));
// the zzz in Rfc822OutputLocalDateTimeFormat makes the timezone e.g. "-08:00" but we require e.g. "-0800" without the ':'
sb.Remove(sb.Length - 3, 1);
return sb.ToString();
}
}
private async Task<SyndicationLink> ReadAlternateLinkAsync(XmlReaderWrapper reader, Uri baseUri)
{
SyndicationLink link = new SyndicationLink();
link.BaseUri = baseUri;
link.RelationshipType = Atom10Constants.AlternateTag;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs)
{
link.BaseUri = FeedUtils.CombineXmlBase(link.BaseUri, await reader.GetValueAsync());
}
else if (!FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI))
{
if (this.PreserveAttributeExtensions)
{
link.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync());
}
}
}
}
string localName = reader.LocalName;
string namespaceUri = reader.NamespaceURI;
link.Uri = UriParser(await reader.ReadElementStringAsync(), localName, namespaceUri);//new Uri(uri, UriKind.RelativeOrAbsolute);
return link;
}
private async Task<SyndicationCategory> ReadCategoryAsync(XmlReaderWrapper reader, SyndicationFeed feed)
{
SyndicationCategory result = CreateCategory(feed);
await ReadCategoryAsync(reader, result);
return result;
}
private async Task ReadCategoryAsync(XmlReaderWrapper reader, SyndicationCategory category)
{
bool isEmpty = reader.IsEmptyElement;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (FeedUtils.IsXmlns(name, ns))
{
continue;
}
string val = await reader.GetValueAsync();
if (name == Rss20Constants.DomainTag && ns == Rss20Constants.Rss20Namespace)
{
category.Scheme = val;
}
else if (!TryParseAttribute(name, ns, val, category, this.Version))
{
if (_preserveAttributeExtensions)
{
category.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
}
}
}
}
await reader.ReadStartElementAsync(Rss20Constants.CategoryTag, Rss20Constants.Rss20Namespace);
if (!isEmpty)
{
category.Name = StringParser(await reader.ReadStringAsync(), reader.LocalName, Rss20Constants.Rss20Namespace);
await reader.ReadEndElementAsync();
}
}
private async Task<SyndicationCategory> ReadCategoryAsync(XmlReaderWrapper reader, SyndicationItem item)
{
SyndicationCategory result = CreateCategory(item);
await ReadCategoryAsync(reader, result);
return result;
}
private async Task<SyndicationLink> ReadMediaEnclosureAsync(XmlReaderWrapper reader, Uri baseUri)
{
SyndicationLink link = new SyndicationLink();
link.BaseUri = baseUri;
link.RelationshipType = Rss20Constants.EnclosureTag;
bool isEmptyElement = reader.IsEmptyElement;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (name == "base" && ns == Atom10FeedFormatter.XmlNs)
{
link.BaseUri = FeedUtils.CombineXmlBase(link.BaseUri, await reader.GetValueAsync());
continue;
}
if (FeedUtils.IsXmlns(name, ns))
{
continue;
}
string val = await reader.GetValueAsync();
if (name == Rss20Constants.UrlTag && ns == Rss20Constants.Rss20Namespace)
{
link.Uri = new Uri(val, UriKind.RelativeOrAbsolute);
}
else if (name == Rss20Constants.TypeTag && ns == Rss20Constants.Rss20Namespace)
{
link.MediaType = val;
}
else if (name == Rss20Constants.LengthTag && ns == Rss20Constants.Rss20Namespace)
{
link.Length = !string.IsNullOrEmpty(val) ? Convert.ToInt64(val, CultureInfo.InvariantCulture.NumberFormat) : 0;
}
else if (!FeedUtils.IsXmlns(name, ns))
{
if (_preserveAttributeExtensions)
{
link.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
}
}
}
}
await reader.ReadStartElementAsync(Rss20Constants.EnclosureTag, Rss20Constants.Rss20Namespace);
if (!isEmptyElement)
{
await reader.ReadEndElementAsync();
}
return link;
}
private async Task<SyndicationPerson> ReadPersonAsync(XmlReaderWrapper reader, SyndicationFeed feed)
{
SyndicationPerson result = CreatePerson(feed);
await ReadPersonAsync(reader, result);
return result;
}
private async Task ReadPersonAsync(XmlReaderWrapper reader, SyndicationPerson person)
{
bool isEmpty = reader.IsEmptyElement;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (FeedUtils.IsXmlns(name, ns))
{
continue;
}
string val = await reader.GetValueAsync();
if (!TryParseAttribute(name, ns, val, person, this.Version))
{
if (_preserveAttributeExtensions)
{
person.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
}
}
}
}
await reader.ReadStartElementAsync();
if (!isEmpty)
{
string email = StringParser(await reader.ReadStringAsync(), reader.LocalName, reader.NamespaceURI);
await reader.ReadEndElementAsync();
person.Email = email;
}
}
private async Task<SyndicationPerson> ReadPersonAsync(XmlReaderWrapper reader, SyndicationItem item)
{
SyndicationPerson result = CreatePerson(item);
await ReadPersonAsync(reader, result);
return result;
}
private bool checkTextInput(SyndicationTextInput textInput)
{
//All textInput items are required, we check if all items were instantiated.
return (textInput.Description != null && textInput.title != null && textInput.name != null && textInput.link != null);
}
private async Task readTextInputTag(XmlReaderWrapper reader, SyndicationFeed result)
{
await reader.ReadStartElementAsync();
SyndicationTextInput textInput = new SyndicationTextInput();
string val = String.Empty;
while (await reader.IsStartElementAsync())
{
string name = reader.LocalName;
string namespaceUri = reader.NamespaceURI;
val = StringParser(await reader.ReadElementStringAsync(), name, Rss20Constants.Rss20Namespace);
switch (name)
{
case Rss20Constants.DescriptionTag:
textInput.Description = val;
break;
case Rss20Constants.TitleTag:
textInput.title = val;
break;
case Rss20Constants.LinkTag:
textInput.link = new SyndicationLink(UriParser(val, name, namespaceUri));
break;
case Rss20Constants.NameTag:
textInput.name = val;
break;
default:
//ignore!
break;
}
}
if (checkTextInput(textInput) == true)
{
result.TextInput = textInput;
}
await reader.ReadEndElementAsync();
}
private async Task ReadXmlAsync(XmlReaderWrapper reader, SyndicationFeed result)
{
string baseUri = null;
await reader.MoveToContentAsync();
string version = reader.GetAttribute(Rss20Constants.VersionTag, Rss20Constants.Rss20Namespace);
if (version != Rss20Constants.Version)
{
throw new NotSupportedException(FeedUtils.AddLineInfo(reader, (string.Format(SR.UnsupportedRssVersion, version))));
}
if (reader.AttributeCount > 1)
{
string tmp = reader.GetAttribute("base", Atom10FeedFormatter.XmlNs);
if (!string.IsNullOrEmpty(tmp))
{
baseUri = tmp;
}
}
await reader.ReadStartElementAsync();
await reader.MoveToContentAsync();
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (name == "base" && ns == Atom10FeedFormatter.XmlNs)
{
baseUri = await reader.GetValueAsync();
continue;
}
if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
{
continue;
}
string val = await reader.GetValueAsync();
if (!TryParseAttribute(name, ns, val, result, this.Version))
{
if (_preserveAttributeExtensions)
{
result.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
}
}
}
}
if (!string.IsNullOrEmpty(baseUri))
{
result.BaseUri = new Uri(baseUri, UriKind.RelativeOrAbsolute);
}
bool areAllItemsRead = true;
await reader.ReadStartElementAsync(Rss20Constants.ChannelTag, Rss20Constants.Rss20Namespace);
XmlBuffer buffer = null;
XmlDictionaryWriter extWriter = null;
NullNotAllowedCollection<SyndicationItem> feedItems = new NullNotAllowedCollection<SyndicationItem>();
try
{
while (await reader.IsStartElementAsync())
{
bool notHandled = false;
if (await reader.MoveToContentAsync() == XmlNodeType.Element && reader.NamespaceURI == Rss20Constants.Rss20Namespace)
{
switch (reader.LocalName)
{
case Rss20Constants.TitleTag:
result.Title = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace));
break;
case Rss20Constants.LinkTag:
result.Links.Add(await ReadAlternateLinkAsync(reader, result.BaseUri));
break;
case Rss20Constants.DescriptionTag:
result.Description = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace));
break;
case Rss20Constants.LanguageTag:
result.Language = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.LanguageTag, Rss20Constants.Rss20Namespace);
break;
case Rss20Constants.CopyrightTag:
result.Copyright = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.CopyrightTag, Rss20Constants.Rss20Namespace));
break;
case Rss20Constants.ManagingEditorTag:
result.Authors.Add(await ReadPersonAsync(reader, result));
break;
case Rss20Constants.LastBuildDateTag:
{
bool canReadContent = !reader.IsEmptyElement;
await reader.ReadStartElementAsync();
if (canReadContent)
{
string str = await reader.ReadStringAsync();
if (!string.IsNullOrEmpty(str))
{
result.LastUpdatedTime = DateParser(str, Rss20Constants.LastBuildDateTag, reader.NamespaceURI);
}
await reader.ReadEndElementAsync();
}
break;
}
case Rss20Constants.CategoryTag:
result.Categories.Add(await ReadCategoryAsync(reader, result));
break;
case Rss20Constants.GeneratorTag:
result.Generator = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.GeneratorTag, Rss20Constants.Rss20Namespace);
break;
case Rss20Constants.ImageTag:
{
await OnReadImage(reader, result);
break;
}
case Rss20Constants.ItemTag:
{
NullNotAllowedCollection<SyndicationItem> items = new NullNotAllowedCollection<SyndicationItem>();
while (await reader.IsStartElementAsync(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace))
{
feedItems.Add(await ReadItemAsync(reader, result));
}
areAllItemsRead = true;
break;
}
//Optional tags
case Rss20Constants.DocumentationTag:
result.Documentation = await ReadAlternateLinkAsync(reader, result.BaseUri);
break;
case Rss20Constants.TimeToLiveTag:
string value = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TimeToLiveTag, Rss20Constants.Rss20Namespace);
int timeToLive = int.Parse(value);
result.TimeToLive = timeToLive;
break;
case Rss20Constants.TextInputTag:
await readTextInputTag(reader, result);
break;
case Rss20Constants.SkipHoursTag:
await ReadSkipHoursAsync(reader, result);
break;
case Rss20Constants.SkipDaysTag:
await ReadSkipDaysAsync(reader, result);
break;
default:
notHandled = true;
break;
}
}
else
{
notHandled = true;
}
if (notHandled)
{
bool parsedExtension = _serializeExtensionsAsAtom && await _atomSerializer.TryParseFeedElementFromAsync(reader, result);
if (!parsedExtension)
{
parsedExtension = TryParseElement(reader, result, this.Version);
}
if (!parsedExtension)
{
if (_preserveElementExtensions)
{
if (buffer == null)
{
buffer = new XmlBuffer(_maxExtensionSize);
extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
}
await XmlReaderWrapper.WriteNodeAsync(extWriter, reader, false);
}
else
{
await reader.SkipAsync();
}
}
}
if (!areAllItemsRead)
{
break;
}
}
//asign all read items to feed items.
result.Items = feedItems;
LoadElementExtensions(buffer, extWriter, result);
}
catch (FormatException e)
{
throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e);
}
catch (ArgumentException e)
{
throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e);
}
finally
{
if (extWriter != null)
{
((IDisposable)extWriter).Dispose();
}
}
if (areAllItemsRead)
{
await reader.ReadEndElementAsync(); // channel
await reader.ReadEndElementAsync(); // rss
}
}
private async Task WriteAlternateLinkAsync(XmlWriter writer, SyndicationLink link, Uri baseUri)
{
await writer.WriteStartElementAsync(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace);
Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri);
if (baseUriToWrite != null)
{
await writer.WriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite));
}
await link.WriteAttributeExtensionsAsync(writer, SyndicationVersions.Rss20);
await writer.WriteStringAsync(FeedUtils.GetUriString(link.Uri));
await writer.WriteEndElementAsync();
}
private async Task WriteCategoryAsync(XmlWriter writer, SyndicationCategory category)
{
if (category == null)
{
return;
}
await writer.WriteStartElementAsync(Rss20Constants.CategoryTag, Rss20Constants.Rss20Namespace);
await WriteAttributeExtensionsAsync(writer, category, this.Version);
if (!string.IsNullOrEmpty(category.Scheme) && !category.AttributeExtensions.ContainsKey(s_rss20Domain))
{
await writer.WriteAttributeStringAsync(Rss20Constants.DomainTag, Rss20Constants.Rss20Namespace, category.Scheme);
}
await writer.WriteStringAsync(category.Name);
await writer.WriteEndElementAsync();
}
private async Task WriteFeedAsync(XmlWriter writer)
{
if (this.Feed == null)
{
throw new InvalidOperationException(SR.FeedFormatterDoesNotHaveFeed);
}
if (_serializeExtensionsAsAtom)
{
await writer.InternalWriteAttributeStringAsync("xmlns", Atom10Constants.Atom10Prefix, null, Atom10Constants.Atom10Namespace);
}
await writer.WriteAttributeStringAsync(Rss20Constants.VersionTag, Rss20Constants.Version);
await writer.WriteStartElementAsync(Rss20Constants.ChannelTag, Rss20Constants.Rss20Namespace);
if (this.Feed.BaseUri != null)
{
await writer.InternalWriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(this.Feed.BaseUri));
}
await WriteAttributeExtensionsAsync(writer, this.Feed, this.Version);
string title = this.Feed.Title != null ? this.Feed.Title.Text : string.Empty;
await writer.WriteElementStringAsync(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace, title);
SyndicationLink alternateLink = null;
for (int i = 0; i < this.Feed.Links.Count; ++i)
{
if (this.Feed.Links[i].RelationshipType == Atom10Constants.AlternateTag)
{
alternateLink = this.Feed.Links[i];
await WriteAlternateLinkAsync(writer, alternateLink, this.Feed.BaseUri);
break;
}
}
string description = this.Feed.Description != null ? this.Feed.Description.Text : string.Empty;
await writer.WriteElementStringAsync(Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace, description);
if (this.Feed.Language != null)
{
await writer.WriteElementStringAsync(Rss20Constants.LanguageTag, this.Feed.Language);
}
if (this.Feed.Copyright != null)
{
await writer.WriteElementStringAsync(Rss20Constants.CopyrightTag, Rss20Constants.Rss20Namespace, this.Feed.Copyright.Text);
}
// if there's a single author with an email address, then serialize as the managingEditor
// else serialize the authors as Atom extensions
if ((this.Feed.Authors.Count == 1) && (this.Feed.Authors[0].Email != null))
{
await WritePersonAsync(writer, Rss20Constants.ManagingEditorTag, this.Feed.Authors[0]);
}
else
{
if (_serializeExtensionsAsAtom)
{
await _atomSerializer.WriteFeedAuthorsToAsync(writer, this.Feed.Authors);
}
}
if (this.Feed.LastUpdatedTime > DateTimeOffset.MinValue)
{
await writer.WriteStartElementAsync(Rss20Constants.LastBuildDateTag);
await writer.WriteStringAsync(AsString(this.Feed.LastUpdatedTime));
await writer.WriteEndElementAsync();
}
for (int i = 0; i < this.Feed.Categories.Count; ++i)
{
await WriteCategoryAsync(writer, this.Feed.Categories[i]);
}
if (!string.IsNullOrEmpty(this.Feed.Generator))
{
await writer.WriteElementStringAsync(Rss20Constants.GeneratorTag, this.Feed.Generator);
}
if (this.Feed.Contributors.Count > 0)
{
if (_serializeExtensionsAsAtom)
{
await _atomSerializer.WriteFeedContributorsToAsync(writer, this.Feed.Contributors);
}
}
if (this.Feed.ImageUrl != null)
{
await writer.WriteStartElementAsync(Rss20Constants.ImageTag);
await writer.WriteElementStringAsync(Rss20Constants.UrlTag, FeedUtils.GetUriString(this.Feed.ImageUrl));
string imageTitle = Feed.ImageTitle == null ? title : Feed.ImageTitle.Text;
await writer.WriteElementStringAsync(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace, imageTitle);
string imgAlternateLink = alternateLink != null ? FeedUtils.GetUriString(alternateLink.Uri) : string.Empty;
string imageLink = Feed.ImageLink == null ? imgAlternateLink : FeedUtils.GetUriString(Feed.ImageLink);
await writer.WriteElementStringAsync(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace, imageLink);
await writer.WriteEndElementAsync(); // image
}
//Optional spec items
//time to live
if (this.Feed.TimeToLive != 0)
{
await writer.WriteElementStringAsync(Rss20Constants.TimeToLiveTag, this.Feed.TimeToLive.ToString());
}
//skiphours
if (this.Feed.SkipHours.Count > 0)
{
await writer.WriteStartElementAsync(Rss20Constants.SkipHoursTag);
foreach (int hour in this.Feed.SkipHours)
{
writer.WriteElementString(Rss20Constants.HourTag, hour.ToString());
}
await writer.WriteEndElementAsync();
}
//skipDays
if (this.Feed.SkipDays.Count > 0)
{
await writer.WriteStartElementAsync(Rss20Constants.SkipDaysTag);
foreach (string day in this.Feed.SkipDays)
{
await writer.WriteElementStringAsync(Rss20Constants.DayTag, day);
}
await writer.WriteEndElementAsync();
}
//textinput
if (this.Feed.TextInput != null)
{
await writer.WriteStartElementAsync(Rss20Constants.TextInputTag);
await writer.WriteElementStringAsync(Rss20Constants.DescriptionTag, this.Feed.TextInput.Description);
await writer.WriteElementStringAsync(Rss20Constants.TitleTag, this.Feed.TextInput.title);
await writer.WriteElementStringAsync(Rss20Constants.LinkTag, this.Feed.TextInput.link.GetAbsoluteUri().ToString());
await writer.WriteElementStringAsync(Rss20Constants.NameTag, this.Feed.TextInput.name);
await writer.WriteEndElementAsync();
}
if (_serializeExtensionsAsAtom)
{
await _atomSerializer.WriteElementAsync(writer, Atom10Constants.IdTag, this.Feed.Id);
// dont write out the 1st alternate link since that would have been written out anyway
bool isFirstAlternateLink = true;
for (int i = 0; i < this.Feed.Links.Count; ++i)
{
if (this.Feed.Links[i].RelationshipType == Atom10Constants.AlternateTag && isFirstAlternateLink)
{
isFirstAlternateLink = false;
continue;
}
await _atomSerializer.WriteLinkAsync(writer, this.Feed.Links[i], this.Feed.BaseUri);
}
}
await WriteElementExtensionsAsync(writer, this.Feed, this.Version);
await WriteItemsAsync(writer, this.Feed.Items, this.Feed.BaseUri);
await writer.WriteEndElementAsync(); // channel
}
private async Task WriteItemContentsAsync(XmlWriter writer, SyndicationItem item, Uri feedBaseUri)
{
Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(feedBaseUri, item.BaseUri);
if (baseUriToWrite != null)
{
await writer.InternalWriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite));
}
await WriteAttributeExtensionsAsync(writer, item, this.Version);
string guid = item.Id ?? string.Empty;
bool isPermalink = false;
SyndicationLink firstAlternateLink = null;
for (int i = 0; i < item.Links.Count; ++i)
{
if (item.Links[i].RelationshipType == Atom10Constants.AlternateTag)
{
if (firstAlternateLink == null)
{
firstAlternateLink = item.Links[i];
}
if (guid == FeedUtils.GetUriString(item.Links[i].Uri))
{
isPermalink = true;
break;
}
}
}
if (!string.IsNullOrEmpty(guid))
{
await writer.WriteStartElementAsync(Rss20Constants.GuidTag);
if (isPermalink)
{
await writer.WriteAttributeStringAsync(Rss20Constants.IsPermaLinkTag, "true");
}
else
{
await writer.WriteAttributeStringAsync(Rss20Constants.IsPermaLinkTag, "false");
}
await writer.WriteStringAsync(guid);
await writer.WriteEndElementAsync();
}
if (firstAlternateLink != null)
{
await WriteAlternateLinkAsync(writer, firstAlternateLink, (item.BaseUri != null ? item.BaseUri : feedBaseUri));
}
if (item.Authors.Count == 1 && !string.IsNullOrEmpty(item.Authors[0].Email))
{
await WritePersonAsync(writer, Rss20Constants.AuthorTag, item.Authors[0]);
}
else
{
if (_serializeExtensionsAsAtom)
{
await _atomSerializer.WriteItemAuthorsToAsync(writer, item.Authors);
}
}
for (int i = 0; i < item.Categories.Count; ++i)
{
await WriteCategoryAsync(writer, item.Categories[i]);
}
bool serializedTitle = false;
if (item.Title != null)
{
await writer.WriteElementStringAsync(Rss20Constants.TitleTag, item.Title.Text);
serializedTitle = true;
}
bool serializedContentAsDescription = false;
TextSyndicationContent summary = item.Summary;
if (summary == null)
{
summary = (item.Content as TextSyndicationContent);
serializedContentAsDescription = (summary != null);
}
// the spec requires the wire to have a title or a description
if (!serializedTitle && summary == null)
{
summary = new TextSyndicationContent(string.Empty);
}
if (summary != null)
{
await writer.WriteElementStringAsync(Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace, summary.Text);
}
if (item.SourceFeed != null)
{
await writer.WriteStartElementAsync(Rss20Constants.SourceTag, Rss20Constants.Rss20Namespace);
await WriteAttributeExtensionsAsync(writer, item.SourceFeed, this.Version);
SyndicationLink selfLink = null;
for (int i = 0; i < item.SourceFeed.Links.Count; ++i)
{
if (item.SourceFeed.Links[i].RelationshipType == Atom10Constants.SelfTag)
{
selfLink = item.SourceFeed.Links[i];
break;
}
}
if (selfLink != null && !item.SourceFeed.AttributeExtensions.ContainsKey(s_rss20Url))
{
await writer.WriteAttributeStringAsync(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace, FeedUtils.GetUriString(selfLink.Uri));
}
string title = (item.SourceFeed.Title != null) ? item.SourceFeed.Title.Text : string.Empty;
await writer.WriteStringAsync(title);
await writer.WriteEndElementAsync();
}
if (item.PublishDate > DateTimeOffset.MinValue)
{
await writer.WriteElementStringAsync(Rss20Constants.PubDateTag, Rss20Constants.Rss20Namespace, AsString(item.PublishDate));
}
// serialize the enclosures
SyndicationLink firstEnclosureLink = null;
bool passedFirstAlternateLink = false;
for (int i = 0; i < item.Links.Count; ++i)
{
if (item.Links[i].RelationshipType == Rss20Constants.EnclosureTag)
{
if (firstEnclosureLink == null)
{
firstEnclosureLink = item.Links[i];
await WriteMediaEnclosureAsync(writer, item.Links[i], item.BaseUri);
continue;
}
}
else if (item.Links[i].RelationshipType == Atom10Constants.AlternateTag)
{
if (!passedFirstAlternateLink)
{
passedFirstAlternateLink = true;
continue;
}
}
if (_serializeExtensionsAsAtom)
{
await _atomSerializer.WriteLinkAsync(writer, item.Links[i], item.BaseUri);
}
}
if (item.LastUpdatedTime > DateTimeOffset.MinValue)
{
if (_serializeExtensionsAsAtom)
{
await _atomSerializer.WriteItemLastUpdatedTimeToAsync(writer, item.LastUpdatedTime);
}
}
if (_serializeExtensionsAsAtom)
{
await _atomSerializer.WriteContentToAsync(writer, Atom10Constants.RightsTag, item.Copyright);
}
if (!serializedContentAsDescription)
{
if (_serializeExtensionsAsAtom)
{
await _atomSerializer.WriteContentToAsync(writer, Atom10Constants.ContentTag, item.Content);
}
}
if (item.Contributors.Count > 0)
{
if (_serializeExtensionsAsAtom)
{
await _atomSerializer.WriteItemContributorsToAsync(writer, item.Contributors);
}
}
await WriteElementExtensionsAsync(writer, item, this.Version);
}
private async Task WriteMediaEnclosureAsync(XmlWriter writer, SyndicationLink link, Uri baseUri)
{
await writer.WriteStartElementAsync(Rss20Constants.EnclosureTag, Rss20Constants.Rss20Namespace);
Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri);
if (baseUriToWrite != null)
{
await writer.InternalWriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite));
}
await link.WriteAttributeExtensionsAsync(writer, SyndicationVersions.Rss20);
if (!link.AttributeExtensions.ContainsKey(s_rss20Url))
{
await writer.WriteAttributeStringAsync(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace, FeedUtils.GetUriString(link.Uri));
}
if (link.MediaType != null && !link.AttributeExtensions.ContainsKey(s_rss20Type))
{
await writer.WriteAttributeStringAsync(Rss20Constants.TypeTag, Rss20Constants.Rss20Namespace, link.MediaType);
}
if (link.Length != 0 && !link.AttributeExtensions.ContainsKey(s_rss20Length))
{
await writer.WriteAttributeStringAsync(Rss20Constants.LengthTag, Rss20Constants.Rss20Namespace, Convert.ToString(link.Length, CultureInfo.InvariantCulture));
}
await writer.WriteEndElementAsync();
}
private async Task WritePersonAsync(XmlWriter writer, string elementTag, SyndicationPerson person)
{
await writer.WriteStartElementAsync(elementTag, Rss20Constants.Rss20Namespace);
await WriteAttributeExtensionsAsync(writer, person, this.Version);
await writer.WriteStringAsync(person.Email);
await writer.WriteEndElementAsync();
}
private static bool OriginalDateParser(string dateTimeString, out DateTimeOffset dto)
{
StringBuilder dateTimeStringBuilder = new StringBuilder(dateTimeString.Trim());
if (dateTimeStringBuilder.Length < 18)
{
return false;
}
int timeZoneStartIndex;
for (timeZoneStartIndex = dateTimeStringBuilder.Length - 1; dateTimeStringBuilder[timeZoneStartIndex] != ' '; timeZoneStartIndex--) ;
timeZoneStartIndex++;
string timeZoneSuffix = dateTimeStringBuilder.ToString().Substring(timeZoneStartIndex);
dateTimeStringBuilder.Remove(timeZoneStartIndex, dateTimeStringBuilder.Length - timeZoneStartIndex);
bool isUtc;
dateTimeStringBuilder.Append(NormalizeTimeZone(timeZoneSuffix, out isUtc));
string wellFormattedString = dateTimeStringBuilder.ToString();
DateTimeOffset theTime;
string[] parseFormat =
{
"ddd, dd MMMM yyyy HH:mm:ss zzz",
"dd MMMM yyyy HH:mm:ss zzz",
"ddd, dd MMM yyyy HH:mm:ss zzz",
"dd MMM yyyy HH:mm:ss zzz",
"ddd, dd MMMM yyyy HH:mm zzz",
"dd MMMM yyyy HH:mm zzz",
"ddd, dd MMM yyyy HH:mm zzz",
"dd MMM yyyy HH:mm zzz"
};
if (DateTimeOffset.TryParseExact(wellFormattedString, parseFormat,
CultureInfo.InvariantCulture.DateTimeFormat,
(isUtc ? DateTimeStyles.AdjustToUniversal : DateTimeStyles.None), out theTime))
{
dto = theTime;
return true;
}
return false;
}
// Custom parsers
public static DateTimeOffset DefaultDateParser(string dateTimeString, string localName, string ns)
{
bool parsed = false;
DateTimeOffset dto;
parsed = DateTimeOffset.TryParse(dateTimeString, out dto);
if (parsed)
return dto;
//original parser here
parsed = OriginalDateParser(dateTimeString, out dto);
if (parsed)
return dto;
//Impossible to parse - using a default date;
return new DateTimeOffset();
}
}
[XmlRoot(ElementName = Rss20Constants.RssTag, Namespace = Rss20Constants.Rss20Namespace)]
public class Rss20FeedFormatter<TSyndicationFeed> : Rss20FeedFormatter
where TSyndicationFeed : SyndicationFeed, new()
{
// constructors
public Rss20FeedFormatter()
: base(typeof(TSyndicationFeed))
{
}
public Rss20FeedFormatter(TSyndicationFeed feedToWrite)
: base(feedToWrite)
{
}
public Rss20FeedFormatter(TSyndicationFeed feedToWrite, bool serializeExtensionsAsAtom)
: base(feedToWrite, serializeExtensionsAsAtom)
{
}
protected override SyndicationFeed CreateFeedInstance()
{
return new TSyndicationFeed();
}
}
internal class ItemParseOptions
{
public bool readItemsAtLeastOnce;
public bool areAllItemsRead;
public ItemParseOptions(bool readItemsAtLeastOnce, bool areAllItemsRead)
{
this.readItemsAtLeastOnce = readItemsAtLeastOnce;
this.areAllItemsRead = areAllItemsRead;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("Modifiers/Morph Ref")]
public class MegaMorphRef : MegaMorphBase
{
public MegaMorph source;
public bool UseLimit;
public float Max;
public float Min;
public int[] mapping;
public float importScale = 1.0f;
public bool flipyz = false;
public bool negx = false;
[HideInInspector]
public float tolerance = 0.0001f;
public bool showmapping = false;
public float mappingSize = 0.001f;
public int mapStart = 0;
public int mapEnd = 0;
Vector3[] dif;
static Vector3[] endpoint = new Vector3[4];
static Vector3[] splinepoint = new Vector3[4];
static Vector3[] temppoint = new Vector3[2];
Vector3[] p1;
Vector3[] p2;
Vector3[] p3;
Vector3[] p4;
public List<float> pers = new List<float>(4);
public override string ModName() { return "Morph Ref"; }
public override string GetHelpURL() { return "?page_id=257"; }
[HideInInspector]
public int compressedmem = 0;
[HideInInspector]
public int compressedmem1 = 0;
[HideInInspector]
public int memuse = 0;
public void SetSource(MegaMorph src)
{
source = src;
if ( source )
{
if ( chanBank == null )
chanBank = new List<MegaMorphChan>();
chanBank.Clear();
for ( int i = 0; i < source.chanBank.Count; i++ )
{
MegaMorphChan ch = new MegaMorphChan();
ch.control = source.chanBank[i].control;
ch.Percent = source.chanBank[i].Percent;
ch.mName = source.chanBank[i].mName;
chanBank.Add(ch);
}
}
}
public override bool ModLateUpdate(MegaModContext mc)
{
if ( source )
{
if ( animate )
{
if ( Application.isPlaying )
animtime += Time.deltaTime * speed;
switch ( repeatMode )
{
case MegaRepeatMode.Loop: animtime = Mathf.Repeat(animtime, looptime); break;
case MegaRepeatMode.Clamp: animtime = Mathf.Clamp(animtime, 0.0f, looptime); break;
}
SetAnim(animtime);
}
if ( dif == null )
{
dif = new Vector3[mc.mod.verts.Length];
}
}
return Prepare(mc);
}
public bool animate = false;
public float atime = 0.0f;
public float animtime = 0.0f;
public float looptime = 0.0f;
public MegaRepeatMode repeatMode = MegaRepeatMode.Loop;
public float speed = 1.0f;
public override bool Prepare(MegaModContext mc)
{
if ( source )
return source.Prepare(mc);
return false;
}
// Only need to call if a Percent value has changed on a Channel or a target, so flag for a change
void SetVerts(int j, Vector3[] p)
{
switch ( j )
{
case 0: p1 = p; break;
case 1: p2 = p; break;
case 2: p3 = p; break;
case 3: p4 = p; break;
}
}
void SetVerts(MegaMorphChan chan, int j, Vector3[] p)
{
switch ( j )
{
case 0: chan.p1 = p; break;
case 1: chan.p2 = p; break;
case 2: chan.p3 = p; break;
case 3: chan.p4 = p; break;
}
}
static int framenum;
// oPoints whould be verts
public override void Modify(MegaModifiers mc)
{
if ( source == null )
return;
if ( source.nonMorphedVerts != null && source.nonMorphedVerts.Length > 1 )
{
ModifyCompressed(mc);
return;
}
framenum++;
mc.ChangeSourceVerts();
float fChannelPercent;
Vector3 delt;
// cycle through channels, searching for ones to use
bool firstchan = true;
bool morphed = false;
float min = 0.0f;
float max = 100.0f;
if ( UseLimit )
{
min = Min;
max = Max;
}
for ( int i = 0; i < source.chanBank.Count; i++ )
{
MegaMorphChan chan = source.chanBank[i];
// This needs to be local chan list
chan.UpdatePercent();
if ( UseLimit )
{
fChannelPercent = Mathf.Clamp(chan.Percent, min, max); //chan.mSpinmin, chan.mSpinmax);
}
else
{
if ( chan.mUseLimit )
fChannelPercent = Mathf.Clamp(chan.Percent, chan.mSpinmin, chan.mSpinmax);
else
fChannelPercent = Mathf.Clamp(chan.Percent, 0.0f, 100.0f);
}
if ( fChannelPercent != 0.0f || (fChannelPercent == 0.0f && chan.fChannelPercent != 0.0f) )
{
chan.fChannelPercent = fChannelPercent;
if ( chan.mTargetCache != null && chan.mTargetCache.Count > 0 && chan.mActiveOverride ) //&& fChannelPercent != 0.0f )
{
morphed = true;
if ( chan.mUseLimit ) //|| glUseLimit )
{
}
if ( firstchan )
{
firstchan = false;
for ( int pointnum = 0; pointnum < source.oPoints.Length; pointnum++ )
{
dif[pointnum] = source.oPoints[pointnum];
}
}
if ( chan.mTargetCache.Count == 1 )
{
for ( int pointnum = 0; pointnum < source.oPoints.Length; pointnum++ )
{
delt = chan.mDeltas[pointnum];
dif[pointnum].x += delt.x * fChannelPercent;
dif[pointnum].y += delt.y * fChannelPercent;
dif[pointnum].z += delt.z * fChannelPercent;
}
}
else
{
int totaltargs = chan.mTargetCache.Count; // + 1; // + 1;
float fProgression = fChannelPercent; //Mathf.Clamp(fChannelPercent, 0.0f, 100.0f);
int segment = 1;
while ( segment <= totaltargs && fProgression >= chan.GetTargetPercent(segment - 2) )
segment++;
if ( segment > totaltargs )
segment = totaltargs;
p4 = source.oPoints;
if ( segment == 1 )
{
p1 = source.oPoints;
p2 = chan.mTargetCache[0].points; // mpoints
p3 = chan.mTargetCache[1].points;
}
else
{
if ( segment == totaltargs )
{
int targnum = totaltargs - 1;
for ( int j = 2; j >= 0; j-- )
{
targnum--;
if ( targnum == -2 )
SetVerts(j, source.oPoints);
else
SetVerts(j, chan.mTargetCache[targnum + 1].points);
}
}
else
{
int targnum = segment;
for ( int j = 3; j >= 0; j-- )
{
targnum--;
if ( targnum == -2 )
SetVerts(j, source.oPoints);
else
SetVerts(j, chan.mTargetCache[targnum + 1].points);
}
}
}
float targetpercent1 = chan.GetTargetPercent(segment - 3);
float targetpercent2 = chan.GetTargetPercent(segment - 2);
float top = fProgression - targetpercent1;
float bottom = targetpercent2 - targetpercent1;
float u = top / bottom;
{
for ( int pointnum = 0; pointnum < source.oPoints.Length; pointnum++ )
{
Vector3 vert = source.oPoints[pointnum];
float length;
Vector3 progession;
endpoint[0] = p1[pointnum];
endpoint[1] = p2[pointnum];
endpoint[2] = p3[pointnum];
endpoint[3] = p4[pointnum];
if ( segment == 1 )
{
splinepoint[0] = endpoint[0];
splinepoint[3] = endpoint[1];
temppoint[1] = endpoint[2] - endpoint[0];
temppoint[0] = endpoint[1] - endpoint[0];
length = temppoint[1].sqrMagnitude;
if ( length == 0.0f )
{
splinepoint[1] = endpoint[0];
splinepoint[2] = endpoint[1];
}
else
{
splinepoint[2] = endpoint[1] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1];
splinepoint[1] = endpoint[0] + chan.mCurvature * (splinepoint[2] - endpoint[0]);
}
}
else
{
if ( segment == totaltargs )
{
splinepoint[0] = endpoint[1];
splinepoint[3] = endpoint[2];
temppoint[1] = endpoint[2] - endpoint[0];
temppoint[0] = endpoint[1] - endpoint[2];
length = temppoint[1].sqrMagnitude;
if ( length == 0.0f )
{
splinepoint[1] = endpoint[0];
splinepoint[2] = endpoint[1];
}
else
{
splinepoint[1] = endpoint[1] - (Vector3.Dot(temppoint[1], temppoint[0]) * chan.mCurvature / length) * temppoint[1];
splinepoint[2] = endpoint[2] + chan.mCurvature * (splinepoint[1] - endpoint[2]);
}
}
else
{
temppoint[1] = endpoint[2] - endpoint[0];
temppoint[0] = endpoint[1] - endpoint[0];
length = temppoint[1].sqrMagnitude;
splinepoint[0] = endpoint[1];
splinepoint[3] = endpoint[2];
if ( length == 0.0f )
splinepoint[1] = endpoint[0];
else
splinepoint[1] = endpoint[1] + (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1];
temppoint[1] = endpoint[3] - endpoint[1];
temppoint[0] = endpoint[2] - endpoint[1];
length = temppoint[1].sqrMagnitude;
if ( length == 0.0f )
splinepoint[2] = endpoint[1];
else
splinepoint[2] = endpoint[2] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1];
}
}
MegaUtils.Bez3D(out progession, ref splinepoint, u);
dif[pointnum].x += progession.x - vert.x; //delt;
dif[pointnum].y += progession.y - vert.y; //delt;
dif[pointnum].z += progession.z - vert.z; //delt;
}
}
}
}
}
}
if ( morphed )
{
for ( int i = 0; i < source.mapping.Length; i++ )
sverts[i] = dif[source.mapping[i]];
}
else
{
for ( int i = 0; i < verts.Length; i++ )
sverts[i] = verts[i];
}
}
bool Changed(int v, int c)
{
for ( int t = 0; t < source.chanBank[c].mTargetCache.Count; t++ )
{
if ( !source.oPoints[v].Equals(source.chanBank[c].mTargetCache[t].points[v]) )
return true;
}
return false;
}
public void ModifyCompressed(MegaModifiers mc)
{
framenum++;
mc.ChangeSourceVerts();
float fChannelPercent;
Vector3 delt;
// cycle through channels, searching for ones to use
bool firstchan = true;
bool morphed = false;
for ( int i = 0; i < source.chanBank.Count; i++ )
{
MegaMorphChan chan = source.chanBank[i];
MegaMorphChan lchan = chanBank[i]; // copy of source banks with out the vert data
chan.UpdatePercent();
if ( chan.mUseLimit )
fChannelPercent = Mathf.Clamp(lchan.Percent, chan.mSpinmin, chan.mSpinmax);
else
fChannelPercent = Mathf.Clamp(lchan.Percent, 0.0f, 100.0f);
if ( fChannelPercent != 0.0f || (fChannelPercent == 0.0f && chan.fChannelPercent != 0.0f) )
{
chan.fChannelPercent = fChannelPercent;
if ( chan.mTargetCache != null && chan.mTargetCache.Count > 0 && chan.mActiveOverride ) //&& fChannelPercent != 0.0f )
{
morphed = true;
if ( chan.mUseLimit ) //|| glUseLimit )
{
}
// New bit
if ( firstchan )
{
firstchan = false;
// Save a int array of morphedpoints and use that, then only dealing with changed info
for ( int pointnum = 0; pointnum < source.morphedVerts.Length; pointnum++ )
{
// this will change when we remove points
int p = source.morphedVerts[pointnum];
dif[p] = source.oPoints[p]; //morphedVerts[pointnum]];
}
}
// end new
if ( chan.mTargetCache.Count == 1 )
{
// Save a int array of morphedpoints and use that, then only dealing with changed info
for ( int pointnum = 0; pointnum < source.morphedVerts.Length; pointnum++ )
{
int p = source.morphedVerts[pointnum];
delt = chan.mDeltas[p]; //morphedVerts[pointnum]];
//delt = chan.mDeltas[pointnum]; //morphedVerts[pointnum]];
dif[p].x += delt.x * fChannelPercent;
dif[p].y += delt.y * fChannelPercent;
dif[p].z += delt.z * fChannelPercent;
}
}
else
{
int totaltargs = chan.mTargetCache.Count; // + 1; // + 1;
float fProgression = fChannelPercent; //Mathf.Clamp(fChannelPercent, 0.0f, 100.0f);
int segment = 1;
while ( segment <= totaltargs && fProgression >= chan.GetTargetPercent(segment - 2) )
segment++;
if ( segment > totaltargs )
segment = totaltargs;
p4 = source.oPoints;
if ( segment == 1 )
{
p1 = source.oPoints;
p2 = chan.mTargetCache[0].points; // mpoints
p3 = chan.mTargetCache[1].points;
}
else
{
if ( segment == totaltargs )
{
int targnum = totaltargs - 1;
for ( int j = 2; j >= 0; j-- )
{
targnum--;
if ( targnum == -2 )
SetVerts(j, source.oPoints);
else
SetVerts(j, chan.mTargetCache[targnum + 1].points);
}
}
else
{
int targnum = segment;
for ( int j = 3; j >= 0; j-- )
{
targnum--;
if ( targnum == -2 )
SetVerts(j, source.oPoints);
else
SetVerts(j, chan.mTargetCache[targnum + 1].points);
}
}
}
float targetpercent1 = chan.GetTargetPercent(segment - 3);
float targetpercent2 = chan.GetTargetPercent(segment - 2);
float top = fProgression - targetpercent1;
float bottom = targetpercent2 - targetpercent1;
float u = top / bottom;
for ( int pointnum = 0; pointnum < source.morphedVerts.Length; pointnum++ )
{
int p = source.morphedVerts[pointnum];
Vector3 vert = source.oPoints[p]; //pointnum];
float length;
Vector3 progession;
endpoint[0] = p1[p];
endpoint[1] = p2[p];
endpoint[2] = p3[p];
endpoint[3] = p4[p];
if ( segment == 1 )
{
splinepoint[0] = endpoint[0];
splinepoint[3] = endpoint[1];
temppoint[1] = endpoint[2] - endpoint[0];
temppoint[0] = endpoint[1] - endpoint[0];
length = temppoint[1].sqrMagnitude;
if ( length == 0.0f )
{
splinepoint[1] = endpoint[0];
splinepoint[2] = endpoint[1];
}
else
{
splinepoint[2] = endpoint[1] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1];
splinepoint[1] = endpoint[0] + chan.mCurvature * (splinepoint[2] - endpoint[0]);
}
}
else
{
if ( segment == totaltargs )
{
splinepoint[0] = endpoint[1];
splinepoint[3] = endpoint[2];
temppoint[1] = endpoint[2] - endpoint[0];
temppoint[0] = endpoint[1] - endpoint[2];
length = temppoint[1].sqrMagnitude;
if ( length == 0.0f )
{
splinepoint[1] = endpoint[0];
splinepoint[2] = endpoint[1];
}
else
{
splinepoint[1] = endpoint[1] - (Vector3.Dot(temppoint[1], temppoint[0]) * chan.mCurvature / length) * temppoint[1];
splinepoint[2] = endpoint[2] + chan.mCurvature * (splinepoint[1] - endpoint[2]);
}
}
else
{
temppoint[1] = endpoint[2] - endpoint[0];
temppoint[0] = endpoint[1] - endpoint[0];
length = temppoint[1].sqrMagnitude;
splinepoint[0] = endpoint[1];
splinepoint[3] = endpoint[2];
if ( length == 0.0f )
splinepoint[1] = endpoint[0];
else
splinepoint[1] = endpoint[1] + (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1];
temppoint[1] = endpoint[3] - endpoint[1];
temppoint[0] = endpoint[2] - endpoint[1];
length = temppoint[1].sqrMagnitude;
if ( length == 0.0f )
splinepoint[2] = endpoint[1];
else
splinepoint[2] = endpoint[2] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1];
}
}
MegaUtils.Bez3D(out progession, ref splinepoint, u);
dif[p].x += progession.x - vert.x;
dif[p].y += progession.y - vert.y;
dif[p].z += progession.z - vert.z;
}
}
}
}
}
if ( morphed )
{
for ( int i = 0; i < source.morphMappingFrom.Length; i++ )
sverts[source.morphMappingTo[i]] = dif[source.morphMappingFrom[i]];
for ( int i = 0; i < source.nonMorphMappingFrom.Length; i++ )
sverts[source.nonMorphMappingTo[i]] = source.oPoints[source.nonMorphMappingFrom[i]];
}
else
{
for ( int i = 0; i < verts.Length; i++ )
sverts[i] = verts[i];
}
}
// Threaded version
Vector3[] _verts;
Vector3[] _sverts;
public override void PrepareMT(MegaModifiers mc, int cores)
{
PrepareForMT(mc, cores);
}
public override void DoWork(MegaModifiers mc, int index, int start, int end, int cores)
{
ModifyCompressedMT(mc, index, cores);
}
public void PrepareForMT(MegaModifiers mc, int cores)
{
if ( setStart == null )
BuildMorphVertInfo(cores);
// cycle through channels, searching for ones to use
mtmorphed = false;
for ( int i = 0; i < source.chanBank.Count; i++ )
{
MegaMorphChan chan = source.chanBank[i];
chan.UpdatePercent();
//float fChannelPercent = Mathf.Clamp(chan.Percent, 0.0f, 100.0f);
float fChannelPercent;
if ( chan.mUseLimit )
fChannelPercent = Mathf.Clamp(chan.Percent, chan.mSpinmin, chan.mSpinmax);
else
fChannelPercent = Mathf.Clamp(chan.Percent, 0.0f, 100.0f);
if ( fChannelPercent != 0.0f || (fChannelPercent == 0.0f && chan.fChannelPercent != 0.0f) )
{
chan.fChannelPercent = fChannelPercent;
if ( chan.mTargetCache != null && chan.mTargetCache.Count > 0 && chan.mActiveOverride )
{
mtmorphed = true;
if ( chan.mTargetCache.Count > 1 )
{
int totaltargs = chan.mTargetCache.Count; // + 1; // + 1;
chan.fProgression = chan.fChannelPercent; //Mathf.Clamp(fChannelPercent, 0.0f, 100.0f);
chan.segment = 1;
while ( chan.segment <= totaltargs && chan.fProgression >= chan.GetTargetPercent(chan.segment - 2) )
chan.segment++;
if ( chan.segment > totaltargs )
chan.segment = totaltargs;
chan.p4 = source.oPoints;
if ( chan.segment == 1 )
{
chan.p1 = source.oPoints;
chan.p2 = chan.mTargetCache[0].points; // mpoints
chan.p3 = chan.mTargetCache[1].points;
}
else
{
if ( chan.segment == totaltargs )
{
int targnum = totaltargs - 1;
for ( int j = 2; j >= 0; j-- )
{
targnum--;
if ( targnum == -2 )
SetVerts(chan, j, source.oPoints);
else
SetVerts(chan, j, chan.mTargetCache[targnum + 1].points);
}
}
else
{
int targnum = chan.segment;
for ( int j = 3; j >= 0; j-- )
{
targnum--;
if ( targnum == -2 )
SetVerts(chan, j, source.oPoints);
else
SetVerts(chan, j, chan.mTargetCache[targnum + 1].points);
}
}
}
}
}
}
}
if ( !mtmorphed )
{
for ( int i = 0; i < verts.Length; i++ )
sverts[i] = verts[i];
}
}
bool mtmorphed;
public void ModifyCompressedMT(MegaModifiers mc, int tindex, int cores)
{
if ( !mtmorphed )
return;
int step = source.morphedVerts.Length / cores;
int startvert = (tindex * step);
int endvert = startvert + step;
if ( tindex == cores - 1 )
endvert = source.morphedVerts.Length;
framenum++;
Vector3 delt;
// cycle through channels, searching for ones to use
bool firstchan = true;
Vector3[] endpoint = new Vector3[4]; // These in channel class
Vector3[] splinepoint = new Vector3[4];
Vector3[] temppoint = new Vector3[2];
for ( int i = 0; i < chanBank.Count; i++ )
{
MegaMorphChan chan = chanBank[i];
if ( chan.fChannelPercent != 0.0f )
{
if ( chan.mTargetCache != null && chan.mTargetCache.Count > 0 && chan.mActiveOverride ) //&& fChannelPercent != 0.0f )
{
if ( firstchan )
{
firstchan = false;
for ( int pointnum = startvert; pointnum < endvert; pointnum++ )
{
int p = source.morphedVerts[pointnum];
dif[p] = source.oPoints[p];
}
}
if ( chan.mTargetCache.Count == 1 )
{
{
for ( int pointnum = startvert; pointnum < endvert; pointnum++ )
{
int p = source.morphedVerts[pointnum];
delt = chan.mDeltas[p];
dif[p].x += delt.x * chan.fChannelPercent;
dif[p].y += delt.y * chan.fChannelPercent;
dif[p].z += delt.z * chan.fChannelPercent;
}
}
}
else
{
float targetpercent1 = chan.GetTargetPercent(chan.segment - 3);
float targetpercent2 = chan.GetTargetPercent(chan.segment - 2);
float top = chan.fProgression - targetpercent1;
float bottom = targetpercent2 - targetpercent1;
float u = top / bottom;
for ( int pointnum = startvert; pointnum < endvert; pointnum++ )
{
int p = source.morphedVerts[pointnum];
Vector3 vert = source.oPoints[p]; //pointnum];
float length;
Vector3 progession;
endpoint[0] = chan.p1[p];
endpoint[1] = chan.p2[p];
endpoint[2] = chan.p3[p];
endpoint[3] = chan.p4[p];
if ( chan.segment == 1 )
{
splinepoint[0] = endpoint[0];
splinepoint[3] = endpoint[1];
temppoint[1] = endpoint[2] - endpoint[0];
temppoint[0] = endpoint[1] - endpoint[0];
length = temppoint[1].sqrMagnitude;
if ( length == 0.0f )
{
splinepoint[1] = endpoint[0];
splinepoint[2] = endpoint[1];
}
else
{
splinepoint[2] = endpoint[1] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1];
splinepoint[1] = endpoint[0] + chan.mCurvature * (splinepoint[2] - endpoint[0]);
}
}
else
{
if ( chan.segment == chan.mTargetCache.Count ) //chan.totaltargs )
{
splinepoint[0] = endpoint[1];
splinepoint[3] = endpoint[2];
temppoint[1] = endpoint[2] - endpoint[0];
temppoint[0] = endpoint[1] - endpoint[2];
length = temppoint[1].sqrMagnitude;
if ( length == 0.0f )
{
splinepoint[1] = endpoint[0];
splinepoint[2] = endpoint[1];
}
else
{
splinepoint[1] = endpoint[1] - (Vector3.Dot(temppoint[1], temppoint[0]) * chan.mCurvature / length) * temppoint[1];
splinepoint[2] = endpoint[2] + chan.mCurvature * (splinepoint[1] - endpoint[2]);
}
}
else
{
temppoint[1] = endpoint[2] - endpoint[0];
temppoint[0] = endpoint[1] - endpoint[0];
length = temppoint[1].sqrMagnitude;
splinepoint[0] = endpoint[1];
splinepoint[3] = endpoint[2];
if ( length == 0.0f )
splinepoint[1] = endpoint[0];
else
splinepoint[1] = endpoint[1] + (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1];
temppoint[1] = endpoint[3] - endpoint[1];
temppoint[0] = endpoint[2] - endpoint[1];
length = temppoint[1].sqrMagnitude;
if ( length == 0.0f )
splinepoint[2] = endpoint[1];
else
splinepoint[2] = endpoint[2] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1];
}
}
MegaUtils.Bez3D(out progession, ref splinepoint, u);
dif[p].x += progession.x - vert.x;
dif[p].y += progession.y - vert.y;
dif[p].z += progession.z - vert.z;
}
}
}
}
}
if ( mtmorphed )
{
for ( int i = setStart[tindex]; i < setEnd[tindex]; i++ )
sverts[source.morphMappingTo[i]] = dif[source.morphMappingFrom[i]];
for ( int i = copyStart[tindex]; i < copyEnd[tindex]; i++ )
sverts[source.nonMorphMappingTo[i]] = source.oPoints[source.nonMorphMappingFrom[i]];
}
}
int[] setStart;
int[] setEnd;
int[] copyStart;
int[] copyEnd;
int Find(int index)
{
int f = source.morphedVerts[index];
for ( int i = 0; i < source.morphMappingFrom.Length; i++ )
{
if ( source.morphMappingFrom[i] > f )
return i;
}
return source.morphMappingFrom.Length - 1;
}
void BuildMorphVertInfo(int cores)
{
int step = source.morphedVerts.Length / cores;
setStart = new int[cores];
setEnd = new int[cores];
copyStart = new int[cores];
copyEnd = new int[cores];
int start = 0;
int fv = 0;
for ( int i = 0; i < cores; i++ )
{
setStart[i] = start;
if ( i < cores - 1 )
{
setEnd[i] = Find(fv + step);
}
start = setEnd[i];
fv += step;
}
setEnd[cores - 1] = source.morphMappingFrom.Length;
// copys can be simple split as nothing happens to them
start = 0;
step = source.nonMorphMappingFrom.Length / cores;
for ( int i = 0; i < cores; i++ )
{
copyStart[i] = start;
copyEnd[i] = start + step;
start += step;
}
copyEnd[cores - 1] = source.nonMorphMappingFrom.Length;
}
public void SetAnimTime(float t)
{
animtime = t;
switch ( repeatMode )
{
case MegaRepeatMode.Loop: animtime = Mathf.Repeat(animtime, looptime); break;
//case RepeatMode.PingPong: animtime = Mathf.PingPong(animtime, looptime); break;
case MegaRepeatMode.Clamp: animtime = Mathf.Clamp(animtime, 0.0f, looptime); break;
}
SetAnim(animtime);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
namespace System.IO
{
internal sealed class SyncTextWriter : TextWriter, IDisposable
{
private readonly object _methodLock = new object();
internal readonly TextWriter _out;
internal static SyncTextWriter GetSynchronizedTextWriter(TextWriter writer)
{
Debug.Assert(writer != null);
return writer as SyncTextWriter ??
new SyncTextWriter(writer);
}
internal SyncTextWriter(TextWriter t)
: base(t.FormatProvider)
{
_out = t;
}
public override Encoding Encoding
{
get { return _out.Encoding; }
}
public override IFormatProvider FormatProvider
{
get { return _out.FormatProvider; }
}
public override String NewLine
{
get { lock (_methodLock) { return _out.NewLine; } }
set { lock (_methodLock) { _out.NewLine = value; } }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
lock (_methodLock)
{
_out.Dispose();
}
}
}
public override void Flush()
{
lock (_methodLock)
{
_out.Flush();
}
}
public override void Write(char value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(char[] buffer)
{
lock (_methodLock)
{
_out.Write(buffer);
}
}
public override void Write(char[] buffer, int index, int count)
{
lock (_methodLock)
{
_out.Write(buffer, index, count);
}
}
public override void Write(bool value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(int value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(uint value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(long value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(ulong value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(float value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(double value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(Decimal value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(String value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(Object value)
{
lock (_methodLock)
{
_out.Write(value);
}
}
public override void Write(String format, Object[] arg)
{
lock (_methodLock)
{
_out.Write(format, arg);
}
}
public override void WriteLine()
{
lock (_methodLock)
{
_out.WriteLine();
}
}
public override void WriteLine(char value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(decimal value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(char[] buffer)
{
lock (_methodLock)
{
_out.WriteLine(buffer);
}
}
public override void WriteLine(char[] buffer, int index, int count)
{
lock (_methodLock)
{
_out.WriteLine(buffer, index, count);
}
}
public override void WriteLine(bool value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(int value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(uint value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(long value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(ulong value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(float value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(double value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(String value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(Object value)
{
lock (_methodLock)
{
_out.WriteLine(value);
}
}
public override void WriteLine(String format, Object[] arg)
{
lock (_methodLock)
{
_out.WriteLine(format, arg);
}
}
//
// On SyncTextWriter all APIs should run synchronously, even the async ones.
//
public override Task WriteAsync(char value)
{
Write(value);
return Task.CompletedTask;
}
public override Task WriteAsync(String value)
{
Write(value);
return Task.CompletedTask;
}
public override Task WriteAsync(char[] buffer, int index, int count)
{
Write(buffer, index, count);
return Task.CompletedTask;
}
public override Task WriteLineAsync(char value)
{
WriteLine(value);
return Task.CompletedTask;
}
public override Task WriteLineAsync(String value)
{
WriteLine(value);
return Task.CompletedTask;
}
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
WriteLine(buffer, index, count);
return Task.CompletedTask;
}
public override Task FlushAsync()
{
Flush();
return Task.CompletedTask;
}
}
}
| |
namespace android.view.animation
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.view.animation.Animation_))]
public abstract partial class Animation : java.lang.Object, java.lang.Cloneable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Animation(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.animation.Animation.AnimationListener_))]
public partial interface AnimationListener : global::MonoJavaBridge.IJavaObject
{
void onAnimationStart(android.view.animation.Animation arg0);
void onAnimationEnd(android.view.animation.Animation arg0);
void onAnimationRepeat(android.view.animation.Animation arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.animation.Animation.AnimationListener))]
internal sealed partial class AnimationListener_ : java.lang.Object, AnimationListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal AnimationListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.view.animation.Animation.AnimationListener.onAnimationStart(android.view.animation.Animation arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.AnimationListener_.staticClass, "onAnimationStart", "(Landroid/view/animation/Animation;)V", ref global::android.view.animation.Animation.AnimationListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
void android.view.animation.Animation.AnimationListener.onAnimationEnd(android.view.animation.Animation arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.AnimationListener_.staticClass, "onAnimationEnd", "(Landroid/view/animation/Animation;)V", ref global::android.view.animation.Animation.AnimationListener_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
void android.view.animation.Animation.AnimationListener.onAnimationRepeat(android.view.animation.Animation arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.AnimationListener_.staticClass, "onAnimationRepeat", "(Landroid/view/animation/Animation;)V", ref global::android.view.animation.Animation.AnimationListener_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static AnimationListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.Animation.AnimationListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/Animation$AnimationListener"));
}
}
[global::MonoJavaBridge.JavaClass()]
protected partial class Description : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Description(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
protected Description() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.animation.Animation.Description._m0.native == global::System.IntPtr.Zero)
global::android.view.animation.Animation.Description._m0 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.Description.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.Animation.Description.staticClass, global::android.view.animation.Animation.Description._m0);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _type5876;
public int type
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetIntField(this.JvmHandle, _type5876);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _value5877;
public float value
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetFloatField(this.JvmHandle, _value5877);
}
set
{
}
}
static Description()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.Animation.Description.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/Animation$Description"));
global::android.view.animation.Animation.Description._type5876 = @__env.GetFieldIDNoThrow(global::android.view.animation.Animation.Description.staticClass, "type", "I");
global::android.view.animation.Animation.Description._value5877 = @__env.GetFieldIDNoThrow(global::android.view.animation.Animation.Description.staticClass, "value", "F");
}
}
private static global::MonoJavaBridge.MethodId _m0;
protected virtual global::android.view.animation.Animation clone()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.animation.Animation.staticClass, "clone", "()Landroid/view/animation/Animation;", ref global::android.view.animation.Animation._m0) as android.view.animation.Animation;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual void start()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "start", "()V", ref global::android.view.animation.Animation._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual void reset()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "reset", "()V", ref global::android.view.animation.Animation._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual void initialize(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "initialize", "(IIII)V", ref global::android.view.animation.Animation._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void cancel()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "cancel", "()V", ref global::android.view.animation.Animation._m4);
}
private static global::MonoJavaBridge.MethodId _m5;
protected virtual float resolveSize(int arg0, float arg1, int arg2, int arg3)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.view.animation.Animation.staticClass, "resolveSize", "(IFII)F", ref global::android.view.animation.Animation._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual int getRepeatCount()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.animation.Animation.staticClass, "getRepeatCount", "()I", ref global::android.view.animation.Animation._m6);
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void setInterpolator(android.view.animation.Interpolator arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setInterpolator", "(Landroid/view/animation/Interpolator;)V", ref global::android.view.animation.Animation._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setInterpolator(global::android.view.animation.InterpolatorDelegate arg0)
{
setInterpolator((global::android.view.animation.InterpolatorDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void setInterpolator(android.content.Context arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setInterpolator", "(Landroid/content/Context;I)V", ref global::android.view.animation.Animation._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual global::android.view.animation.Interpolator getInterpolator()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.view.animation.Interpolator>(this, global::android.view.animation.Animation.staticClass, "getInterpolator", "()Landroid/view/animation/Interpolator;", ref global::android.view.animation.Animation._m9) as android.view.animation.Interpolator;
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual bool isInitialized()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.Animation.staticClass, "isInitialized", "()Z", ref global::android.view.animation.Animation._m10);
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual void setStartOffset(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setStartOffset", "(J)V", ref global::android.view.animation.Animation._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual void setDuration(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setDuration", "(J)V", ref global::android.view.animation.Animation._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void restrictDuration(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "restrictDuration", "(J)V", ref global::android.view.animation.Animation._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void scaleCurrentDuration(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "scaleCurrentDuration", "(F)V", ref global::android.view.animation.Animation._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void setStartTime(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setStartTime", "(J)V", ref global::android.view.animation.Animation._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void startNow()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "startNow", "()V", ref global::android.view.animation.Animation._m16);
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void setRepeatMode(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setRepeatMode", "(I)V", ref global::android.view.animation.Animation._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void setRepeatCount(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setRepeatCount", "(I)V", ref global::android.view.animation.Animation._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual bool isFillEnabled()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.Animation.staticClass, "isFillEnabled", "()Z", ref global::android.view.animation.Animation._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void setFillEnabled(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setFillEnabled", "(Z)V", ref global::android.view.animation.Animation._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual void setFillBefore(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setFillBefore", "(Z)V", ref global::android.view.animation.Animation._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual void setFillAfter(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setFillAfter", "(Z)V", ref global::android.view.animation.Animation._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual void setZAdjustment(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setZAdjustment", "(I)V", ref global::android.view.animation.Animation._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual void setDetachWallpaper(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setDetachWallpaper", "(Z)V", ref global::android.view.animation.Animation._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual long getStartTime()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.view.animation.Animation.staticClass, "getStartTime", "()J", ref global::android.view.animation.Animation._m25);
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual long getDuration()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.view.animation.Animation.staticClass, "getDuration", "()J", ref global::android.view.animation.Animation._m26);
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual long getStartOffset()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.view.animation.Animation.staticClass, "getStartOffset", "()J", ref global::android.view.animation.Animation._m27);
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual int getRepeatMode()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.animation.Animation.staticClass, "getRepeatMode", "()I", ref global::android.view.animation.Animation._m28);
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual bool getFillBefore()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.Animation.staticClass, "getFillBefore", "()Z", ref global::android.view.animation.Animation._m29);
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual bool getFillAfter()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.Animation.staticClass, "getFillAfter", "()Z", ref global::android.view.animation.Animation._m30);
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual int getZAdjustment()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.animation.Animation.staticClass, "getZAdjustment", "()I", ref global::android.view.animation.Animation._m31);
}
private static global::MonoJavaBridge.MethodId _m32;
public virtual bool getDetachWallpaper()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.Animation.staticClass, "getDetachWallpaper", "()Z", ref global::android.view.animation.Animation._m32);
}
private static global::MonoJavaBridge.MethodId _m33;
public virtual bool willChangeTransformationMatrix()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.Animation.staticClass, "willChangeTransformationMatrix", "()Z", ref global::android.view.animation.Animation._m33);
}
private static global::MonoJavaBridge.MethodId _m34;
public virtual bool willChangeBounds()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.Animation.staticClass, "willChangeBounds", "()Z", ref global::android.view.animation.Animation._m34);
}
private static global::MonoJavaBridge.MethodId _m35;
public virtual void setAnimationListener(android.view.animation.Animation.AnimationListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "setAnimationListener", "(Landroid/view/animation/Animation$AnimationListener;)V", ref global::android.view.animation.Animation._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m36;
protected virtual void ensureInterpolator()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "ensureInterpolator", "()V", ref global::android.view.animation.Animation._m36);
}
private static global::MonoJavaBridge.MethodId _m37;
public virtual long computeDurationHint()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.view.animation.Animation.staticClass, "computeDurationHint", "()J", ref global::android.view.animation.Animation._m37);
}
private static global::MonoJavaBridge.MethodId _m38;
public virtual bool getTransformation(long arg0, android.view.animation.Transformation arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.Animation.staticClass, "getTransformation", "(JLandroid/view/animation/Transformation;)Z", ref global::android.view.animation.Animation._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m39;
public virtual bool hasStarted()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.Animation.staticClass, "hasStarted", "()Z", ref global::android.view.animation.Animation._m39);
}
private static global::MonoJavaBridge.MethodId _m40;
public virtual bool hasEnded()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.animation.Animation.staticClass, "hasEnded", "()Z", ref global::android.view.animation.Animation._m40);
}
private static global::MonoJavaBridge.MethodId _m41;
protected virtual void applyTransformation(float arg0, android.view.animation.Transformation arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.animation.Animation.staticClass, "applyTransformation", "(FLandroid/view/animation/Transformation;)V", ref global::android.view.animation.Animation._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m42;
public Animation(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.animation.Animation._m42.native == global::System.IntPtr.Zero)
global::android.view.animation.Animation._m42 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.Animation.staticClass, global::android.view.animation.Animation._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m43;
public Animation() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.animation.Animation._m43.native == global::System.IntPtr.Zero)
global::android.view.animation.Animation._m43 = @__env.GetMethodIDNoThrow(global::android.view.animation.Animation.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.Animation.staticClass, global::android.view.animation.Animation._m43);
Init(@__env, handle);
}
public static int INFINITE
{
get
{
return -1;
}
}
public static int RESTART
{
get
{
return 1;
}
}
public static int REVERSE
{
get
{
return 2;
}
}
public static int START_ON_FIRST_FRAME
{
get
{
return -1;
}
}
public static int ABSOLUTE
{
get
{
return 0;
}
}
public static int RELATIVE_TO_SELF
{
get
{
return 1;
}
}
public static int RELATIVE_TO_PARENT
{
get
{
return 2;
}
}
public static int ZORDER_NORMAL
{
get
{
return 0;
}
}
public static int ZORDER_TOP
{
get
{
return 1;
}
}
public static int ZORDER_BOTTOM
{
get
{
return -1;
}
}
static Animation()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.Animation.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/Animation"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.animation.Animation))]
internal sealed partial class Animation_ : android.view.animation.Animation
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Animation_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
static Animation_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.Animation_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/Animation"));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Batch
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for BatchAccountOperations.
/// </summary>
public static partial class BatchAccountOperationsExtensions
{
/// <summary>
/// Creates a new Batch account with the specified parameters. Existing
/// accounts cannot be updated with this API and should instead be updated with
/// the Update Batch Account API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the new Batch account.
/// </param>
/// <param name='accountName'>
/// A name for the Batch account which must be unique within the region. Batch
/// account names must be between 3 and 24 characters in length and must use
/// only numbers and lowercase letters. This name is used as part of the DNS
/// name that is used to access the Batch service in the region in which the
/// account is created. For example:
/// http://accountname.region.batch.azure.com/.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account creation.
/// </param>
public static BatchAccount Create(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters)
{
return operations.CreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Batch account with the specified parameters. Existing
/// accounts cannot be updated with this API and should instead be updated with
/// the Update Batch Account API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the new Batch account.
/// </param>
/// <param name='accountName'>
/// A name for the Batch account which must be unique within the region. Batch
/// account names must be between 3 and 24 characters in length and must use
/// only numbers and lowercase letters. This name is used as part of the DNS
/// name that is used to access the Batch service in the region in which the
/// account is created. For example:
/// http://accountname.region.batch.azure.com/.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account creation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BatchAccount> CreateAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the properties of an existing Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account update.
/// </param>
public static BatchAccount Update(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountUpdateParameters parameters)
{
return operations.UpdateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the properties of an existing Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account update.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BatchAccount> UpdateAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account to be
/// deleted.
/// </param>
/// <param name='accountName'>
/// The name of the account to be deleted.
/// </param>
public static BatchAccountDeleteHeaders Delete(this IBatchAccountOperations operations, string resourceGroupName, string accountName)
{
return operations.DeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account to be
/// deleted.
/// </param>
/// <param name='accountName'>
/// The name of the account to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BatchAccountDeleteHeaders> DeleteAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets information about the specified Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
public static BatchAccount Get(this IBatchAccountOperations operations, string resourceGroupName, string accountName)
{
return operations.GetAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BatchAccount> GetAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about the Batch accounts associated with the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<BatchAccount> List(this IBatchAccountOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the Batch accounts associated with the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<BatchAccount>> ListAsync(this IBatchAccountOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about the Batch accounts associated within the specified
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group whose Batch accounts to list.
/// </param>
public static IPage<BatchAccount> ListByResourceGroup(this IBatchAccountOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the Batch accounts associated within the specified
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group whose Batch accounts to list.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<BatchAccount>> ListByResourceGroupAsync(this IBatchAccountOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Synchronizes access keys for the auto storage account configured for the
/// specified Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
public static void SynchronizeAutoStorageKeys(this IBatchAccountOperations operations, string resourceGroupName, string accountName)
{
operations.SynchronizeAutoStorageKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Synchronizes access keys for the auto storage account configured for the
/// specified Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task SynchronizeAutoStorageKeysAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.SynchronizeAutoStorageKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Regenerates the specified account key for the Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
/// <param name='keyName'>
/// The type of account key to regenerate. Possible values include: 'Primary',
/// 'Secondary'
/// </param>
public static BatchAccountKeys RegenerateKey(this IBatchAccountOperations operations, string resourceGroupName, string accountName, AccountKeyType keyName)
{
return operations.RegenerateKeyAsync(resourceGroupName, accountName, keyName).GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the specified account key for the Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
/// <param name='keyName'>
/// The type of account key to regenerate. Possible values include: 'Primary',
/// 'Secondary'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BatchAccountKeys> RegenerateKeyAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, AccountKeyType keyName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, keyName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the account keys for the specified Batch account.
/// </summary>
/// <remarks>
/// This operation applies only to Batch accounts created with a
/// poolAllocationMode of 'BatchService'. If the Batch account was created with
/// a poolAllocationMode of 'UserSubscription', clients cannot use access to
/// keys to authenticate, and must use Azure Active Directory instead. In this
/// case, getting the keys will fail.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
public static BatchAccountKeys GetKeys(this IBatchAccountOperations operations, string resourceGroupName, string accountName)
{
return operations.GetKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the account keys for the specified Batch account.
/// </summary>
/// <remarks>
/// This operation applies only to Batch accounts created with a
/// poolAllocationMode of 'BatchService'. If the Batch account was created with
/// a poolAllocationMode of 'UserSubscription', clients cannot use access to
/// keys to authenticate, and must use Azure Active Directory instead. In this
/// case, getting the keys will fail.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BatchAccountKeys> GetKeysAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new Batch account with the specified parameters. Existing
/// accounts cannot be updated with this API and should instead be updated with
/// the Update Batch Account API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the new Batch account.
/// </param>
/// <param name='accountName'>
/// A name for the Batch account which must be unique within the region. Batch
/// account names must be between 3 and 24 characters in length and must use
/// only numbers and lowercase letters. This name is used as part of the DNS
/// name that is used to access the Batch service in the region in which the
/// account is created. For example:
/// http://accountname.region.batch.azure.com/.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account creation.
/// </param>
public static BatchAccount BeginCreate(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters)
{
return operations.BeginCreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Batch account with the specified parameters. Existing
/// accounts cannot be updated with this API and should instead be updated with
/// the Update Batch Account API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the new Batch account.
/// </param>
/// <param name='accountName'>
/// A name for the Batch account which must be unique within the region. Batch
/// account names must be between 3 and 24 characters in length and must use
/// only numbers and lowercase letters. This name is used as part of the DNS
/// name that is used to access the Batch service in the region in which the
/// account is created. For example:
/// http://accountname.region.batch.azure.com/.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account creation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BatchAccount> BeginCreateAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account to be
/// deleted.
/// </param>
/// <param name='accountName'>
/// The name of the account to be deleted.
/// </param>
public static BatchAccountDeleteHeaders BeginDelete(this IBatchAccountOperations operations, string resourceGroupName, string accountName)
{
return operations.BeginDeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Batch account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account to be
/// deleted.
/// </param>
/// <param name='accountName'>
/// The name of the account to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BatchAccountDeleteHeaders> BeginDeleteAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets information about the Batch accounts associated with the subscription.
/// </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<BatchAccount> ListNext(this IBatchAccountOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the Batch accounts associated with the subscription.
/// </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<BatchAccount>> ListNextAsync(this IBatchAccountOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about the Batch accounts associated within the specified
/// resource 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<BatchAccount> ListByResourceGroupNext(this IBatchAccountOperations operations, string nextPageLink)
{
return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the Batch accounts associated within the specified
/// resource 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<BatchAccount>> ListByResourceGroupNextAsync(this IBatchAccountOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Globalization {
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Text;
using System;
using System.Diagnostics.Contracts;
//
// Property Default Description
// PositiveSign '+' Character used to indicate positive values.
// NegativeSign '-' Character used to indicate negative values.
// NumberDecimalSeparator '.' The character used as the decimal separator.
// NumberGroupSeparator ',' The character used to separate groups of
// digits to the left of the decimal point.
// NumberDecimalDigits 2 The default number of decimal places.
// NumberGroupSizes 3 The number of digits in each group to the
// left of the decimal point.
// NaNSymbol "NaN" The string used to represent NaN values.
// PositiveInfinitySymbol"Infinity" The string used to represent positive
// infinities.
// NegativeInfinitySymbol"-Infinity" The string used to represent negative
// infinities.
//
//
//
// Property Default Description
// CurrencyDecimalSeparator '.' The character used as the decimal
// separator.
// CurrencyGroupSeparator ',' The character used to separate groups
// of digits to the left of the decimal
// point.
// CurrencyDecimalDigits 2 The default number of decimal places.
// CurrencyGroupSizes 3 The number of digits in each group to
// the left of the decimal point.
// CurrencyPositivePattern 0 The format of positive values.
// CurrencyNegativePattern 0 The format of negative values.
// CurrencySymbol "$" String used as local monetary symbol.
//
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class NumberFormatInfo : ICloneable, IFormatProvider
{
// invariantInfo is constant irrespective of your current culture.
private static volatile NumberFormatInfo invariantInfo;
// READTHIS READTHIS READTHIS
// This class has an exact mapping onto a native structure defined in COMNumber.cpp
// DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END.
// ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets.
// READTHIS READTHIS READTHIS
internal int[] numberGroupSizes = new int[] {3};
internal int[] currencyGroupSizes = new int[] {3};
internal int[] percentGroupSizes = new int[] {3};
internal String positiveSign = "+";
internal String negativeSign = "-";
internal String numberDecimalSeparator = ".";
internal String numberGroupSeparator = ",";
internal String currencyGroupSeparator = ",";
internal String currencyDecimalSeparator = ".";
internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund.
// The alternative currency symbol used in Win9x ANSI codepage, that can not roundtrip between ANSI and Unicode.
// Currently, only ja-JP and ko-KR has non-null values (which is U+005c, backslash)
// NOTE: The only legal values for this string are null and "\x005c"
internal String ansiCurrencySymbol = null;
internal String nanSymbol = "NaN";
internal String positiveInfinitySymbol = "Infinity";
internal String negativeInfinitySymbol = "-Infinity";
internal String percentDecimalSeparator = ".";
internal String percentGroupSeparator = ",";
internal String percentSymbol = "%";
internal String perMilleSymbol = "\u2030";
[OptionalField(VersionAdded = 2)]
internal String[] nativeDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
// an index which points to a record in Culture Data Table.
// We shouldn't be persisting dataItem (since its useless & we weren't using it),
// but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now.
[OptionalField(VersionAdded = 1)]
internal int m_dataItem = 0; // NEVER USED, DO NOT USE THIS! (Serialized in Everett)
internal int numberDecimalDigits = 2;
internal int currencyDecimalDigits = 2;
internal int currencyPositivePattern = 0;
internal int currencyNegativePattern = 0;
internal int numberNegativePattern = 1;
internal int percentPositivePattern = 0;
internal int percentNegativePattern = 0;
internal int percentDecimalDigits = 2;
#if !FEATURE_CORECLR
[OptionalField(VersionAdded = 2)]
internal int digitSubstitution = 1; // DigitShapes.None
#endif // !FEATURE_CORECLR
internal bool isReadOnly=false;
// We shouldn't be persisting m_useUserOverride (since its useless & we weren't using it),
// but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now.
[OptionalField(VersionAdded = 1)]
internal bool m_useUserOverride=false; // NEVER USED, DO NOT USE THIS! (Serialized in Everett)
// Is this NumberFormatInfo for invariant culture?
[OptionalField(VersionAdded = 2)]
internal bool m_isInvariant=false;
public NumberFormatInfo() : this(null) {
}
#region Serialization
#if !FEATURE_CORECLR
// Check if NumberFormatInfo was not set up ambiguously for parsing as number and currency
// eg. if the NumberDecimalSeparator and the NumberGroupSeparator were the same. This check
// is solely for backwards compatibility / version tolerant serialization
[OptionalField(VersionAdded = 1)]
internal bool validForParseAsNumber = true; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
[OptionalField(VersionAdded = 1)]
internal bool validForParseAsCurrency = true; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
#endif // !FEATURE_CORECLR
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
#if !FEATURE_CORECLR
// Update these legacy flags, so that 1.1/2.0 versions of the framework
// can still throw while parsing; even when using a de-serialized
// NumberFormatInfo from a 4.0+ version of the framework
if (numberDecimalSeparator != numberGroupSeparator) {
validForParseAsNumber = true;
} else {
validForParseAsNumber = false;
}
if ((numberDecimalSeparator != numberGroupSeparator) &&
(numberDecimalSeparator != currencyGroupSeparator) &&
(currencyDecimalSeparator != numberGroupSeparator) &&
(currencyDecimalSeparator != currencyGroupSeparator)) {
validForParseAsCurrency = true;
} else {
validForParseAsCurrency = false;
}
#endif // !FEATURE_CORECLR
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
}
#endregion Serialization
static private void VerifyDecimalSeparator(String decSep, String propertyName) {
if (decSep==null) {
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_String"));
}
if (decSep.Length==0) {
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyDecString"));
}
Contract.EndContractBlock();
}
static private void VerifyGroupSeparator(String groupSep, String propertyName) {
if (groupSep==null) {
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
}
static private void VerifyNativeDigits(String [] nativeDig, String propertyName) {
if (nativeDig==null) {
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_Array"));
}
if (nativeDig.Length != 10)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitCount"), propertyName);
}
Contract.EndContractBlock();
for(int i = 0; i < nativeDig.Length; i++)
{
if (nativeDig[i] == null)
{
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_ArrayValue"));
}
if (nativeDig[i].Length != 1) {
if(nativeDig[i].Length != 2) {
// Not 1 or 2 UTF-16 code points
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName);
} else if(!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1])) {
// 2 UTF-6 code points, but not a surrogate pair
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName);
}
}
if (CharUnicodeInfo.GetDecimalDigitValue(nativeDig[i], 0) != i &&
CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse) {
// Not the appropriate digit according to the Unicode data properties
// (Digit 0 must be a 0, etc.).
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName);
}
}
}
#if !FEATURE_CORECLR
static private void VerifyDigitSubstitution(DigitShapes digitSub, String propertyName) {
switch(digitSub)
{
case DigitShapes.Context:
case DigitShapes.None:
case DigitShapes.NativeNational:
// Success.
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDigitSubstitution"), propertyName);
}
}
#endif // !FEATURE_CORECLR
// We aren't persisting dataItem any more (since its useless & we weren't using it),
// Ditto with m_useUserOverride. Don't use them, we use a local copy of everything.
[System.Security.SecuritySafeCritical] // auto-generated
internal NumberFormatInfo(CultureData cultureData)
{
if (cultureData != null)
{
// We directly use fields here since these data is coming from data table or Win32, so we
// don't need to verify their values (except for invalid parsing situations).
cultureData.GetNFIValues(this);
if (cultureData.IsInvariantCulture)
{
// For invariant culture
this.m_isInvariant = true;
}
}
}
[Pure]
private void VerifyWritable() {
if (isReadOnly) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
Contract.EndContractBlock();
}
// Returns a default NumberFormatInfo that will be universally
// supported and constant irrespective of the current culture.
// Used by FromString methods.
//
public static NumberFormatInfo InvariantInfo {
get {
if (invariantInfo == null) {
// Lazy create the invariant info. This cannot be done in a .cctor because exceptions can
// be thrown out of a .cctor stack that will need this.
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.m_isInvariant = true;
invariantInfo = ReadOnly(nfi);
}
return invariantInfo;
}
}
public static NumberFormatInfo GetInstance(IFormatProvider formatProvider) {
// Fast case for a regular CultureInfo
NumberFormatInfo info;
CultureInfo cultureProvider = formatProvider as CultureInfo;
if (cultureProvider != null && !cultureProvider.m_isInherited) {
info = cultureProvider.numInfo;
if (info != null) {
return info;
}
else {
return cultureProvider.NumberFormat;
}
}
// Fast case for an NFI;
info = formatProvider as NumberFormatInfo;
if (info != null) {
return info;
}
if (formatProvider != null) {
info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
if (info != null) {
return info;
}
}
return CurrentInfo;
}
public Object Clone() {
NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone();
n.isReadOnly = false;
return n;
}
public int CurrencyDecimalDigits {
get { return currencyDecimalDigits; }
set {
if (value < 0 || value > 99) {
throw new ArgumentOutOfRangeException(
"CurrencyDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
currencyDecimalDigits = value;
}
}
public String CurrencyDecimalSeparator {
get { return currencyDecimalSeparator; }
set {
VerifyWritable();
VerifyDecimalSeparator(value, "CurrencyDecimalSeparator");
currencyDecimalSeparator = value;
}
}
public bool IsReadOnly {
get {
return isReadOnly;
}
}
//
// Check the values of the groupSize array.
//
// Every element in the groupSize array should be between 1 and 9
// excpet the last element could be zero.
//
static internal void CheckGroupSize(String propName, int[] groupSize)
{
for (int i = 0; i < groupSize.Length; i++)
{
if (groupSize[i] < 1)
{
if (i == groupSize.Length - 1 && groupSize[i] == 0)
return;
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGroupSize"), propName);
}
else if (groupSize[i] > 9)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGroupSize"), propName);
}
}
}
public int[] CurrencyGroupSizes {
get {
return ((int[])currencyGroupSizes.Clone());
}
set {
if (value == null) {
throw new ArgumentNullException("CurrencyGroupSizes",
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("CurrencyGroupSizes", inputSizes);
currencyGroupSizes = inputSizes;
}
}
public int[] NumberGroupSizes {
get {
return ((int[])numberGroupSizes.Clone());
}
set {
if (value == null) {
throw new ArgumentNullException("NumberGroupSizes",
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("NumberGroupSizes", inputSizes);
numberGroupSizes = inputSizes;
}
}
public int[] PercentGroupSizes {
get {
return ((int[])percentGroupSizes.Clone());
}
set {
if (value == null) {
throw new ArgumentNullException("PercentGroupSizes",
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("PercentGroupSizes", inputSizes);
percentGroupSizes = inputSizes;
}
}
public String CurrencyGroupSeparator {
get { return currencyGroupSeparator; }
set {
VerifyWritable();
VerifyGroupSeparator(value, "CurrencyGroupSeparator");
currencyGroupSeparator = value;
}
}
public String CurrencySymbol {
get { return currencySymbol; }
set {
if (value == null) {
throw new ArgumentNullException("CurrencySymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
currencySymbol = value;
}
}
// Returns the current culture's NumberFormatInfo. Used by Parse methods.
//
public static NumberFormatInfo CurrentInfo {
get {
System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
if (!culture.m_isInherited) {
NumberFormatInfo info = culture.numInfo;
if (info != null) {
return info;
}
}
return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)));
}
}
public String NaNSymbol {
get {
return nanSymbol;
}
set {
if (value == null) {
throw new ArgumentNullException("NaNSymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
nanSymbol = value;
}
}
public int CurrencyNegativePattern {
get { return currencyNegativePattern; }
set {
if (value < 0 || value > 15) {
throw new ArgumentOutOfRangeException(
"CurrencyNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
15));
}
Contract.EndContractBlock();
VerifyWritable();
currencyNegativePattern = value;
}
}
public int NumberNegativePattern {
get { return numberNegativePattern; }
set {
//
// NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 4) {
throw new ArgumentOutOfRangeException(
"NumberNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
4));
}
Contract.EndContractBlock();
VerifyWritable();
numberNegativePattern = value;
}
}
public int PercentPositivePattern {
get { return percentPositivePattern; }
set {
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 3) {
throw new ArgumentOutOfRangeException(
"PercentPositivePattern",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
3));
}
Contract.EndContractBlock();
VerifyWritable();
percentPositivePattern = value;
}
}
public int PercentNegativePattern {
get { return percentNegativePattern; }
set {
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 11) {
throw new ArgumentOutOfRangeException(
"PercentNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
11));
}
Contract.EndContractBlock();
VerifyWritable();
percentNegativePattern = value;
}
}
public String NegativeInfinitySymbol {
get {
return negativeInfinitySymbol;
}
set {
if (value == null) {
throw new ArgumentNullException("NegativeInfinitySymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
negativeInfinitySymbol = value;
}
}
public String NegativeSign {
get { return negativeSign; }
set {
if (value == null) {
throw new ArgumentNullException("NegativeSign",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
negativeSign = value;
}
}
public int NumberDecimalDigits {
get { return numberDecimalDigits; }
set {
if (value < 0 || value > 99) {
throw new ArgumentOutOfRangeException(
"NumberDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
numberDecimalDigits = value;
}
}
public String NumberDecimalSeparator {
get { return numberDecimalSeparator; }
set {
VerifyWritable();
VerifyDecimalSeparator(value, "NumberDecimalSeparator");
numberDecimalSeparator = value;
}
}
public String NumberGroupSeparator {
get { return numberGroupSeparator; }
set {
VerifyWritable();
VerifyGroupSeparator(value, "NumberGroupSeparator");
numberGroupSeparator = value;
}
}
public int CurrencyPositivePattern {
get { return currencyPositivePattern; }
set {
if (value < 0 || value > 3) {
throw new ArgumentOutOfRangeException(
"CurrencyPositivePattern",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
3));
}
Contract.EndContractBlock();
VerifyWritable();
currencyPositivePattern = value;
}
}
public String PositiveInfinitySymbol {
get {
return positiveInfinitySymbol;
}
set {
if (value == null) {
throw new ArgumentNullException("PositiveInfinitySymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
positiveInfinitySymbol = value;
}
}
public String PositiveSign {
get { return positiveSign; }
set {
if (value == null) {
throw new ArgumentNullException("PositiveSign",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
positiveSign = value;
}
}
public int PercentDecimalDigits {
get { return percentDecimalDigits; }
set {
if (value < 0 || value > 99) {
throw new ArgumentOutOfRangeException(
"PercentDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
percentDecimalDigits = value;
}
}
public String PercentDecimalSeparator {
get { return percentDecimalSeparator; }
set {
VerifyWritable();
VerifyDecimalSeparator(value, "PercentDecimalSeparator");
percentDecimalSeparator = value;
}
}
public String PercentGroupSeparator {
get { return percentGroupSeparator; }
set {
VerifyWritable();
VerifyGroupSeparator(value, "PercentGroupSeparator");
percentGroupSeparator = value;
}
}
public String PercentSymbol {
get {
return percentSymbol;
}
set {
if (value == null) {
throw new ArgumentNullException("PercentSymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
percentSymbol = value;
}
}
public String PerMilleSymbol {
get { return perMilleSymbol; }
set {
if (value == null) {
throw new ArgumentNullException("PerMilleSymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
perMilleSymbol = value;
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public String[] NativeDigits
{
get { return (String[])nativeDigits.Clone(); }
set
{
VerifyWritable();
VerifyNativeDigits(value, "NativeDigits");
nativeDigits = value;
}
}
#if !FEATURE_CORECLR
[System.Runtime.InteropServices.ComVisible(false)]
public DigitShapes DigitSubstitution
{
get { return (DigitShapes)digitSubstitution; }
set
{
VerifyWritable();
VerifyDigitSubstitution(value, "DigitSubstitution");
digitSubstitution = (int)value;
}
}
#endif // !FEATURE_CORECLR
public Object GetFormat(Type formatType) {
return formatType == typeof(NumberFormatInfo)? this: null;
}
public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) {
if (nfi == null) {
throw new ArgumentNullException("nfi");
}
Contract.EndContractBlock();
if (nfi.IsReadOnly) {
return (nfi);
}
NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone());
info.isReadOnly = true;
return info;
}
// private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00);
private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
internal static void ValidateParseStyleInteger(NumberStyles style) {
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), "style");
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
if ((style & ~NumberStyles.HexNumber) != 0) {
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHexStyle"));
}
}
}
internal static void ValidateParseStyleFloatingPoint(NumberStyles style) {
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), "style");
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
throw new ArgumentException(Environment.GetResourceString("Arg_HexStyleNotSupported"));
}
}
} // NumberFormatInfo
}
| |
using System.Collections.Generic;
using System.Linq;
using EnsureThat;
namespace MyCouch
{
public class QueryViewParametersConfigurator
{
protected readonly IQueryParameters Parameters;
public QueryViewParametersConfigurator(IQueryParameters parameters)
{
Parameters = parameters;
}
/// <summary>
/// Allow the results from a stale view to be used.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator Stale(Stale value)
{
Parameters.Stale = value;
return this;
}
/// <summary>
/// Include the full content of the documents in the return;
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator IncludeDocs(bool value)
{
Parameters.IncludeDocs = value;
return this;
}
/// <summary>
/// Return the documents in descending by key order.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator Descending(bool value)
{
Parameters.Descending = value;
return this;
}
/// <summary>
/// Return only documents that match the specified key.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator Key(string value)
{
Ensure.String.IsNotNullOrWhiteSpace(value, nameof(value));
return SetKey(value);
}
/// <summary>
/// Return only documents that match the specified key.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator Key<T>(T value)
{
return SetKey(value);
}
/// <summary>
/// Return only documents that match the specified complex-key.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator Key<T>(T[] value)
{
EnsureArg.HasItems(value, nameof(value));
return SetKey(value);
}
/// <summary>
/// Returns only documents that matches any of the specified keys.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator Keys<T>(params T[] value)
{
EnsureArg.HasItems(value, nameof(value));
Parameters.Keys = value.Select(i => i as object).ToArray();
return this;
}
/// <summary>
/// Return records starting with the specified key.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator StartKey(string value)
{
Ensure.String.IsNotNullOrWhiteSpace(value, nameof(value));
return SetStartKey(value);
}
/// <summary>
/// Return records starting with the specified key.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator StartKey<T>(T value)
{
return SetStartKey(value);
}
/// <summary>
/// Return records starting with the specified complex-key.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator StartKey<T>(T[] value)
{
EnsureArg.HasItems(value, nameof(value));
return SetStartKey(value);
}
/// <summary>
/// Return records starting with the specified document ID.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator StartKeyDocId(string value)
{
Ensure.String.IsNotNullOrWhiteSpace(value, nameof(value));
Parameters.StartKeyDocId = value;
return this;
}
/// <summary>
/// Stop returning records when the specified key is reached.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator EndKey(string value)
{
Ensure.String.IsNotNullOrWhiteSpace(value, nameof(value));
return SetEndKey(value);
}
/// <summary>
/// Stop returning records when the specified key is reached.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator EndKey<T>(T value)
{
return SetEndKey(value);
}
/// <summary>
/// Stop returning records when the specified complex-key is reached.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator EndKey<T>(T[] value)
{
EnsureArg.HasItems(value, nameof(value));
return SetEndKey(value);
}
/// <summary>
/// Stop returning records when the specified document ID is reached.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator EndKeyDocId(string value)
{
Ensure.String.IsNotNullOrWhiteSpace(value, nameof(value));
Parameters.EndKeyDocId = value;
return this;
}
/// <summary>
/// Specifies whether the specified end key should be included in the result.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator InclusiveEnd(bool value)
{
Parameters.InclusiveEnd = value;
return this;
}
/// <summary>
/// Skip this number of records before starting to return the results.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator Skip(int value)
{
Parameters.Skip = value;
return this;
}
/// <summary>
/// Limit the number of the returned documents to the specified number.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator Limit(int value)
{
Parameters.Limit = value;
return this;
}
/// <summary>
/// Use the reduction function.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator Reduce(bool value)
{
Parameters.Reduce = value;
return this;
}
/// <summary>
/// Include the update sequence in the generated results.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator UpdateSeq(bool value)
{
Parameters.UpdateSeq = value;
return this;
}
/// <summary>
/// The group option controls whether the reduce function reduces to a set of distinct keys or to a single result row.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator Group(bool value)
{
Parameters.Group = value;
return this;
}
/// <summary>
/// Specify the group level to be used.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator GroupLevel(int value)
{
Parameters.GroupLevel = value;
return this;
}
/// <summary>
/// Additional custom query string parameters.
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator CustomQueryParameters(IDictionary<string, object> parameters)
{
EnsureArg.HasItems(parameters, nameof(parameters));
Parameters.CustomQueryParameters = parameters;
return this;
}
/// <summary>
/// Specify if you want to target a specific list in the view.
/// </summary>
/// <param name="name"></param>
/// <param name="accept"></param>
/// <returns></returns>
public virtual QueryViewParametersConfigurator WithList(string name, string accept = null)
{
EnsureArg.IsNotNullOrWhiteSpace(name, nameof(name));
Parameters.ListName = name;
if (!string.IsNullOrWhiteSpace(accept))
Parameters.Accepts = new[] { accept };
return this;
}
protected virtual QueryViewParametersConfigurator SetKey(object value)
{
EnsureArg.IsNotNull(value, nameof(value));
Parameters.Key = value;
return this;
}
protected virtual QueryViewParametersConfigurator SetStartKey(object value)
{
EnsureArg.IsNotNull(value, nameof(value));
Parameters.StartKey = value;
return this;
}
protected virtual QueryViewParametersConfigurator SetEndKey(object value)
{
EnsureArg.IsNotNull(value, nameof(value));
Parameters.EndKey = value;
return this;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.ElasticSearch;
using ASC.Projects.Core.DataInterfaces;
using ASC.Projects.Core.Domain;
using ASC.Projects.Core.Services.NotifyService;
using ASC.Web.Projects.Core.Search;
namespace ASC.Projects.Engine
{
public class SubtaskEngine : ProjectEntityEngine
{
public IDaoFactory DaoFactory { get; set; }
public SubtaskEngine(bool disableNotifications) : base(NotifyConstants.Event_NewCommentForTask, disableNotifications)
{
}
#region get
public List<Task> GetByDate(DateTime from, DateTime to)
{
var subtasks = DaoFactory.SubtaskDao.GetUpdates(from, to).ToDictionary(x => x.Task, x => x);
var ids = subtasks.Select(x => x.Value.Task).Distinct().ToList();
var tasks = DaoFactory.TaskDao.GetById(ids);
foreach (var task in tasks)
{
Subtask subtask;
subtasks.TryGetValue(task.ID, out subtask);
task.SubTasks.Add(subtask);
}
return tasks;
}
public List<Task> GetByResponsible(Guid id, TaskStatus? status = null)
{
var subtasks = DaoFactory.SubtaskDao.GetByResponsible(id, status);
var ids = subtasks.Select(x => x.Task).Distinct().ToList();
var tasks = DaoFactory.TaskDao.GetById(ids);
foreach (var task in tasks)
{
task.SubTasks.AddRange(subtasks.FindAll(r => r.Task == task.ID));
}
return tasks;
}
public int GetSubtaskCount(int taskid, params TaskStatus[] statuses)
{
return DaoFactory.SubtaskDao.GetSubtaskCount(taskid, statuses);
}
public int GetSubtaskCount(int taskid)
{
return DaoFactory.SubtaskDao.GetSubtaskCount(taskid, null);
}
public Subtask GetById(int id)
{
return DaoFactory.SubtaskDao.GetById(id);
}
#endregion
#region Actions
public Subtask ChangeStatus(Task task, Subtask subtask, TaskStatus newStatus)
{
if (subtask == null) throw new Exception("subtask.Task");
if (task == null) throw new ArgumentNullException("task");
if (task.Status == TaskStatus.Closed) throw new Exception("task can't be closed");
if (subtask.Status == newStatus) return subtask;
ProjectSecurity.DemandEdit(task, subtask);
subtask.Status = newStatus;
subtask.LastModifiedBy = SecurityContext.CurrentAccount.ID;
subtask.LastModifiedOn = TenantUtil.DateTimeNow();
subtask.StatusChangedOn = TenantUtil.DateTimeNow();
if (subtask.Responsible.Equals(Guid.Empty))
subtask.Responsible = SecurityContext.CurrentAccount.ID;
var senders = GetSubscribers(task);
if (task.Status != TaskStatus.Closed && newStatus == TaskStatus.Closed && !DisableNotifications && senders.Count != 0)
NotifyClient.Instance.SendAboutSubTaskClosing(senders, task, subtask);
if (task.Status != TaskStatus.Closed && newStatus == TaskStatus.Open && !DisableNotifications && senders.Count != 0)
NotifyClient.Instance.SendAboutSubTaskResumed(senders, task, subtask);
return DaoFactory.SubtaskDao.Save(subtask);
}
public Subtask SaveOrUpdate(Subtask subtask, Task task)
{
if (subtask == null) throw new Exception("subtask.Task");
if (task == null) throw new ArgumentNullException("task");
if (task.Status == TaskStatus.Closed) throw new Exception("task can't be closed");
// check guest responsible
if (ProjectSecurity.IsVisitor(subtask.Responsible))
{
ProjectSecurity.CreateGuestSecurityException();
}
var isNew = subtask.ID == default(int); //Task is new
var oldResponsible = Guid.Empty;
subtask.LastModifiedBy = SecurityContext.CurrentAccount.ID;
subtask.LastModifiedOn = TenantUtil.DateTimeNow();
if (isNew)
{
if (subtask.CreateBy == default(Guid)) subtask.CreateBy = SecurityContext.CurrentAccount.ID;
if (subtask.CreateOn == default(DateTime)) subtask.CreateOn = TenantUtil.DateTimeNow();
ProjectSecurity.DemandEdit(task);
subtask = DaoFactory.SubtaskDao.Save(subtask);
}
else
{
var oldSubtask = DaoFactory.SubtaskDao.GetById(new[] { subtask.ID }).First();
if (oldSubtask == null) throw new ArgumentNullException("subtask");
oldResponsible = oldSubtask.Responsible;
//changed task
ProjectSecurity.DemandEdit(task, oldSubtask);
subtask = DaoFactory.SubtaskDao.Save(subtask);
}
NotifySubtask(task, subtask, isNew, oldResponsible);
var senders = new HashSet<Guid> { subtask.Responsible, subtask.CreateBy };
senders.Remove(Guid.Empty);
foreach (var sender in senders)
{
Subscribe(task, sender);
}
FactoryIndexer<SubtasksWrapper>.IndexAsync(subtask);
return subtask;
}
public Subtask Copy(Subtask from, Task task, IEnumerable<Participant> team)
{
var subtask = new Subtask
{
ID = default(int),
CreateBy = SecurityContext.CurrentAccount.ID,
CreateOn = TenantUtil.DateTimeNow(),
Task = task.ID,
Title = from.Title,
Status = from.Status
};
if (team.Any(r => r.ID == from.Responsible))
{
subtask.Responsible = from.Responsible;
}
return SaveOrUpdate(subtask, task);
}
private void NotifySubtask(Task task, Subtask subtask, bool isNew, Guid oldResponsible)
{
//Don't send anything if notifications are disabled
if (DisableNotifications) return;
var recipients = GetSubscribers(task);
if (!subtask.Responsible.Equals(Guid.Empty) && (isNew || !oldResponsible.Equals(subtask.Responsible)))
{
NotifyClient.Instance.SendAboutResponsibleBySubTask(subtask, task);
recipients.RemoveAll(r => r.ID.Equals(subtask.Responsible.ToString()));
}
if (isNew)
{
NotifyClient.Instance.SendAboutSubTaskCreating(recipients, task, subtask);
}
else
{
NotifyClient.Instance.SendAboutSubTaskEditing(recipients, task, subtask);
}
}
public void Delete(Subtask subtask, Task task)
{
if (subtask == null) throw new ArgumentNullException("subtask");
if (task == null) throw new ArgumentNullException("task");
ProjectSecurity.DemandEdit(task, subtask);
DaoFactory.SubtaskDao.Delete(subtask.ID);
var recipients = GetSubscribers(task);
if (recipients.Any())
{
NotifyClient.Instance.SendAboutSubTaskDeleting(recipients, task, subtask);
}
}
#endregion
}
}
| |
using System;
using Shouldly;
using Spk.Common.Helpers.Guard;
using Xunit;
// ReSharper disable InconsistentNaming
namespace Spk.Common.Tests.Helpers.Guard
{
public partial class ArgumentGuardTests
{
public class GuardIsGreaterThan_double
{
[Theory]
[InlineData(2, 1)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThan_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanTarget(
double argument,
double target)
{
var result = argument.GuardIsGreaterThan(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThan_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
double argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThan(target, nameof(argument)); });
}
}
public class GuardIsGreaterThan_float
{
[Theory]
[InlineData(2, 1)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThan_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanTarget(
float argument,
double target)
{
var result = argument.GuardIsGreaterThan(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThan_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
float argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThan(target, nameof(argument)); });
}
}
public class GuardIsGreaterThan_decimal
{
[Theory]
[InlineData(2, 1)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThan_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanTarget(
decimal argument,
double target)
{
var result = argument.GuardIsGreaterThan(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThan_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
decimal argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThan(target, nameof(argument)); });
}
}
public class GuardIsGreaterThan_short
{
[Theory]
[InlineData(2, 1)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThan_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanTarget(
short argument,
double target)
{
var result = argument.GuardIsGreaterThan(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThan_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
short argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThan(target, nameof(argument)); });
}
}
public class GuardIsGreaterThan_int
{
[Theory]
[InlineData(2, 1)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThan_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanTarget(
int argument,
double target)
{
var result = argument.GuardIsGreaterThan(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThan_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
int argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThan(target, nameof(argument)); });
}
}
public class GuardIsGreaterThan_long
{
[Theory]
[InlineData(2, 1)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThan_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanTarget(
long argument,
double target)
{
var result = argument.GuardIsGreaterThan(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThan_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
long argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThan(target, nameof(argument)); });
}
}
public class GuardIsGreaterThan_ushort
{
[Theory]
[InlineData(2, 1)]
public void GuardIsGreaterThan_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanTarget(
ushort argument,
double target)
{
var result = argument.GuardIsGreaterThan(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 2)]
public void GuardIsGreaterThan_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
ushort argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThan(target, nameof(argument)); });
}
}
public class GuardIsGreaterThan_uint
{
[Theory]
[InlineData(2, 1)]
public void GuardIsGreaterThan_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanTarget(
uint argument,
double target)
{
var result = argument.GuardIsGreaterThan(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 2)]
public void GuardIsGreaterThan_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
uint argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThan(target, nameof(argument)); });
}
public class GuardIsGreaterThan_ulong
{
[Theory]
[InlineData(2, 1)]
public void GuardIsGreaterThan_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanTarget(
ulong argument,
double target)
{
var result = argument.GuardIsGreaterThan(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 2)]
public void GuardIsGreaterThan_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
ulong argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThan(target, nameof(argument)); });
}
}
}
}
}
| |
// 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;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Text;
namespace Text.Analyzers
{
/// <summary>
/// CA1704: Identifiers should be spelled correctly
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class IdentifiersShouldBeSpelledCorrectlyAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1704";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyTitle), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageFileParse = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyFileParse), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageAssembly = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageAssembly), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNamespace = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageNamespace), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageType = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageType), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageVariable = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageVariable), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMember = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMember), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMemberParameter = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMemberParameter), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDelegateParameter = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageDelegateParameter), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageTypeTypeParameter = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageTypeTypeParameter), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMethodTypeParameter = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMethodTypeParameter), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageAssemblyMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageAssemblyMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNamespaceMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageNamespaceMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageTypeMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageTypeMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMemberMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMemberMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMemberParameterMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMemberParameterMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDelegateParameterMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageDelegateParameterMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageTypeTypeParameterMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageTypeTypeParameterMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMethodTypeParameterMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMethodTypeParameterMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyDescription), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly SourceTextValueProvider<CodeAnalysisDictionary> s_xmlDictionaryProvider = new SourceTextValueProvider<CodeAnalysisDictionary>(ParseXmlDictionary);
private static readonly SourceTextValueProvider<CodeAnalysisDictionary> s_dicDictionaryProvider = new SourceTextValueProvider<CodeAnalysisDictionary>(ParseDicDictionary);
private static readonly CodeAnalysisDictionary s_mainDictionary = GetMainDictionary();
internal static DiagnosticDescriptor FileParseRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageFileParse,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor AssemblyRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageAssembly,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor NamespaceRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageNamespace,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor TypeRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageType,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor VariableRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageVariable,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor MemberRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageMember,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor MemberParameterRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageMemberParameter,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor DelegateParameterRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageDelegateParameter,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor TypeTypeParameterRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageTypeTypeParameter,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor MethodTypeParameterRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageMethodTypeParameter,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor AssemblyMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageAssemblyMoreMeaningfulName,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor NamespaceMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageNamespaceMoreMeaningfulName,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor TypeMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageTypeMoreMeaningfulName,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor MemberMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageMemberMoreMeaningfulName,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor MemberParameterMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageMemberParameterMoreMeaningfulName,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor DelegateParameterMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageDelegateParameterMoreMeaningfulName,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor TypeTypeParameterMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageTypeTypeParameterMoreMeaningfulName,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor MethodTypeParameterMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
s_localizableMessageMethodTypeParameterMoreMeaningfulName,
DiagnosticCategory.Naming,
RuleLevel.BuildWarning,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(
FileParseRule,
AssemblyRule,
NamespaceRule,
TypeRule,
VariableRule,
MemberRule,
MemberParameterRule,
DelegateParameterRule,
TypeTypeParameterRule,
MethodTypeParameterRule,
AssemblyMoreMeaningfulNameRule,
NamespaceMoreMeaningfulNameRule,
TypeMoreMeaningfulNameRule,
MemberMoreMeaningfulNameRule,
MemberParameterMoreMeaningfulNameRule,
DelegateParameterMoreMeaningfulNameRule,
TypeTypeParameterMoreMeaningfulNameRule,
MethodTypeParameterMoreMeaningfulNameRule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(OnCompilationStart);
}
private static void OnCompilationStart(CompilationStartAnalysisContext compilationStartContext)
{
var dictionaries = ReadDictionaries();
var projectDictionary = CodeAnalysisDictionary.CreateFromDictionaries(dictionaries.Concat(s_mainDictionary));
compilationStartContext.RegisterOperationAction(AnalyzeVariable, OperationKind.VariableDeclarator);
compilationStartContext.RegisterCompilationEndAction(AnalyzeAssembly);
compilationStartContext.RegisterSymbolAction(
AnalyzeSymbol,
SymbolKind.Namespace,
SymbolKind.NamedType,
SymbolKind.Method,
SymbolKind.Property,
SymbolKind.Event,
SymbolKind.Field,
SymbolKind.Parameter);
IEnumerable<CodeAnalysisDictionary> ReadDictionaries()
{
var fileProvider = AdditionalFileProvider.FromOptions(compilationStartContext.Options);
return fileProvider.GetMatchingFiles(@"(?:dictionary|custom).*?\.(?:xml|dic)$")
.Select(CreateDictionaryFromAdditionalText)
.Where(x => x != null)
.ToList();
CodeAnalysisDictionary CreateDictionaryFromAdditionalText(AdditionalText additionalFile)
{
var text = additionalFile.GetText(compilationStartContext.CancellationToken);
var isXml = additionalFile.Path.EndsWith(".xml", StringComparison.OrdinalIgnoreCase);
var provider = isXml ? s_xmlDictionaryProvider : s_dicDictionaryProvider;
if (!compilationStartContext.TryGetValue(text, provider, out var dictionary))
{
try
{
// Annoyingly (and expectedly), TryGetValue swallows the parsing exception,
// so we have to parse again to get it.
var unused = isXml ? ParseXmlDictionary(text) : ParseDicDictionary(text);
ReportFileParseDiagnostic(additionalFile.Path, "Unknown error");
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
ReportFileParseDiagnostic(additionalFile.Path, ex.Message);
}
}
return dictionary;
}
void ReportFileParseDiagnostic(string filePath, string message)
{
var diagnostic = Diagnostic.Create(FileParseRule, Location.None, filePath, message);
compilationStartContext.RegisterCompilationEndAction(x => x.ReportDiagnostic(diagnostic));
}
}
void AnalyzeVariable(OperationAnalysisContext operationContext)
{
var variableOperation = (IVariableDeclaratorOperation)operationContext.Operation;
var variable = variableOperation.Symbol;
ReportDiagnosticsForSymbol(variable, variable.Name, operationContext.ReportDiagnostic, checkForUnmeaningful: false);
}
void AnalyzeAssembly(CompilationAnalysisContext context)
{
var assembly = context.Compilation.Assembly;
ReportDiagnosticsForSymbol(assembly, assembly.Name, context.ReportDiagnostic);
}
void AnalyzeSymbol(SymbolAnalysisContext symbolContext)
{
var typeParameterDiagnostics = Enumerable.Empty<Diagnostic>();
ISymbol symbol = symbolContext.Symbol;
if (symbol.IsOverride)
{
return;
}
var symbolName = symbol.Name;
switch (symbol)
{
case IFieldSymbol:
symbolName = RemovePrefixIfPresent('_', symbolName);
break;
case IMethodSymbol method:
switch (method.MethodKind)
{
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
return;
case MethodKind.Constructor:
case MethodKind.StaticConstructor:
symbolName = symbol.ContainingType.Name;
break;
}
foreach (var typeParameter in method.TypeParameters)
{
ReportDiagnosticsForSymbol(typeParameter, RemovePrefixIfPresent('T', typeParameter.Name), symbolContext.ReportDiagnostic);
}
break;
case INamedTypeSymbol type:
if (type.TypeKind == TypeKind.Interface)
{
symbolName = RemovePrefixIfPresent('I', symbolName);
}
foreach (var typeParameter in type.TypeParameters)
{
ReportDiagnosticsForSymbol(typeParameter, RemovePrefixIfPresent('T', typeParameter.Name), symbolContext.ReportDiagnostic);
}
break;
}
ReportDiagnosticsForSymbol(symbol, symbolName, symbolContext.ReportDiagnostic);
}
void ReportDiagnosticsForSymbol(ISymbol symbol, string symbolName, Action<Diagnostic> reportDiagnostic, bool checkForUnmeaningful = true)
{
foreach (var misspelledWord in GetMisspelledWords(symbolName))
{
reportDiagnostic(GetMisspelledWordDiagnostic(symbol, misspelledWord));
}
if (checkForUnmeaningful && symbolName.Length == 1)
{
reportDiagnostic(GetUnmeaningfulIdentifierDiagnostic(symbol, symbolName));
}
}
IEnumerable<string> GetMisspelledWords(string symbolName)
{
var parser = new WordParser(symbolName, WordParserOptions.SplitCompoundWords);
string? word;
while ((word = parser.NextWord()) != null)
{
if (!IsWordAcronym(word) && !IsWordNumeric(word) && !IsWordSpelledCorrectly(word))
{
yield return word;
}
}
}
static bool IsWordAcronym(string word) => word.All(char.IsUpper);
static bool IsWordNumeric(string word) => char.IsDigit(word[0]);
bool IsWordSpelledCorrectly(string word)
=> !projectDictionary.UnrecognizedWords.Contains(word) && projectDictionary.RecognizedWords.Contains(word);
}
private static CodeAnalysisDictionary GetMainDictionary()
{
// The "main" dictionary, Dictionary.dic, was created in WSL Ubuntu with the following commands:
//
// Install dependencies:
// > sudo apt install hunspell-tools hunspell-en-us
//
// Create dictionary:
// > unmunch /usr/share/hunspell/en_US.dic /usr/share/hunspell/en_US.aff > Dictionary.dic
//
// Tweak:
// Added the words: 'namespace'
var text = SourceText.From(TextAnalyzersResources.Dictionary);
return ParseDicDictionary(text);
}
private static CodeAnalysisDictionary ParseXmlDictionary(SourceText text)
=> text.Parse(CodeAnalysisDictionary.CreateFromXml);
private static CodeAnalysisDictionary ParseDicDictionary(SourceText text)
=> text.Parse(CodeAnalysisDictionary.CreateFromDic);
private static string RemovePrefixIfPresent(char prefix, string name)
=> name.Length > 0 && name[0] == prefix ? name[1..] : name;
private static Diagnostic GetMisspelledWordDiagnostic(ISymbol symbol, string misspelledWord)
{
return symbol.Kind switch
{
SymbolKind.Assembly => symbol.CreateDiagnostic(AssemblyRule, misspelledWord, symbol.Name),
SymbolKind.Namespace => symbol.CreateDiagnostic(NamespaceRule, misspelledWord, symbol.ToDisplayString()),
SymbolKind.NamedType => symbol.CreateDiagnostic(TypeRule, misspelledWord, symbol.ToDisplayString()),
SymbolKind.Method or SymbolKind.Property or SymbolKind.Event or SymbolKind.Field
=> symbol.CreateDiagnostic(MemberRule, misspelledWord, symbol.ToDisplayString()),
SymbolKind.Parameter => symbol.ContainingType.TypeKind == TypeKind.Delegate
? symbol.CreateDiagnostic(DelegateParameterRule, symbol.ContainingType.ToDisplayString(), misspelledWord, symbol.Name)
: symbol.CreateDiagnostic(MemberParameterRule, symbol.ContainingSymbol.ToDisplayString(), misspelledWord, symbol.Name),
SymbolKind.TypeParameter => symbol.ContainingSymbol.Kind == SymbolKind.Method
? symbol.CreateDiagnostic(MethodTypeParameterRule, symbol.ContainingSymbol.ToDisplayString(), misspelledWord, symbol.Name)
: symbol.CreateDiagnostic(TypeTypeParameterRule, symbol.ContainingSymbol.ToDisplayString(), misspelledWord, symbol.Name),
SymbolKind.Local => symbol.CreateDiagnostic(VariableRule, misspelledWord, symbol.ToDisplayString()),
_ => throw new NotImplementedException($"Unknown SymbolKind: {symbol.Kind}"),
};
}
private static Diagnostic GetUnmeaningfulIdentifierDiagnostic(ISymbol symbol, string symbolName)
{
return symbol.Kind switch
{
SymbolKind.Assembly => symbol.CreateDiagnostic(AssemblyMoreMeaningfulNameRule, symbolName),
SymbolKind.Namespace => symbol.CreateDiagnostic(NamespaceMoreMeaningfulNameRule, symbolName),
SymbolKind.NamedType => symbol.CreateDiagnostic(TypeMoreMeaningfulNameRule, symbolName),
SymbolKind.Method or SymbolKind.Property or SymbolKind.Event or SymbolKind.Field
=> symbol.CreateDiagnostic(MemberMoreMeaningfulNameRule, symbolName),
SymbolKind.Parameter => symbol.ContainingType.TypeKind == TypeKind.Delegate
? symbol.CreateDiagnostic(DelegateParameterMoreMeaningfulNameRule, symbol.ContainingType.ToDisplayString(), symbolName)
: symbol.CreateDiagnostic(MemberParameterMoreMeaningfulNameRule, symbol.ContainingSymbol.ToDisplayString(), symbolName),
SymbolKind.TypeParameter => symbol.ContainingSymbol.Kind == SymbolKind.Method
? symbol.CreateDiagnostic(MethodTypeParameterMoreMeaningfulNameRule, symbol.ContainingSymbol.ToDisplayString(), symbol.Name)
: symbol.CreateDiagnostic(TypeTypeParameterMoreMeaningfulNameRule, symbol.ContainingSymbol.ToDisplayString(), symbol.Name),
_ => throw new NotImplementedException($"Unknown SymbolKind: {symbol.Kind}"),
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Core.Routing;
using Microsoft.Msagl.Routing.ConstrainedDelaunayTriangulation;
using Microsoft.Msagl.DebugHelpers;
namespace Microsoft.Msagl.Routing.Spline.Bundling {
/// <summary>
/// Calculates node radii with 'water algorithm'
/// </summary>
public class HubRadiiCalculator {
/// <summary>
/// bundle data
/// </summary>
readonly MetroGraphData metroGraphData;
/// <summary>
/// Algorithm settings
/// </summary>
readonly BundlingSettings bundlingSettings;
internal HubRadiiCalculator(MetroGraphData metroGraphData, BundlingSettings bundlingSettings) {
this.metroGraphData = metroGraphData;
this.bundlingSettings = bundlingSettings;
}
/// <summary>
/// calculate node radii with fixed hubs
/// </summary>
internal void CreateNodeRadii() {
//set radii to zero
foreach (var v in metroGraphData.VirtualNodes()) {
v.Radius = 0;
v.cachedIdealRadius = CalculateIdealHubRadiusWithNeighbors(metroGraphData, bundlingSettings, v);
;
}
//TimeMeasurer.DebugOutput("Initial cost of radii: " + Cost());
GrowHubs(false);
//maximally use free space
GrowHubs(true);
//TimeMeasurer.DebugOutput("Optimized cost of radii: " + Cost());
//ensure radii are not zero
foreach (var v in metroGraphData.VirtualNodes()) {
v.Radius = Math.Max(v.Radius, bundlingSettings.MinHubRadius);
}
}
/// <summary>
/// Grow hubs
/// </summary>
bool GrowHubs(bool useHalfEdgesAsIdealR) {
var queue = new GenericBinaryHeapPriorityQueue<Station>();
foreach (var v in metroGraphData.VirtualNodes()) {
queue.Enqueue(v, -CalculatePotential(v, useHalfEdgesAsIdealR));
}
bool progress = false;
//choose a hub with the greatest potential
while (!queue.IsEmpty()) {
double hu;
Station v = queue.Dequeue(out hu);
if (hu >= 0)
break;
//grow the hub
if (TryGrowHub(v, useHalfEdgesAsIdealR)) {
queue.Enqueue(v, -CalculatePotential(v, useHalfEdgesAsIdealR));
progress = true;
}
}
return progress;
}
bool TryGrowHub(Station v, bool useHalfEdgesAsIdealR) {
double oldR = v.Radius;
double allowedRadius = CalculateAllowedHubRadius(v);
Debug.Assert(allowedRadius > 0);
if (v.Radius >= allowedRadius)
return false;
double idealR = useHalfEdgesAsIdealR ?
CalculateIdealHubRadiusWithAdjacentEdges(metroGraphData, bundlingSettings, v) :
v.cachedIdealRadius;
Debug.Assert(idealR > 0);
if (v.Radius >= idealR)
return false;
double step = 0.05;
double delta = step * (idealR - v.Radius);
if (delta < 1.0)
delta = 1.0;
double newR = Math.Min(v.Radius + delta, allowedRadius);
if (newR <= v.Radius)
return false;
v.Radius = newR;
return true;
}
double CalculatePotential(Station v, bool useHalfEdgesAsIdealR) {
double idealR = useHalfEdgesAsIdealR ?
CalculateIdealHubRadiusWithAdjacentEdges(metroGraphData, bundlingSettings, v) :
v.cachedIdealRadius;
if (idealR <= v.Radius)
return 0.0;
return (idealR - v.Radius) / idealR;
}
#region allowed and desired radii
///<summary>
/// Returns the maximal possible radius of the node
/// </summary>
double CalculateAllowedHubRadius(Station node) {
double r = bundlingSettings.MaxHubRadius;
//adjacent nodes
foreach (Station adj in node.Neighbors) {
double dist = (adj.Position - node.Position).Length;
Debug.Assert(dist - 0.05 * (node.Radius + adj.Radius) + 1 >= node.Radius + adj.Radius);
r = Math.Min(r, dist / 1.05 - adj.Radius);
}
//TODO: still we can have two intersecting hubs for not adjacent nodes
//obstacles
double minimalDistance = metroGraphData.tightIntersections.GetMinimalDistanceToObstacles(node, node.Position, r);
if (minimalDistance < r)
r = minimalDistance - 0.001;
return Math.Max(r, 0.1);
}
/// <summary>
/// Returns the ideal radius of the hub
/// </summary>
static double CalculateIdealHubRadius(MetroGraphData metroGraphData, BundlingSettings bundlingSettings, Station node) {
double r = 1.0;
foreach (Station adj in node.Neighbors) {
double width = metroGraphData.GetWidth(adj, node, bundlingSettings.EdgeSeparation);
double nr = width / 2.0 + bundlingSettings.EdgeSeparation;
r = Math.Max(r, nr);
}
r = Math.Min(r, 2 * bundlingSettings.MaxHubRadius);
return r;
}
/// <summary>
/// Returns the ideal radius of the hub
/// </summary>
internal static double CalculateIdealHubRadiusWithNeighbors(MetroGraphData metroGraphData, BundlingSettings bundlingSettings, Station node) {
return CalculateIdealHubRadiusWithNeighbors(metroGraphData, bundlingSettings, node, node.Position);
}
/// <summary>
/// Returns the ideal radius of the hub
/// </summary>
internal static double CalculateIdealHubRadiusWithNeighbors(MetroGraphData metroGraphData, BundlingSettings bundlingSettings, Station node, Point newPosition) {
double r = CalculateIdealHubRadius(metroGraphData, bundlingSettings, node);
if (node.Neighbors.Count() > 1) {
Station[] adjNodes = node.Neighbors;
//there must be enough space between neighbor bundles
for (int i = 0; i < adjNodes.Length; i++) {
Station adj = adjNodes[i];
Station nextAdj = adjNodes[(i + 1) % adjNodes.Length];
r = Math.Max(r, GetMinRadiusForTwoAdjacentBundles(r, node, newPosition, adj, nextAdj, metroGraphData, bundlingSettings));
}
}
r = Math.Min(r, 2 * bundlingSettings.MaxHubRadius);
return r;
}
/// <summary>
/// Returns the ideal radius of the hub
/// </summary>
static double CalculateIdealHubRadiusWithAdjacentEdges(MetroGraphData metroGraphData, BundlingSettings bundlingSettings, Station node) {
double r = bundlingSettings.MaxHubRadius;
foreach (var adj in node.Neighbors) {
r = Math.Min(r, (node.Position - adj.Position).Length / 2);
}
return r;
}
internal static double GetMinRadiusForTwoAdjacentBundles(double r, Station node, Point nodePosition, Station adj0, Station adj1,
MetroGraphData metroGraphData, BundlingSettings bundlingSettings) {
double w0 = metroGraphData.GetWidth(node, adj0, bundlingSettings.EdgeSeparation);
double w1 = metroGraphData.GetWidth(node, adj1, bundlingSettings.EdgeSeparation);
return GetMinRadiusForTwoAdjacentBundles(r, nodePosition, adj0.Position, adj1.Position, w0, w1, metroGraphData, bundlingSettings);
}
/// <summary>
/// Radius we need to draw to separate adjacent bundles ab and ac
/// </summary>
internal static double GetMinRadiusForTwoAdjacentBundles(double r, Point a, Point b, Point c, double widthAB, double widthAC,
MetroGraphData metroGraphData, BundlingSettings bundlingSettings) {
if (widthAB < ApproximateComparer.DistanceEpsilon || widthAC < ApproximateComparer.DistanceEpsilon)
return r;
double angle = Point.Angle(b, a, c);
angle = Math.Min(angle, Math.PI * 2 - angle);
if (angle < ApproximateComparer.DistanceEpsilon)
return 2 * bundlingSettings.MaxHubRadius;
if (angle >= Math.PI / 2)
return r * 1.05;
//find the intersection point of two bundles
double sina = Math.Sin(angle);
double cosa = Math.Cos(angle);
double aa = widthAB / (4 * sina);
double bb = widthAC / (4 * sina);
double d = 2 * Math.Sqrt(aa * aa + bb * bb + 2 * aa * bb * cosa);
d = Math.Min(d, 2 * bundlingSettings.MaxHubRadius);
d = Math.Max(d, r);
return d;
}
#endregion
}
}
| |
//
// MonoDevelop.Components.Docking.cs
//
// Author:
// Lluis Sanchez Gual
//
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using Gtk;
using Gdk;
namespace MonoDevelop.Components.Docking
{
public class DockFrame: HBox
{
internal const double ItemDockCenterArea = 0.4;
internal const int GroupDockSeparatorSize = 40;
internal bool ShadedSeparators = true;
DockContainer container;
int handleSize = IsWindows ? 4 : 6;
int handlePadding = 0;
int defaultItemWidth = 130;
int defaultItemHeight = 130;
uint autoShowDelay = 400;
uint autoHideDelay = 500;
SortedDictionary<string,DockLayout> layouts = new SortedDictionary<string,DockLayout> ();
List<DockFrameTopLevel> topLevels = new List<DockFrameTopLevel> ();
string currentLayout;
int compactGuiLevel = 3;
DockBar dockBarTop, dockBarBottom, dockBarLeft, dockBarRight;
VBox mainBox;
ShadedContainer shadedContainer;
public DockFrame ()
{
shadedContainer = new ShadedContainer ();
dockBarTop = new DockBar (this, Gtk.PositionType.Top);
dockBarBottom = new DockBar (this, Gtk.PositionType.Bottom);
dockBarLeft = new DockBar (this, Gtk.PositionType.Left);
dockBarRight = new DockBar (this, Gtk.PositionType.Right);
container = new DockContainer (this);
HBox hbox = new HBox ();
hbox.PackStart (dockBarLeft, false, false, 0);
hbox.PackStart (container, true, true, 0);
hbox.PackStart (dockBarRight, false, false, 0);
mainBox = new VBox ();
mainBox.PackStart (dockBarTop, false, false, 0);
mainBox.PackStart (hbox, true, true, 0);
mainBox.PackStart (dockBarBottom, false, false, 0);
Add (mainBox);
mainBox.ShowAll ();
mainBox.NoShowAll = true;
CompactGuiLevel = 2;
dockBarTop.UpdateVisibility ();
dockBarBottom.UpdateVisibility ();
dockBarLeft.UpdateVisibility ();
dockBarRight.UpdateVisibility ();
}
/// <summary>
/// Compactness level of the gui, from 1 (not compact) to 5 (very compact).
/// </summary>
public int CompactGuiLevel {
get { return compactGuiLevel; }
set {
compactGuiLevel = value;
switch (compactGuiLevel) {
case 1: handleSize = 6; break;
case 2:
case 3: handleSize = IsWindows ? 4 : 6; break;
case 4:
case 5: handleSize = 3; break;
}
handlePadding = 0;
dockBarTop.OnCompactLevelChanged ();
dockBarBottom.OnCompactLevelChanged ();
dockBarLeft.OnCompactLevelChanged ();
dockBarRight.OnCompactLevelChanged ();
container.RelayoutWidgets ();
}
}
public DockBar ExtractDockBar (PositionType pos)
{
DockBar db = new DockBar (this, pos);
switch (pos) {
case PositionType.Left: db.OriginalBar = dockBarLeft; dockBarLeft = db; break;
case PositionType.Top: db.OriginalBar = dockBarTop; dockBarTop = db; break;
case PositionType.Right: db.OriginalBar = dockBarRight; dockBarRight = db; break;
case PositionType.Bottom: db.OriginalBar = dockBarBottom; dockBarBottom = db; break;
}
return db;
}
internal DockBar GetDockBar (PositionType pos)
{
switch (pos) {
case Gtk.PositionType.Top: return dockBarTop;
case Gtk.PositionType.Bottom: return dockBarBottom;
case Gtk.PositionType.Left: return dockBarLeft;
case Gtk.PositionType.Right: return dockBarRight;
}
return null;
}
internal DockContainer Container {
get { return container; }
}
public ShadedContainer ShadedContainer {
get { return this.shadedContainer; }
}
public int HandleSize {
get {
return handleSize;
}
set {
handleSize = value;
}
}
public int HandlePadding {
get {
return handlePadding;
}
set {
handlePadding = value;
}
}
public int DefaultItemWidth {
get {
return defaultItemWidth;
}
set {
defaultItemWidth = value;
}
}
public int DefaultItemHeight {
get {
return defaultItemHeight;
}
set {
defaultItemHeight = value;
}
}
internal int TotalHandleSize {
get { return handleSize + handlePadding*2; }
}
public DockItem AddItem (string id)
{
foreach (DockItem dit in container.Items) {
if (dit.Id == id) {
if (dit.IsPositionMarker) {
dit.IsPositionMarker = false;
return dit;
}
throw new InvalidOperationException ("An item with id '" + id + "' already exists.");
}
}
DockItem it = new DockItem (this, id);
container.Items.Add (it);
return it;
}
public void RemoveItem (DockItem it)
{
if (container.Layout != null)
container.Layout.RemoveItemRec (it);
foreach (DockGroup grp in layouts.Values)
grp.RemoveItemRec (it);
container.Items.Remove (it);
}
public DockItem GetItem (string id)
{
foreach (DockItem it in container.Items) {
if (it.Id == id) {
if (!it.IsPositionMarker)
return it;
else
return null;
}
}
return null;
}
public IEnumerable<DockItem> GetItems ()
{
return container.Items;
}
bool LoadLayout (string layoutName)
{
DockLayout dl;
if (!layouts.TryGetValue (layoutName, out dl))
return false;
container.LoadLayout (dl);
return true;
}
public void CreateLayout (string name)
{
CreateLayout (name, false);
}
public void DeleteLayout (string name)
{
layouts.Remove (name);
}
public void CreateLayout (string name, bool copyCurrent)
{
DockLayout dl;
if (container.Layout == null || !copyCurrent) {
dl = GetDefaultLayout ();
} else {
container.StoreAllocation ();
dl = (DockLayout) container.Layout.Clone ();
}
dl.Name = name;
layouts [name] = dl;
}
public string CurrentLayout {
get {
return currentLayout;
}
set {
if (currentLayout == value)
return;
if (LoadLayout (value)) {
currentLayout = value;
}
}
}
public bool HasLayout (string id)
{
return layouts.ContainsKey (id);
}
public string[] Layouts {
get {
if (layouts.Count == 0)
return new string [0];
string[] arr = new string [layouts.Count];
layouts.Keys.CopyTo (arr, 0);
return arr;
}
}
public uint AutoShowDelay {
get {
return autoShowDelay;
}
set {
autoShowDelay = value;
}
}
public uint AutoHideDelay {
get {
return autoHideDelay;
}
set {
autoHideDelay = value;
}
}
public void SaveLayouts (string file)
{
using (XmlTextWriter w = new XmlTextWriter (file, System.Text.Encoding.UTF8)) {
w.Formatting = Formatting.Indented;
SaveLayouts (w);
}
}
public void SaveLayouts (XmlWriter writer)
{
if (container.Layout != null)
container.Layout.StoreAllocation ();
writer.WriteStartElement ("layouts");
foreach (DockLayout la in layouts.Values)
la.Write (writer);
writer.WriteEndElement ();
}
public void LoadLayouts (string file)
{
using (XmlReader r = new XmlTextReader (new System.IO.StreamReader (file))) {
LoadLayouts (r);
}
}
public void LoadLayouts (XmlReader reader)
{
layouts.Clear ();
container.Clear ();
currentLayout = null;
reader.MoveToContent ();
if (reader.IsEmptyElement) {
reader.Skip ();
return;
}
reader.ReadStartElement ("layouts");
reader.MoveToContent ();
while (reader.NodeType != XmlNodeType.EndElement) {
if (reader.NodeType == XmlNodeType.Element) {
DockLayout layout = DockLayout.Read (this, reader);
layouts.Add (layout.Name, layout);
}
else
reader.Skip ();
reader.MoveToContent ();
}
reader.ReadEndElement ();
container.RelayoutWidgets ();
}
internal void UpdateTitle (DockItem item)
{
DockGroupItem gitem = container.FindDockGroupItem (item.Id);
if (gitem == null)
return;
gitem.ParentGroup.UpdateTitle (item);
dockBarTop.UpdateTitle (item);
dockBarBottom.UpdateTitle (item);
dockBarLeft.UpdateTitle (item);
dockBarRight.UpdateTitle (item);
}
internal void Present (DockItem item, bool giveFocus)
{
DockGroupItem gitem = container.FindDockGroupItem (item.Id);
if (gitem == null)
return;
gitem.ParentGroup.Present (item, giveFocus);
}
internal bool GetVisible (DockItem item)
{
DockGroupItem gitem = container.FindDockGroupItem (item.Id);
if (gitem == null)
return false;
return gitem.VisibleFlag;
}
internal bool GetVisible (DockItem item, string layoutName)
{
DockLayout dl;
if (!layouts.TryGetValue (layoutName, out dl))
return false;
DockGroupItem gitem = dl.FindDockGroupItem (item.Id);
if (gitem == null)
return false;
return gitem.VisibleFlag;
}
internal void SetVisible (DockItem item, bool visible)
{
if (container.Layout == null)
return;
DockGroupItem gitem = container.FindDockGroupItem (item.Id);
if (gitem == null) {
if (visible) {
// The item is not present in the layout. Add it now.
if (!string.IsNullOrEmpty (item.DefaultLocation))
gitem = AddDefaultItem (container.Layout, item);
if (gitem == null) {
// No default position
gitem = new DockGroupItem (this, item);
container.Layout.AddObject (gitem);
}
} else
return; // Already invisible
}
gitem.SetVisible (visible);
container.RelayoutWidgets ();
}
internal DockItemStatus GetStatus (DockItem item)
{
DockGroupItem gitem = container.FindDockGroupItem (item.Id);
if (gitem == null)
return DockItemStatus.Dockable;
return gitem.Status;
}
internal void SetStatus (DockItem item, DockItemStatus status)
{
DockGroupItem gitem = container.FindDockGroupItem (item.Id);
if (gitem == null) {
item.DefaultStatus = status;
return;
}
gitem.StoreAllocation ();
gitem.Status = status;
container.RelayoutWidgets ();
}
internal void SetDockLocation (DockItem item, string placement)
{
bool vis = item.Visible;
DockItemStatus stat = item.Status;
item.ResetMode ();
container.Layout.RemoveItemRec (item);
AddItemAtLocation (container.Layout, item, placement, vis, stat);
}
DockLayout GetDefaultLayout ()
{
DockLayout group = new DockLayout (this);
// Add items which don't have relative defaut positions
List<DockItem> todock = new List<DockItem> ();
foreach (DockItem item in container.Items) {
if (string.IsNullOrEmpty (item.DefaultLocation)) {
DockGroupItem dgt = new DockGroupItem (this, item);
dgt.SetVisible (item.DefaultVisible);
group.AddObject (dgt);
}
else
todock.Add (item);
}
// Add items with relative positions.
int lastCount = 0;
while (lastCount != todock.Count) {
lastCount = todock.Count;
for (int n=0; n<todock.Count; n++) {
DockItem it = todock [n];
if (AddDefaultItem (group, it) != null) {
todock.RemoveAt (n);
n--;
}
}
}
// Items which could not be docked because of an invalid default location
foreach (DockItem item in todock) {
DockGroupItem dgt = new DockGroupItem (this, item);
dgt.SetVisible (false);
group.AddObject (dgt);
}
// group.Dump ();
return group;
}
DockGroupItem AddDefaultItem (DockGroup grp, DockItem it)
{
return AddItemAtLocation (grp, it, it.DefaultLocation, it.DefaultVisible, it.DefaultStatus);
}
DockGroupItem AddItemAtLocation (DockGroup grp, DockItem it, string location, bool visible, DockItemStatus status)
{
string[] positions = location.Split (';');
foreach (string pos in positions) {
int i = pos.IndexOf ('/');
if (i == -1) continue;
string id = pos.Substring (0,i).Trim ();
DockGroup g = grp.FindGroupContaining (id);
if (g != null) {
DockPosition dpos;
try {
dpos = (DockPosition) Enum.Parse (typeof(DockPosition), pos.Substring(i+1).Trim(), true);
}
catch {
continue;
}
DockGroupItem dgt = g.AddObject (it, dpos, id);
dgt.SetVisible (visible);
dgt.Status = status;
return dgt;
}
}
return null;
}
internal void AddTopLevel (DockFrameTopLevel w, int x, int y)
{
w.Parent = this;
w.X = x;
w.Y = y;
Requisition r = w.SizeRequest ();
w.Allocation = new Gdk.Rectangle (Allocation.X + x, Allocation.Y + y, r.Width, r.Height);
topLevels.Add (w);
}
internal void RemoveTopLevel (DockFrameTopLevel w)
{
w.Unparent ();
topLevels.Remove (w);
QueueResize ();
}
public Gdk.Rectangle GetCoordinates (Gtk.Widget w)
{
int px, py;
if (!w.TranslateCoordinates (this, 0, 0, out px, out py))
return new Gdk.Rectangle (0,0,0,0);
Gdk.Rectangle rect = w.Allocation;
rect.X = px - Allocation.X;
rect.Y = py - Allocation.Y;
return rect;
}
internal void ShowPlaceholder ()
{
container.ShowPlaceholder ();
}
internal void DockInPlaceholder (DockItem item)
{
container.DockInPlaceholder (item);
}
internal void HidePlaceholder ()
{
container.HidePlaceholder ();
}
internal void UpdatePlaceholder (DockItem item, Gdk.Size size, bool allowDocking)
{
container.UpdatePlaceholder (item, size, allowDocking);
}
internal DockBarItem BarDock (Gtk.PositionType pos, DockItem item, int size)
{
return GetDockBar (pos).AddItem (item, size);
}
internal AutoHideBox AutoShow (DockItem item, DockBar bar, int size)
{
AutoHideBox aframe = new AutoHideBox (this, item, bar.Position, size);
Gdk.Size sTop = GetBarFrameSize (dockBarTop);
Gdk.Size sBot = GetBarFrameSize (dockBarBottom);
Gdk.Size sLeft = GetBarFrameSize (dockBarLeft);
Gdk.Size sRgt = GetBarFrameSize (dockBarRight);
int x,y;
if (bar == dockBarLeft || bar == dockBarRight) {
aframe.HeightRequest = Allocation.Height - sTop.Height - sBot.Height;
aframe.WidthRequest = size;
y = sTop.Height;
if (bar == dockBarLeft)
x = sLeft.Width;
else
x = Allocation.Width - size - sRgt.Width;
} else {
aframe.WidthRequest = Allocation.Width - sLeft.Width - sRgt.Width;
aframe.HeightRequest = size;
x = sLeft.Width;
if (bar == dockBarTop)
y = sTop.Height;
else
y = Allocation.Height - size - sBot.Height;
}
AddTopLevel (aframe, x, y);
aframe.AnimateShow ();
return aframe;
}
internal void UpdateSize (DockBar bar, AutoHideBox aframe)
{
Gdk.Size sTop = GetBarFrameSize (dockBarTop);
Gdk.Size sBot = GetBarFrameSize (dockBarBottom);
Gdk.Size sLeft = GetBarFrameSize (dockBarLeft);
Gdk.Size sRgt = GetBarFrameSize (dockBarRight);
if (bar == dockBarLeft || bar == dockBarRight) {
aframe.HeightRequest = Allocation.Height - sTop.Height - sBot.Height;
if (bar == dockBarRight)
aframe.X = Allocation.Width - aframe.Allocation.Width - sRgt.Width;
} else {
aframe.WidthRequest = Allocation.Width - sLeft.Width - sRgt.Width;
if (bar == dockBarBottom)
aframe.Y = Allocation.Height - aframe.Allocation.Height - sBot.Height;
}
}
Gdk.Size GetBarFrameSize (DockBar bar)
{
if (bar.OriginalBar != null)
bar = bar.OriginalBar;
if (!bar.Visible)
return new Gdk.Size (0,0);
Gtk.Requisition req = bar.SizeRequest ();
return new Gdk.Size (req.Width, req.Height);
}
internal void AutoHide (DockItem item, AutoHideBox widget, bool animate)
{
if (animate) {
widget.Hidden += delegate {
if (!widget.Disposed)
AutoHide (item, widget, false);
};
widget.AnimateHide ();
}
else {
Gtk.Container parent = (Gtk.Container) item.Widget.Parent;
parent.Remove (item.Widget);
RemoveTopLevel (widget);
widget.Disposed = true;
widget.Destroy ();
}
}
protected override void OnSizeAllocated (Rectangle allocation)
{
base.OnSizeAllocated (allocation);
foreach (DockFrameTopLevel tl in topLevels) {
Requisition r = tl.SizeRequest ();
tl.SizeAllocate (new Gdk.Rectangle (allocation.X + tl.X, allocation.Y + tl.Y, r.Width, r.Height));
}
}
protected override void ForAll (bool include_internals, Callback callback)
{
base.ForAll (include_internals, callback);
List<DockFrameTopLevel> clone = new List<DockFrameTopLevel> (topLevels);
foreach (DockFrameTopLevel child in clone)
callback (child);
}
protected override void OnRealized ()
{
base.OnRealized ();
HslColor cLight = new HslColor (Style.Background (Gtk.StateType.Normal));
HslColor cDark = cLight;
cLight.L *= 0.9;
cDark.L *= 0.8;
shadedContainer.LightColor = cLight;
shadedContainer.DarkColor = cDark;
}
static internal bool IsWindows {
get { return System.IO.Path.DirectorySeparatorChar == '\\'; }
}
internal static Cairo.Color ToCairoColor (Gdk.Color color)
{
return new Cairo.Color (color.Red / (double) ushort.MaxValue, color.Green / (double) ushort.MaxValue, color.Blue / (double) ushort.MaxValue);
}
}
internal delegate void DockDelegate (DockItem item);
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.Runtime.InteropServices;
namespace Urho
{
// Todo: Remove this warning when the code goes public.
#pragma warning disable 3019
[StructLayout(LayoutKind.Sequential)]
public struct Matrix3 : IEquatable<Matrix3>
{
#region Fields & Access
/// <summary>Row 0, Column 0</summary>
public float R0C0;
/// <summary>Row 0, Column 1</summary>
public float R0C1;
/// <summary>Row 0, Column 2</summary>
public float R0C2;
/// <summary>Row 1, Column 0</summary>
public float R1C0;
/// <summary>Row 1, Column 1</summary>
public float R1C1;
/// <summary>Row 1, Column 2</summary>
public float R1C2;
/// <summary>Row 2, Column 0</summary>
public float R2C0;
/// <summary>Row 2, Column 1</summary>
public float R2C1;
/// <summary>Row 2, Column 2</summary>
public float R2C2;
/// <summary>Gets the component at the given row and column in the matrix.</summary>
/// <param name="row">The row of the matrix.</param>
/// <param name="column">The column of the matrix.</param>
/// <returns>The component at the given row and column in the matrix.</returns>
public float this[int row, int column]
{
get
{
switch( row )
{
case 0:
switch (column)
{
case 0: return R0C0;
case 1: return R0C1;
case 2: return R0C2;
}
break;
case 1:
switch (column)
{
case 0: return R1C0;
case 1: return R1C1;
case 2: return R1C2;
}
break;
case 2:
switch (column)
{
case 0: return R2C0;
case 1: return R2C1;
case 2: return R2C2;
}
break;
}
throw new IndexOutOfRangeException();
}
set
{
switch( row )
{
case 0:
switch (column)
{
case 0: R0C0 = value; return;
case 1: R0C1 = value; return;
case 2: R0C2 = value; return;
}
break;
case 1:
switch (column)
{
case 0: R1C0 = value; return;
case 1: R1C1 = value; return;
case 2: R1C2 = value; return;
}
break;
case 2:
switch (column)
{
case 0: R2C0 = value; return;
case 1: R2C1 = value; return;
case 2: R2C2 = value; return;
}
break;
}
throw new IndexOutOfRangeException();
}
}
/// <summary>Gets the component at the index into the matrix.</summary>
/// <param name="index">The index into the components of the matrix.</param>
/// <returns>The component at the given index into the matrix.</returns>
public float this[int index]
{
get
{
switch (index)
{
case 0: return R0C0;
case 1: return R0C1;
case 2: return R0C2;
case 3: return R1C0;
case 4: return R1C1;
case 5: return R1C2;
case 6: return R2C0;
case 7: return R2C1;
case 8: return R2C2;
default: throw new IndexOutOfRangeException();
}
}
set
{
switch (index)
{
case 0: R0C0 = value; return;
case 1: R0C1 = value; return;
case 2: R0C2 = value; return;
case 3: R1C0 = value; return;
case 4: R1C1 = value; return;
case 5: R1C2 = value; return;
case 6: R2C0 = value; return;
case 7: R2C1 = value; return;
case 8: R2C2 = value; return;
default: throw new IndexOutOfRangeException();
}
}
}
/// <summary>Converts the matrix into an IntPtr.</summary>
/// <param name="matrix">The matrix to convert.</param>
/// <returns>An IntPtr for the matrix.</returns>
public static explicit operator IntPtr(Matrix3 matrix)
{
unsafe
{
return (IntPtr)(&matrix.R0C0);
}
}
/// <summary>Converts the matrix into left float*.</summary>
/// <param name="matrix">The matrix to convert.</param>
/// <returns>A float* for the matrix.</returns>
[CLSCompliant(false)]
unsafe public static explicit operator float*(Matrix3 matrix)
{
return &matrix.R0C0;
}
/// <summary>Converts the matrix into an array of floats.</summary>
/// <param name="matrix">The matrix to convert.</param>
/// <returns>An array of floats for the matrix.</returns>
public static explicit operator float[](Matrix3 matrix)
{
return new float[9]
{
matrix.R0C0,
matrix.R0C1,
matrix.R0C2,
matrix.R1C0,
matrix.R1C1,
matrix.R1C2,
matrix.R2C0,
matrix.R2C1,
matrix.R2C2
};
}
#endregion
#region Constructors
/// <summary>Constructs left matrix with the same components as the given matrix.</summary>
/// <param name="vector">The matrix whose components to copy.</param>
public Matrix3(ref Matrix3 matrix)
{
this.R0C0 = matrix.R0C0;
this.R0C1 = matrix.R0C1;
this.R0C2 = matrix.R0C2;
this.R1C0 = matrix.R1C0;
this.R1C1 = matrix.R1C1;
this.R1C2 = matrix.R1C2;
this.R2C0 = matrix.R2C0;
this.R2C1 = matrix.R2C1;
this.R2C2 = matrix.R2C2;
}
/// <summary>Constructs left matrix with the given values.</summary>
/// <param name="r0c0">The value for row 0 column 0.</param>
/// <param name="r0c1">The value for row 0 column 1.</param>
/// <param name="r0c2">The value for row 0 column 2.</param>
/// <param name="r1c0">The value for row 1 column 0.</param>
/// <param name="r1c1">The value for row 1 column 1.</param>
/// <param name="r1c2">The value for row 1 column 2.</param>
/// <param name="r2c0">The value for row 2 column 0.</param>
/// <param name="r2c1">The value for row 2 column 1.</param>
/// <param name="r2c2">The value for row 2 column 2.</param>
public Matrix3
(
float r0c0,
float r0c1,
float r0c2,
float r1c0,
float r1c1,
float r1c2,
float r2c0,
float r2c1,
float r2c2
)
{
this.R0C0 = r0c0;
this.R0C1 = r0c1;
this.R0C2 = r0c2;
this.R1C0 = r1c0;
this.R1C1 = r1c1;
this.R1C2 = r1c2;
this.R2C0 = r2c0;
this.R2C1 = r2c1;
this.R2C2 = r2c2;
}
/// <summary>Constructs left matrix from the given array of float-precision floating-point numbers.</summary>
/// <param name="floatArray">The array of floats for the components of the matrix.</param>
public Matrix3(float[] floatArray)
{
if (floatArray == null || floatArray.GetLength(0) < 9) throw new InvalidOperationException();
this.R0C0 = floatArray[0];
this.R0C1 = floatArray[1];
this.R0C2 = floatArray[2];
this.R1C0 = floatArray[3];
this.R1C1 = floatArray[4];
this.R1C2 = floatArray[5];
this.R2C0 = floatArray[6];
this.R2C1 = floatArray[7];
this.R2C2 = floatArray[8];
}
#endregion
#region Equality
/// <summary>Indicates whether the current matrix is equal to another matrix.</summary>
/// <param name="matrix">The OpenTK.Matrix3 structure to compare with.</param>
/// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns>
[CLSCompliant(false)]
public bool Equals(Matrix3 matrix)
{
return
R0C0 == matrix.R0C0 &&
R0C1 == matrix.R0C1 &&
R0C2 == matrix.R0C2 &&
R1C0 == matrix.R1C0 &&
R1C1 == matrix.R1C1 &&
R1C2 == matrix.R1C2 &&
R2C0 == matrix.R2C0 &&
R2C1 == matrix.R2C1 &&
R2C2 == matrix.R2C2;
}
/// <summary>Indicates whether the current matrix is equal to another matrix.</summary>
/// <param name="matrix">The OpenTK.Matrix3 structure to compare to.</param>
/// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns>
public bool Equals(ref Matrix3 matrix)
{
return
R0C0 == matrix.R0C0 &&
R0C1 == matrix.R0C1 &&
R0C2 == matrix.R0C2 &&
R1C0 == matrix.R1C0 &&
R1C1 == matrix.R1C1 &&
R1C2 == matrix.R1C2 &&
R2C0 == matrix.R2C0 &&
R2C1 == matrix.R2C1 &&
R2C2 == matrix.R2C2;
}
/// <summary>Indicates whether the current matrix is equal to another matrix.</summary>
/// <param name="left">The left-hand operand.</param>
/// <param name="right">The right-hand operand.</param>
/// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns>
public static bool Equals(ref Matrix3 left, ref Matrix3 right)
{
return
left.R0C0 == right.R0C0 &&
left.R0C1 == right.R0C1 &&
left.R0C2 == right.R0C2 &&
left.R1C0 == right.R1C0 &&
left.R1C1 == right.R1C1 &&
left.R1C2 == right.R1C2 &&
left.R2C0 == right.R2C0 &&
left.R2C1 == right.R2C1 &&
left.R2C2 == right.R2C2;
}
/// <summary>Indicates whether the current matrix is approximately equal to another matrix.</summary>
/// <param name="matrix">The OpenTK.Matrix3 structure to compare with.</param>
/// <param name="tolerance">The limit below which the matrices are considered equal.</param>
/// <returns>true if the current matrix is approximately equal to the matrix parameter; otherwise, false.</returns>
public bool EqualsApprox(ref Matrix3 matrix, float tolerance)
{
return
System.Math.Abs(R0C0 - matrix.R0C0) <= tolerance &&
System.Math.Abs(R0C1 - matrix.R0C1) <= tolerance &&
System.Math.Abs(R0C2 - matrix.R0C2) <= tolerance &&
System.Math.Abs(R1C0 - matrix.R1C0) <= tolerance &&
System.Math.Abs(R1C1 - matrix.R1C1) <= tolerance &&
System.Math.Abs(R1C2 - matrix.R1C2) <= tolerance &&
System.Math.Abs(R2C0 - matrix.R2C0) <= tolerance &&
System.Math.Abs(R2C1 - matrix.R2C1) <= tolerance &&
System.Math.Abs(R2C2 - matrix.R2C2) <= tolerance;
}
/// <summary>Indicates whether the current matrix is approximately equal to another matrix.</summary>
/// <param name="left">The left-hand operand.</param>
/// <param name="right">The right-hand operand.</param>
/// <param name="tolerance">The limit below which the matrices are considered equal.</param>
/// <returns>true if the current matrix is approximately equal to the matrix parameter; otherwise, false.</returns>
public static bool EqualsApprox(ref Matrix3 left, ref Matrix3 right, float tolerance)
{
return
System.Math.Abs(left.R0C0 - right.R0C0) <= tolerance &&
System.Math.Abs(left.R0C1 - right.R0C1) <= tolerance &&
System.Math.Abs(left.R0C2 - right.R0C2) <= tolerance &&
System.Math.Abs(left.R1C0 - right.R1C0) <= tolerance &&
System.Math.Abs(left.R1C1 - right.R1C1) <= tolerance &&
System.Math.Abs(left.R1C2 - right.R1C2) <= tolerance &&
System.Math.Abs(left.R2C0 - right.R2C0) <= tolerance &&
System.Math.Abs(left.R2C1 - right.R2C1) <= tolerance &&
System.Math.Abs(left.R2C2 - right.R2C2) <= tolerance;
}
#endregion
#region Arithmetic Operators
/// <summary>Add left matrix to this matrix.</summary>
/// <param name="matrix">The matrix to add.</param>
public void Add(ref Matrix3 matrix)
{
R0C0 = R0C0 + matrix.R0C0;
R0C1 = R0C1 + matrix.R0C1;
R0C2 = R0C2 + matrix.R0C2;
R1C0 = R1C0 + matrix.R1C0;
R1C1 = R1C1 + matrix.R1C1;
R1C2 = R1C2 + matrix.R1C2;
R2C0 = R2C0 + matrix.R2C0;
R2C1 = R2C1 + matrix.R2C1;
R2C2 = R2C2 + matrix.R2C2;
}
/// <summary>Add left matrix to this matrix.</summary>
/// <param name="matrix">The matrix to add.</param>
/// <param name="result">The resulting matrix of the addition.</param>
public void Add(ref Matrix3 matrix, out Matrix3 result)
{
result.R0C0 = R0C0 + matrix.R0C0;
result.R0C1 = R0C1 + matrix.R0C1;
result.R0C2 = R0C2 + matrix.R0C2;
result.R1C0 = R1C0 + matrix.R1C0;
result.R1C1 = R1C1 + matrix.R1C1;
result.R1C2 = R1C2 + matrix.R1C2;
result.R2C0 = R2C0 + matrix.R2C0;
result.R2C1 = R2C1 + matrix.R2C1;
result.R2C2 = R2C2 + matrix.R2C2;
}
/// <summary>Add left matrix to left matrix.</summary>
/// <param name="matrix">The matrix on the matrix side of the equation.</param>
/// <param name="right">The matrix on the right side of the equation</param>
/// <param name="result">The resulting matrix of the addition.</param>
public static void Add(ref Matrix3 left, ref Matrix3 right, out Matrix3 result)
{
result.R0C0 = left.R0C0 + right.R0C0;
result.R0C1 = left.R0C1 + right.R0C1;
result.R0C2 = left.R0C2 + right.R0C2;
result.R1C0 = left.R1C0 + right.R1C0;
result.R1C1 = left.R1C1 + right.R1C1;
result.R1C2 = left.R1C2 + right.R1C2;
result.R2C0 = left.R2C0 + right.R2C0;
result.R2C1 = left.R2C1 + right.R2C1;
result.R2C2 = left.R2C2 + right.R2C2;
}
/// <summary>Subtract left matrix from this matrix.</summary>
/// <param name="matrix">The matrix to subtract.</param>
public void Subtract(ref Matrix3 matrix)
{
R0C0 = R0C0 + matrix.R0C0;
R0C1 = R0C1 + matrix.R0C1;
R0C2 = R0C2 + matrix.R0C2;
R1C0 = R1C0 + matrix.R1C0;
R1C1 = R1C1 + matrix.R1C1;
R1C2 = R1C2 + matrix.R1C2;
R2C0 = R2C0 + matrix.R2C0;
R2C1 = R2C1 + matrix.R2C1;
R2C2 = R2C2 + matrix.R2C2;
}
/// <summary>Subtract left matrix from this matrix.</summary>
/// <param name="matrix">The matrix to subtract.</param>
/// <param name="result">The resulting matrix of the subtraction.</param>
public void Subtract(ref Matrix3 matrix, out Matrix3 result)
{
result.R0C0 = R0C0 + matrix.R0C0;
result.R0C1 = R0C1 + matrix.R0C1;
result.R0C2 = R0C2 + matrix.R0C2;
result.R1C0 = R1C0 + matrix.R1C0;
result.R1C1 = R1C1 + matrix.R1C1;
result.R1C2 = R1C2 + matrix.R1C2;
result.R2C0 = R2C0 + matrix.R2C0;
result.R2C1 = R2C1 + matrix.R2C1;
result.R2C2 = R2C2 + matrix.R2C2;
}
/// <summary>Subtract left matrix from left matrix.</summary>
/// <param name="matrix">The matrix on the matrix side of the equation.</param>
/// <param name="right">The matrix on the right side of the equation</param>
/// <param name="result">The resulting matrix of the subtraction.</param>
public static void Subtract(ref Matrix3 left, ref Matrix3 right, out Matrix3 result)
{
result.R0C0 = left.R0C0 + right.R0C0;
result.R0C1 = left.R0C1 + right.R0C1;
result.R0C2 = left.R0C2 + right.R0C2;
result.R1C0 = left.R1C0 + right.R1C0;
result.R1C1 = left.R1C1 + right.R1C1;
result.R1C2 = left.R1C2 + right.R1C2;
result.R2C0 = left.R2C0 + right.R2C0;
result.R2C1 = left.R2C1 + right.R2C1;
result.R2C2 = left.R2C2 + right.R2C2;
}
/// <summary>Multiply left martix times this matrix.</summary>
/// <param name="matrix">The matrix to multiply.</param>
public void Multiply(ref Matrix3 matrix)
{
float r0c0 = matrix.R0C0 * R0C0 + matrix.R0C1 * R1C0 + matrix.R0C2 * R2C0;
float r0c1 = matrix.R0C0 * R0C1 + matrix.R0C1 * R1C1 + matrix.R0C2 * R2C1;
float r0c2 = matrix.R0C0 * R0C2 + matrix.R0C1 * R1C2 + matrix.R0C2 * R2C2;
float r1c0 = matrix.R1C0 * R0C0 + matrix.R1C1 * R1C0 + matrix.R1C2 * R2C0;
float r1c1 = matrix.R1C0 * R0C1 + matrix.R1C1 * R1C1 + matrix.R1C2 * R2C1;
float r1c2 = matrix.R1C0 * R0C2 + matrix.R1C1 * R1C2 + matrix.R1C2 * R2C2;
R2C0 = matrix.R2C0 * R0C0 + matrix.R2C1 * R1C0 + matrix.R2C2 * R2C0;
R2C1 = matrix.R2C0 * R0C1 + matrix.R2C1 * R1C1 + matrix.R2C2 * R2C1;
R2C2 = matrix.R2C0 * R0C2 + matrix.R2C1 * R1C2 + matrix.R2C2 * R2C2;
R0C0 = r0c0;
R0C1 = r0c1;
R0C2 = r0c2;
R1C0 = r1c0;
R1C1 = r1c1;
R1C2 = r1c2;
}
/// <summary>Multiply matrix times this matrix.</summary>
/// <param name="matrix">The matrix to multiply.</param>
/// <param name="result">The resulting matrix of the multiplication.</param>
public void Multiply(ref Matrix3 matrix, out Matrix3 result)
{
result.R0C0 = matrix.R0C0 * R0C0 + matrix.R0C1 * R1C0 + matrix.R0C2 * R2C0;
result.R0C1 = matrix.R0C0 * R0C1 + matrix.R0C1 * R1C1 + matrix.R0C2 * R2C1;
result.R0C2 = matrix.R0C0 * R0C2 + matrix.R0C1 * R1C2 + matrix.R0C2 * R2C2;
result.R1C0 = matrix.R1C0 * R0C0 + matrix.R1C1 * R1C0 + matrix.R1C2 * R2C0;
result.R1C1 = matrix.R1C0 * R0C1 + matrix.R1C1 * R1C1 + matrix.R1C2 * R2C1;
result.R1C2 = matrix.R1C0 * R0C2 + matrix.R1C1 * R1C2 + matrix.R1C2 * R2C2;
result.R2C0 = matrix.R2C0 * R0C0 + matrix.R2C1 * R1C0 + matrix.R2C2 * R2C0;
result.R2C1 = matrix.R2C0 * R0C1 + matrix.R2C1 * R1C1 + matrix.R2C2 * R2C1;
result.R2C2 = matrix.R2C0 * R0C2 + matrix.R2C1 * R1C2 + matrix.R2C2 * R2C2;
}
/// <summary>Multiply left matrix times left matrix.</summary>
/// <param name="matrix">The matrix on the matrix side of the equation.</param>
/// <param name="right">The matrix on the right side of the equation</param>
/// <param name="result">The resulting matrix of the multiplication.</param>
public static void Multiply(ref Matrix3 left, ref Matrix3 right, out Matrix3 result)
{
result.R0C0 = right.R0C0 * left.R0C0 + right.R0C1 * left.R1C0 + right.R0C2 * left.R2C0;
result.R0C1 = right.R0C0 * left.R0C1 + right.R0C1 * left.R1C1 + right.R0C2 * left.R2C1;
result.R0C2 = right.R0C0 * left.R0C2 + right.R0C1 * left.R1C2 + right.R0C2 * left.R2C2;
result.R1C0 = right.R1C0 * left.R0C0 + right.R1C1 * left.R1C0 + right.R1C2 * left.R2C0;
result.R1C1 = right.R1C0 * left.R0C1 + right.R1C1 * left.R1C1 + right.R1C2 * left.R2C1;
result.R1C2 = right.R1C0 * left.R0C2 + right.R1C1 * left.R1C2 + right.R1C2 * left.R2C2;
result.R2C0 = right.R2C0 * left.R0C0 + right.R2C1 * left.R1C0 + right.R2C2 * left.R2C0;
result.R2C1 = right.R2C0 * left.R0C1 + right.R2C1 * left.R1C1 + right.R2C2 * left.R2C1;
result.R2C2 = right.R2C0 * left.R0C2 + right.R2C1 * left.R1C2 + right.R2C2 * left.R2C2;
}
/// <summary>Multiply matrix times this matrix.</summary>
/// <param name="matrix">The matrix to multiply.</param>
public void Multiply(float scalar)
{
R0C0 = scalar * R0C0;
R0C1 = scalar * R0C1;
R0C2 = scalar * R0C2;
R1C0 = scalar * R1C0;
R1C1 = scalar * R1C1;
R1C2 = scalar * R1C2;
R2C0 = scalar * R2C0;
R2C1 = scalar * R2C1;
R2C2 = scalar * R2C2;
}
/// <summary>Multiply matrix times this matrix.</summary>
/// <param name="matrix">The matrix to multiply.</param>
/// <param name="result">The resulting matrix of the multiplication.</param>
public void Multiply(float scalar, out Matrix3 result)
{
result.R0C0 = scalar * R0C0;
result.R0C1 = scalar * R0C1;
result.R0C2 = scalar * R0C2;
result.R1C0 = scalar * R1C0;
result.R1C1 = scalar * R1C1;
result.R1C2 = scalar * R1C2;
result.R2C0 = scalar * R2C0;
result.R2C1 = scalar * R2C1;
result.R2C2 = scalar * R2C2;
}
/// <summary>Multiply left matrix times left matrix.</summary>
/// <param name="matrix">The matrix on the matrix side of the equation.</param>
/// <param name="right">The matrix on the right side of the equation</param>
/// <param name="result">The resulting matrix of the multiplication.</param>
public static void Multiply(ref Matrix3 matrix, float scalar, out Matrix3 result)
{
result.R0C0 = scalar * matrix.R0C0;
result.R0C1 = scalar * matrix.R0C1;
result.R0C2 = scalar * matrix.R0C2;
result.R1C0 = scalar * matrix.R1C0;
result.R1C1 = scalar * matrix.R1C1;
result.R1C2 = scalar * matrix.R1C2;
result.R2C0 = scalar * matrix.R2C0;
result.R2C1 = scalar * matrix.R2C1;
result.R2C2 = scalar * matrix.R2C2;
}
#endregion
#region Functions
public float Determinant
{
get
{
return R0C0 * R1C1 * R2C2 - R0C0 * R1C2 * R2C1 - R0C1 * R1C0 * R2C2 + R0C2 * R1C0 * R2C1 + R0C1 * R1C2 * R2C0 - R0C2 * R1C1 * R2C0;
}
}
public void Transpose()
{
MathHelper.Swap(ref R0C1, ref R1C0);
MathHelper.Swap(ref R0C2, ref R2C0);
MathHelper.Swap(ref R1C2, ref R2C1);
}
public void Transpose(out Matrix3 result)
{
result.R0C0 = R0C0;
result.R0C1 = R1C0;
result.R0C2 = R2C0;
result.R1C0 = R0C1;
result.R1C1 = R1C1;
result.R1C2 = R2C1;
result.R2C0 = R0C2;
result.R2C1 = R1C2;
result.R2C2 = R2C2;
}
public static void Transpose(ref Matrix3 matrix, out Matrix3 result)
{
result.R0C0 = matrix.R0C0;
result.R0C1 = matrix.R1C0;
result.R0C2 = matrix.R2C0;
result.R1C0 = matrix.R0C1;
result.R1C1 = matrix.R1C1;
result.R1C2 = matrix.R2C1;
result.R2C0 = matrix.R0C2;
result.R2C1 = matrix.R1C2;
result.R2C2 = matrix.R2C2;
}
#endregion
#region Transformation Functions
public void Transform(ref Vector3 vector)
{
float x = R0C0 * vector.X + R0C1 * vector.Y + R0C2 * vector.Z;
float y = R1C0 * vector.X + R1C1 * vector.Y + R1C2 * vector.Z;
vector.Z = R2C0 * vector.X + R2C1 * vector.Y + R2C2 * vector.Z;
vector.X = x;
vector.Y = y;
}
public static void Transform(ref Matrix3 matrix, ref Vector3 vector)
{
float x = matrix.R0C0 * vector.X + matrix.R0C1 * vector.Y + matrix.R0C2 * vector.Z;
float y = matrix.R1C0 * vector.X + matrix.R1C1 * vector.Y + matrix.R1C2 * vector.Z;
vector.Z = matrix.R2C0 * vector.X + matrix.R2C1 * vector.Y + matrix.R2C2 * vector.Z;
vector.X = x;
vector.Y = y;
}
public void Transform(ref Vector3 vector, out Vector3 result)
{
result.X = R0C0 * vector.X + R0C1 * vector.Y + R0C2 * vector.Z;
result.Y = R1C0 * vector.X + R1C1 * vector.Y + R1C2 * vector.Z;
result.Z = R2C0 * vector.X + R2C1 * vector.Y + R2C2 * vector.Z;
}
public static void Transform(ref Matrix3 matrix, ref Vector3 vector, out Vector3 result)
{
result.X = matrix.R0C0 * vector.X + matrix.R0C1 * vector.Y + matrix.R0C2 * vector.Z;
result.Y = matrix.R1C0 * vector.X + matrix.R1C1 * vector.Y + matrix.R1C2 * vector.Z;
result.Z = matrix.R2C0 * vector.X + matrix.R2C1 * vector.Y + matrix.R2C2 * vector.Z;
}
public void Rotate(float angle)
{
float angleRadians = MathHelper.DegreesToRadians (angle);
float sin = (float)System.Math.Sin(angleRadians);
float cos = (float)System.Math.Cos(angleRadians);
float r0c0 = cos * R0C0 + sin * R1C0;
float r0c1 = cos * R0C1 + sin * R1C1;
float r0c2 = cos * R0C2 + sin * R1C2;
R1C0 = cos * R1C0 - sin * R0C0;
R1C1 = cos * R1C1 - sin * R0C1;
R1C2 = cos * R1C2 - sin * R0C2;
R0C0 = r0c0;
R0C1 = r0c1;
R0C2 = r0c2;
}
public void Rotate(float angle, out Matrix3 result)
{
float angleRadians = MathHelper.DegreesToRadians (angle);
float sin = (float)System.Math.Sin(angleRadians);
float cos = (float)System.Math.Cos(angleRadians);
result.R0C0 = cos * R0C0 + sin * R1C0;
result.R0C1 = cos * R0C1 + sin * R1C1;
result.R0C2 = cos * R0C2 + sin * R1C2;
result.R1C0 = cos * R1C0 - sin * R0C0;
result.R1C1 = cos * R1C1 - sin * R0C1;
result.R1C2 = cos * R1C2 - sin * R0C2;
result.R2C0 = R2C0;
result.R2C1 = R2C1;
result.R2C2 = R2C2;
}
public static void Rotate(ref Matrix3 matrix, float angle, out Matrix3 result)
{
float angleRadians = MathHelper.DegreesToRadians (angle);
float sin = (float)System.Math.Sin(angleRadians);
float cos = (float)System.Math.Cos(angleRadians);
result.R0C0 = cos * matrix.R0C0 + sin * matrix.R1C0;
result.R0C1 = cos * matrix.R0C1 + sin * matrix.R1C1;
result.R0C2 = cos * matrix.R0C2 + sin * matrix.R1C2;
result.R1C0 = cos * matrix.R1C0 - sin * matrix.R0C0;
result.R1C1 = cos * matrix.R1C1 - sin * matrix.R0C1;
result.R1C2 = cos * matrix.R1C2 - sin * matrix.R0C2;
result.R2C0 = matrix.R2C0;
result.R2C1 = matrix.R2C1;
result.R2C2 = matrix.R2C2;
}
public static void RotateMatrix(float angle, out Matrix3 result)
{
float angleRadians = MathHelper.DegreesToRadians(angle);
float sin = (float)System.Math.Sin(angleRadians);
float cos = (float)System.Math.Cos(angleRadians);
result.R0C0 = cos;
result.R0C1 = sin;
result.R0C2 = 0;
result.R1C0 = -sin;
result.R1C1 = cos;
result.R1C2 = 0;
result.R2C0 = 0;
result.R2C1 = 0;
result.R2C2 = 1;
}
public Quaternion ToQuaternion ()
{
return new Quaternion (ref this);
}
#endregion
#region Constants
/// <summary>The identity matrix.</summary>
public static readonly Matrix3 Identity = new Matrix3
(
1, 0, 0,
0, 1, 0,
0, 0, 1
);
/// <summary>A matrix of all zeros.</summary>
public static readonly Matrix3 Zero = new Matrix3
(
0, 0, 0,
0, 0, 0,
0, 0, 0
);
#endregion
#region HashCode
/// <summary>Returns the hash code for this instance.</summary>
/// <returns>A 32-bit signed integer that is the hash code for this instance.</returns>
public override int GetHashCode()
{
return
R0C0.GetHashCode() ^ R0C1.GetHashCode() ^ R0C2.GetHashCode() ^
R1C0.GetHashCode() ^ R1C1.GetHashCode() ^ R1C2.GetHashCode() ^
R2C0.GetHashCode() ^ R2C1.GetHashCode() ^ R2C2.GetHashCode();
}
#endregion
#region String
/// <summary>Returns the fully qualified type name of this instance.</summary>
/// <returns>A System.String containing left fully qualified type name.</returns>
public override string ToString()
{
return String.Format(
"|{00}, {01}, {02}|\n" +
"|{03}, {04}, {05}|\n" +
"|{06}, {07}, {08}|\n",
R0C0, R0C1, R0C2,
R1C0, R1C1, R1C2,
R2C0, R2C1, R2C2);
}
#endregion
}
#pragma warning restore 3019
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using Nirvana.CQRS;
namespace Nirvana.Util.Extensions
{
public static class PropertyInfoExtensions
{
public static string WritePrimitiveType(this PropertyInfo propertyInfo)
{
var type = propertyInfo.PropertyType;
return WritePrimitiveType(type);
}
public static string WritePrimitiveType(this Type type)
{
if (type.IsString())
{
{
return "string";
}
}
if (type.IsType())
{
{
return "any";
}
}
if (type.IsNumber())
{
{
return "number";
}
}
if (type.IsDate())
{
{
return "Date";
}
}
if (IsBoolean(type))
{
{
return "boolean";
}
}
if (type.IsObject())
{
{
return "any";
}
}
if (type.IsObject())
{
{
return "any";
}
}
return string.Empty;
}
public static bool IsPrimitiveType(this PropertyInfo propertyInfo)
{
var propertyType = propertyInfo.PropertyType;
return IsPrimitiveType(propertyType);
}
public static bool IsPrimitiveType(this Type propertyType)
{
return propertyType.IsString()
|| propertyType.IsNumber()
|| IsBoolean(propertyType)
|| propertyType.IsDate()
|| propertyType.IsType()
|| IsObject(propertyType);
}
public static GenericMatch IsEnumType(this PropertyInfo propertyInfo)
{
var propertyType = propertyInfo.PropertyType;
return IsEnumType(propertyType);
}
public static GenericMatch IsEnumType(this Type propertyType)
{
Type[] types;
var isEnumType = propertyType.ClosesOrImplements(typeof(IEnumerable<>), out types);
var isArrayType = propertyType.IsArray;
if (isArrayType)
{
}
return new GenericMatch
{
Matches = isEnumType,
Arguments = types
};
}
public static GenericMatch IsPagedResult(this PropertyInfo propertyInfo)
{
var propertyType = propertyInfo.PropertyType;
return IsPagedResult(propertyType);
}
public static GenericMatch IsPagedResult(this Type propertyType)
{
Type[] types;
var isEnumType = propertyType.ClosesOrImplements(typeof(PagedResult<>), out types);
return new GenericMatch
{
Matches = isEnumType,
Arguments = types
};
}
public static bool IsHiddenProperty(this PropertyInfo propertyInfo)
{
return propertyInfo.Name == "AuthCode";
}
public static bool IsDate(this PropertyInfo prop)
{
var propType = prop.PropertyType;
return IsDate(propType);
}
public static bool IsDate(this Type propType)
{
return propType == typeof(DateTime)
|| propType == typeof(DateTime?);
}
public static bool IsType(this Type propType)
{
return propType == typeof(Type);
}
public static bool IsObject(this Type propType)
{
return propType == typeof(object)
|| propType == typeof(object)
|| propType == typeof(byte);
}
public static bool IsBoolean(this Type propType)
{
return propType == typeof(bool)
|| propType == typeof(bool)
|| propType == typeof(bool?);
}
public static bool IsNumber(this PropertyInfo prop)
{
var propType = prop.PropertyType;
return IsNumber(propType);
}
public static bool IsNumber(this Type propType)
{
return propType == typeof(int)
|| propType == typeof(int?)
|| propType == typeof(short)
|| propType == typeof(short?)
|| propType == typeof(long)
|| propType == typeof(long?)
|| propType == typeof(decimal)
|| propType == typeof(decimal?)
|| propType == typeof(double)
|| propType == typeof(double?)
|| propType == typeof(float)
|| propType == typeof(float?);
}
public static bool IsString(this PropertyInfo prop)
{
var propType = prop.PropertyType;
return IsString(propType);
}
public static bool IsString(this Type propType)
{
return propType == typeof(string)
|| propType == typeof(string)
|| propType == typeof(Guid)
|| propType == typeof(Guid?);
}
public class GenericMatch
{
public bool Matches { get; set; }
public Type[] Arguments { get; set; }
}
}
}
| |
/*
* Velcro Physics:
* Copyright (c) 2017 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using VelcroPhysics.Dynamics.Solver;
using VelcroPhysics.Shared;
using VelcroPhysics.Utilities;
namespace VelcroPhysics.Dynamics.Joints
{
// Pulley:
// length1 = norm(p1 - s1)
// length2 = norm(p2 - s2)
// C0 = (length1 + ratio * length2)_initial
// C = C0 - (length1 + ratio * length2)
// u1 = (p1 - s1) / norm(p1 - s1)
// u2 = (p2 - s2) / norm(p2 - s2)
// Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2))
// J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)]
// K = J * invM * JT
// = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2)
/// <summary>
/// The pulley joint is connected to two bodies and two fixed world points.
/// The pulley supports a ratio such that:
/// <![CDATA[length1 + ratio * length2 <= constant]]>
/// Yes, the force transmitted is scaled by the ratio.
/// Warning: the pulley joint can get a bit squirrelly by itself. They often
/// work better when combined with prismatic joints. You should also cover the
/// the anchor points with static shapes to prevent one side from going to zero length.
/// </summary>
public class PulleyJoint : Joint
{
// Solver shared
private float _impulse;
// Solver temp
private int _indexA;
private int _indexB;
private float _invIA;
private float _invIB;
private float _invMassA;
private float _invMassB;
private Vector2 _localCenterA;
private Vector2 _localCenterB;
private float _mass;
private Vector2 _rA;
private Vector2 _rB;
private Vector2 _uA;
private Vector2 _uB;
internal PulleyJoint()
{
JointType = JointType.Pulley;
}
/// <summary>
/// Constructor for PulleyJoint.
/// </summary>
/// <param name="bodyA">The first body.</param>
/// <param name="bodyB">The second body.</param>
/// <param name="anchorA">The anchor on the first body.</param>
/// <param name="anchorB">The anchor on the second body.</param>
/// <param name="worldAnchorA">The world anchor for the first body.</param>
/// <param name="worldAnchorB">The world anchor for the second body.</param>
/// <param name="ratio">The ratio.</param>
/// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param>
public PulleyJoint(Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, Vector2 worldAnchorA, Vector2 worldAnchorB, float ratio, bool useWorldCoordinates = false)
: base(bodyA, bodyB)
{
JointType = JointType.Pulley;
WorldAnchorA = worldAnchorA;
WorldAnchorB = worldAnchorB;
if (useWorldCoordinates)
{
LocalAnchorA = BodyA.GetLocalPoint(anchorA);
LocalAnchorB = BodyB.GetLocalPoint(anchorB);
Vector2 dA = anchorA - worldAnchorA;
LengthA = dA.Length();
Vector2 dB = anchorB - worldAnchorB;
LengthB = dB.Length();
}
else
{
LocalAnchorA = anchorA;
LocalAnchorB = anchorB;
Vector2 dA = anchorA - BodyA.GetLocalPoint(worldAnchorA);
LengthA = dA.Length();
Vector2 dB = anchorB - BodyB.GetLocalPoint(worldAnchorB);
LengthB = dB.Length();
}
Debug.Assert(ratio != 0.0f);
Debug.Assert(ratio > Settings.Epsilon);
Ratio = ratio;
Constant = LengthA + ratio * LengthB;
_impulse = 0.0f;
}
/// <summary>
/// The local anchor point on BodyA
/// </summary>
public Vector2 LocalAnchorA { get; set; }
/// <summary>
/// The local anchor point on BodyB
/// </summary>
public Vector2 LocalAnchorB { get; set; }
/// <summary>
/// Get the first world anchor.
/// </summary>
/// <value></value>
public sealed override Vector2 WorldAnchorA { get; set; }
/// <summary>
/// Get the second world anchor.
/// </summary>
/// <value></value>
public sealed override Vector2 WorldAnchorB { get; set; }
/// <summary>
/// Get the current length of the segment attached to body1.
/// </summary>
/// <value></value>
public float LengthA { get; set; }
/// <summary>
/// Get the current length of the segment attached to body2.
/// </summary>
/// <value></value>
public float LengthB { get; set; }
/// <summary>
/// The current length between the anchor point on BodyA and WorldAnchorA
/// </summary>
public float CurrentLengthA
{
get
{
Vector2 p = BodyA.GetWorldPoint(LocalAnchorA);
Vector2 s = WorldAnchorA;
Vector2 d = p - s;
return d.Length();
}
}
/// <summary>
/// The current length between the anchor point on BodyB and WorldAnchorB
/// </summary>
public float CurrentLengthB
{
get
{
Vector2 p = BodyB.GetWorldPoint(LocalAnchorB);
Vector2 s = WorldAnchorB;
Vector2 d = p - s;
return d.Length();
}
}
/// <summary>
/// Get the pulley ratio.
/// </summary>
/// <value></value>
public float Ratio { get; set; }
//Velcro note: Only used for serialization.
internal float Constant { get; set; }
public override Vector2 GetReactionForce(float invDt)
{
Vector2 P = _impulse * _uB;
return invDt * P;
}
public override float GetReactionTorque(float invDt)
{
return 0.0f;
}
internal override void InitVelocityConstraints(ref SolverData data)
{
_indexA = BodyA.IslandIndex;
_indexB = BodyB.IslandIndex;
_localCenterA = BodyA._sweep.LocalCenter;
_localCenterB = BodyB._sweep.LocalCenter;
_invMassA = BodyA._invMass;
_invMassB = BodyB._invMass;
_invIA = BodyA._invI;
_invIB = BodyB._invI;
Vector2 cA = data.Positions[_indexA].C;
float aA = data.Positions[_indexA].A;
Vector2 vA = data.Velocities[_indexA].V;
float wA = data.Velocities[_indexA].W;
Vector2 cB = data.Positions[_indexB].C;
float aB = data.Positions[_indexB].A;
Vector2 vB = data.Velocities[_indexB].V;
float wB = data.Velocities[_indexB].W;
Rot qA = new Rot(aA), qB = new Rot(aB);
_rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
_rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
// Get the pulley axes.
_uA = cA + _rA - WorldAnchorA;
_uB = cB + _rB - WorldAnchorB;
float lengthA = _uA.Length();
float lengthB = _uB.Length();
if (lengthA > 10.0f * Settings.LinearSlop)
{
_uA *= 1.0f / lengthA;
}
else
{
_uA = Vector2.Zero;
}
if (lengthB > 10.0f * Settings.LinearSlop)
{
_uB *= 1.0f / lengthB;
}
else
{
_uB = Vector2.Zero;
}
// Compute effective mass.
float ruA = MathUtils.Cross(_rA, _uA);
float ruB = MathUtils.Cross(_rB, _uB);
float mA = _invMassA + _invIA * ruA * ruA;
float mB = _invMassB + _invIB * ruB * ruB;
_mass = mA + Ratio * Ratio * mB;
if (_mass > 0.0f)
{
_mass = 1.0f / _mass;
}
if (Settings.EnableWarmstarting)
{
// Scale impulses to support variable time steps.
_impulse *= data.Step.dtRatio;
// Warm starting.
Vector2 PA = -(_impulse) * _uA;
Vector2 PB = (-Ratio * _impulse) * _uB;
vA += _invMassA * PA;
wA += _invIA * MathUtils.Cross(_rA, PA);
vB += _invMassB * PB;
wB += _invIB * MathUtils.Cross(_rB, PB);
}
else
{
_impulse = 0.0f;
}
data.Velocities[_indexA].V = vA;
data.Velocities[_indexA].W = wA;
data.Velocities[_indexB].V = vB;
data.Velocities[_indexB].W = wB;
}
internal override void SolveVelocityConstraints(ref SolverData data)
{
Vector2 vA = data.Velocities[_indexA].V;
float wA = data.Velocities[_indexA].W;
Vector2 vB = data.Velocities[_indexB].V;
float wB = data.Velocities[_indexB].W;
Vector2 vpA = vA + MathUtils.Cross(wA, _rA);
Vector2 vpB = vB + MathUtils.Cross(wB, _rB);
float Cdot = -Vector2.Dot(_uA, vpA) - Ratio * Vector2.Dot(_uB, vpB);
float impulse = -_mass * Cdot;
_impulse += impulse;
Vector2 PA = -impulse * _uA;
Vector2 PB = -Ratio * impulse * _uB;
vA += _invMassA * PA;
wA += _invIA * MathUtils.Cross(_rA, PA);
vB += _invMassB * PB;
wB += _invIB * MathUtils.Cross(_rB, PB);
data.Velocities[_indexA].V = vA;
data.Velocities[_indexA].W = wA;
data.Velocities[_indexB].V = vB;
data.Velocities[_indexB].W = wB;
}
internal override bool SolvePositionConstraints(ref SolverData data)
{
Vector2 cA = data.Positions[_indexA].C;
float aA = data.Positions[_indexA].A;
Vector2 cB = data.Positions[_indexB].C;
float aB = data.Positions[_indexB].A;
Rot qA = new Rot(aA), qB = new Rot(aB);
Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
// Get the pulley axes.
Vector2 uA = cA + rA - WorldAnchorA;
Vector2 uB = cB + rB - WorldAnchorB;
float lengthA = uA.Length();
float lengthB = uB.Length();
if (lengthA > 10.0f * Settings.LinearSlop)
{
uA *= 1.0f / lengthA;
}
else
{
uA = Vector2.Zero;
}
if (lengthB > 10.0f * Settings.LinearSlop)
{
uB *= 1.0f / lengthB;
}
else
{
uB = Vector2.Zero;
}
// Compute effective mass.
float ruA = MathUtils.Cross(rA, uA);
float ruB = MathUtils.Cross(rB, uB);
float mA = _invMassA + _invIA * ruA * ruA;
float mB = _invMassB + _invIB * ruB * ruB;
float mass = mA + Ratio * Ratio * mB;
if (mass > 0.0f)
{
mass = 1.0f / mass;
}
float C = Constant - lengthA - Ratio * lengthB;
float linearError = Math.Abs(C);
float impulse = -mass * C;
Vector2 PA = -impulse * uA;
Vector2 PB = -Ratio * impulse * uB;
cA += _invMassA * PA;
aA += _invIA * MathUtils.Cross(rA, PA);
cB += _invMassB * PB;
aB += _invIB * MathUtils.Cross(rB, PB);
data.Positions[_indexA].C = cA;
data.Positions[_indexA].A = aA;
data.Positions[_indexB].C = cB;
data.Positions[_indexB].A = aB;
return linearError < Settings.LinearSlop;
}
}
}
| |
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace UMAEditor
{
/// <summary>
/// After removing the UMA.dll from the UMA open source project. Unity3d lost all references to essential scripts such as SlotData.cs, OverlayData.cs ...
/// </summary>
public class FindMissingReferences
{
[MenuItem("UMA/Find Missing References")]
static void Replace()
{
#if UNITY_WEBPLAYER
Debug.LogError("MenuItem - UMA/Find Missing References does not work when the build target is set to Webplayer, we need the full mono framework available.");
#if UMA2_LEAN_AND_CLEAN
Debug.LogError("MenuItem - UMA/Find Missing References does not work with the define UMA2_LEAN_AND_CLEAN, we need all legacy fields available.");
#endif
#else
#if UMA2_LEAN_AND_CLEAN
Debug.LogError("MenuItem - UMA/Find Missing References does not work with the define UMA2_LEAN_AND_CLEAN, we need all legacy fields available.");
#else
List<UnityReference> references = new List<UnityReference>();
var slotFilePaths = new List<string>();
var overlayFilePaths = new List<string>();
references.Add(new UnityReference("e20699a64490c4e4284b27a8aeb05666", "1772484567", FindAssetGuid("OverlayDataAsset", "cs"), "11500000") { updatedFiles = overlayFilePaths }); // OverlayData.cs
references.Add(new UnityReference("e20699a64490c4e4284b27a8aeb05666", "-1278852528", FindAssetGuid("SlotDataAsset", "cs"), "11500000") { updatedFiles = slotFilePaths }); // SlotData.cs
references.Add(new UnityReference("e20699a64490c4e4284b27a8aeb05666", "-335686737", FindAssetGuid("RaceData", "cs"), "11500000")); // RaceData.cs
references.Add(new UnityReference("e20699a64490c4e4284b27a8aeb05666", "-1571472132", FindAssetGuid("UMADefaultMeshCombiner", "cs"), "11500000")); // UMADefaultMeshCombiner.cs
references.Add(new UnityReference("e20699a64490c4e4284b27a8aeb05666", "-1550055707", FindAssetGuid("UMAData", "cs"), "11500000")); // UMAData.cs
references.Add(new UnityReference("e20699a64490c4e4284b27a8aeb05666", "-1708169498", FindAssetGuid("UmaTPose", "cs"), "11500000")); // UmaTPose.cs
references.Add(new UnityReference("e20699a64490c4e4284b27a8aeb05666", "-1175167296", FindAssetGuid("TextureMerge", "cs"), "11500000")); // TextureMerge.cs
references.Add(new UnityReference("7e407fe772026ae4cb2f52b8b5567db5", "11500000", FindAssetGuid("OverlayDataAsset", "cs"), "11500000") { updatedFiles = overlayFilePaths }); // OverlayData.cs
references.Add(new UnityReference("a248d59ac2f3fa14b9c2894f47000560", "11500000", FindAssetGuid("SlotDataAsset", "cs"), "11500000") { updatedFiles = slotFilePaths }); // SlotData.cs
ReplaceReferences(Application.dataPath, references);
if (slotFilePaths.Count > 0 || overlayFilePaths.Count > 0)
{
UMA.UMAMaterial material = AssetDatabase.LoadAssetAtPath("Assets/UMA_Assets/MaterialSamples/DefaultUMAMaterial.asset", typeof(UMA.UMAMaterial)) as UMA.UMAMaterial;
if (material == null) material = AssetDatabase.LoadAssetAtPath("Assets/UMA_Assets/MaterialSamples/UMALegacy.asset", typeof(UMA.UMAMaterial)) as UMA.UMAMaterial;
foreach (var slotFilePath in slotFilePaths)
{
var correctedAssetDatabasePath = "Assets" + slotFilePath.Substring(Application.dataPath.Length);
AssetDatabase.ImportAsset(correctedAssetDatabasePath);
var slotData = AssetDatabase.LoadAssetAtPath(correctedAssetDatabasePath, typeof(UMA.SlotDataAsset)) as UMA.SlotDataAsset;
#pragma warning disable 618
if (slotData.meshRenderer != null)
{
UMASlotProcessingUtil.OptimizeSlotDataMesh(slotData.meshRenderer);
slotData.UpdateMeshData(slotData.meshRenderer);
slotData.material = material;
EditorUtility.SetDirty(slotData);
}
#pragma warning restore 618
}
foreach (var overlayFilePath in overlayFilePaths)
{
var correctedAssetDatabasePath = "Assets" + overlayFilePath.Substring(Application.dataPath.Length);
AssetDatabase.ImportAsset(correctedAssetDatabasePath);
var overlayData = AssetDatabase.LoadAssetAtPath(correctedAssetDatabasePath, typeof(UMA.OverlayDataAsset)) as UMA.OverlayDataAsset;
overlayData.material = material;
EditorUtility.SetDirty(overlayData);
}
}
#endif
#endif
}
static string FindAssetGuid(string assetName, string assetExtension)
{
string fullAssetName = assetName + "." + assetExtension;
string[] guids = AssetDatabase.FindAssets(assetName);
foreach (string guid in guids)
{
string assetPath = AssetDatabase.GUIDToAssetPath(guid);
if (assetPath.EndsWith(fullAssetName))
{
return guid;
}
}
// make sure that we don't continue and break anything!
throw new System.Exception("Unable to find guid for " + fullAssetName);
}
static void ReplaceReferences(string assetFolder, List<UnityReference> r)
{
#if !UNITY_WEBPLAYER
if (EditorSettings.serializationMode != SerializationMode.ForceText)
{
Debug.LogError("Failed to replace refrences, you must set serialzation mode to text. Edit -> Project Settings -> Editor -> Asset Serialziation = Force Text");
return;
}
string[] files = Directory.GetFiles(assetFolder, "*", SearchOption.AllDirectories);
for (int i = 0; i < files.Length; i++)
{
string file = files[i];
if (EditorUtility.DisplayCancelableProgressBar("Update to UMA2", file, i / (float)files.Length))
{
EditorUtility.ClearProgressBar();
return;
}
if (file.EndsWith(".asset") || file.EndsWith(".prefab") || file.EndsWith(".unity"))
{
ReplaceReferencesInFile(file, r);
FindNotReplacedReferences(file, "e20699a64490c4e4284b27a8aeb05666");
}
}
EditorUtility.ClearProgressBar();
#endif
}
static bool IsValidHexString(IEnumerable<char> chars)
{
bool isHex;
foreach(var c in chars)
{
isHex = ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F'));
if(!isHex)
return false;
}
return true;
}
static bool IsHexJunk(string junk)
{
if ((junk.Length % 2) == 1)
{
// can't be an odd number of characters...
return false;
}
if (IsValidHexString(junk))
{
return true;
}
return false;
}
static string HexToString(string hexstr)
{
var sb = new System.Text.StringBuilder(hexstr.Length/2);
for (int i=0;i<hexstr.Length;i+=2)
{
string hex = hexstr.Substring(i,2);
int value = System.Convert.ToInt32(hex, 16);
sb.Append(System.Char.ConvertFromUtf32(value));
}
return sb.ToString();
}
static void ReplaceReferencesInFile(string filePath, List<UnityReference> references)
{
var fileContents = UMA.FileUtils.ReadAllText(filePath);
bool match = false;
foreach (UnityReference r in references)
{
Regex regex = new Regex(@"fileID: " + r.srcFileId + ", guid: " + r.srcGuid);
if (regex.IsMatch(fileContents))
{
if (r.updatedFiles != null)
{
r.updatedFiles.Add(filePath);
}
fileContents = regex.Replace(fileContents, "fileID: " + r.dstFileId + ", guid: " + r.dstGuid);
match = true;
Debug.Log("Replaced: " + filePath);
}
}
// fix name if it's slotdata or overlaydata
if (match) {
string[] lines = fileContents.Split ('\n');
foreach (string line in lines) {
string[] l = line.Trim ('\r', '\n', ' ').Split (':');
if (l.Length > 1) {
if (l [0].StartsWith ("overlayName") || l [0].StartsWith ("slotName")) {
// is it hex junk?
string HexJunk = l [1].Trim ();
if (IsHexJunk (HexJunk)) {
string NewJunk = HexToString(HexJunk);
fileContents = fileContents.Replace(HexJunk,NewJunk);
}
}
}
}
}
if (match)
{
UMA.FileUtils.WriteAllText(filePath, fileContents);
}
}
/// <summary>
/// Just to make sure that all references are replaced.
/// </summary>
static void FindNotReplacedReferences(string filePath, string guid)
{
var fileContents = UMA.FileUtils.ReadAllText(filePath);
// -? number can be negative
// [0-9]+ 1-n numbers
Regex.Replace(fileContents, @"fileID: -?[0-9]+, guid: " + guid,
(match) =>
{
//if (match.Value != "fileID: 11500000, guid: " + guid)
//{
// Debug.LogWarning("NotReplaced: " + match.Value + " " + filePath);
//}
Debug.LogWarning("NotReplaced: " + match.Value + " " + filePath);
return match.Value;
});
}
public class UnityReference
{
public UnityReference(string srcGuid, string srcFileId, string dstGuid, string dstFileId)
{
this.srcGuid = srcGuid;
this.srcFileId = srcFileId;
this.dstGuid = dstGuid;
this.dstFileId = dstFileId;
}
public List<string> updatedFiles;
public string srcGuid;
public string srcFileId;
public string dstGuid;
public string dstFileId;
}
}
}
#endif
| |
//-----------------------------------------------------------------------------
// Map.cs
//
// Spooker Open Source Game Framework
// Copyright (C) Indie Armory. All rights reserved.
// Website: http://indiearmory.com
// Other Contributors: None
// License: MIT
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using TiledSharp;
using FarseerPhysics;
using FarseerPhysics.Common;
using FarseerPhysics.Common.Decomposition;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using Spooker.Time;
namespace Spooker.Graphics.TiledMap
{
////////////////////////////////////////////////////////////
/// <summary>
/// Human-understandable implementation of maps loaded with
/// TiledSharp.
/// </summary>
////////////////////////////////////////////////////////////
public class Map : IDrawable, IUpdateable
{
/// <summary>Handles collisions of this map.</summary>
public World Physics;
/// <summary>Layers of this map.</summary>
public List<Layer> Layers;
/// <summary>Width of map (in tiles).</summary>
public int Width;
/// <summary>Height of map (in tiles).</summary>
public int Height;
/// <summary>Width and height of one tile (in pixels)</summary>
public Vector2 TileSize;
/// <summary>List of all objects in this map</summary>
public List<Object> Objects;
/// <summary>Properties of this map</summary>
public Dictionary<string, string> Properties;
/// <summary>
/// Gets the bounds of this map (in pixels).
/// </summary>
/// <value>The bounds.</value>
public Rectangle Bounds
{
get { return new Rectangle (0, 0, Width * (int)TileSize.X, Height * (int)TileSize.Y); }
}
/// <summary>
/// Initializes a new instance of the <see cref="Spooker.Graphics.TiledMap.Map"/> class.
/// </summary>
/// <param name="filename">Filename.</param>
public Map(string filename)
{
var map = new TmxMap(filename);
Properties = map.Properties;
Width = map.Width;
Height = map.Height;
TileSize = new Vector2 (map.TileWidth, map.TileHeight);
// Initialize grid dictionary
var gidDict = ConvertGidDict (map.Tilesets);
// Load layers
Layers = new List<Layer>();
foreach (var layer in map.Layers)
Layers.Add(new Layer(layer, TileSize, gidDict));
// Load physics
ConvertUnits.SetDisplayUnitToSimUnitRatio (64f);
Physics = new World (Microsoft.Xna.Framework.Vector2.Zero); // No gravity
BodyFactory.CreateEdge (Physics,
ConvertUnits.ToSimUnits (Microsoft.Xna.Framework.Vector2.Zero),
ConvertUnits.ToSimUnits (new Microsoft.Xna.Framework.Vector2 (0, Bounds.Height)));
BodyFactory.CreateEdge (Physics,
ConvertUnits.ToSimUnits (Microsoft.Xna.Framework.Vector2.Zero),
ConvertUnits.ToSimUnits (new Microsoft.Xna.Framework.Vector2 (Bounds.Width, 0)));
BodyFactory.CreateEdge (Physics,
ConvertUnits.ToSimUnits (new Microsoft.Xna.Framework.Vector2 (0, Bounds.Height)),
ConvertUnits.ToSimUnits (new Microsoft.Xna.Framework.Vector2 (Bounds.Width, Bounds.Height)));
BodyFactory.CreateEdge (Physics,
ConvertUnits.ToSimUnits (new Microsoft.Xna.Framework.Vector2 (Bounds.Width, 0)),
ConvertUnits.ToSimUnits (new Microsoft.Xna.Framework.Vector2 (Bounds.Width, Bounds.Height)));
Objects = ConvertObjects(map.ObjectGroups, gidDict);
}
/// <summary>
/// Component uses this for drawing itself
/// </summary>
/// <param name="spriteBatch">Sprite batch.</param>
/// <param name="effects">Effects.</param>
public void Draw(SpriteBatch spriteBatch, SpriteEffects effects)
{
foreach (var layer in Layers)
layer.Draw(spriteBatch, effects);
}
/// <summary>
/// Draw the layer specified by its name.
/// </summary>
/// <param name="spriteBatch">Sprite batch.</param>
/// <param name="name">Name.</param>
/// <param name="effects">Effects.</param>
public void Draw(string name, SpriteBatch spriteBatch, SpriteEffects effects)
{
Layers.Find(l=> l.Name == name).Draw (spriteBatch, effects);
}
/// <summary>
/// Draw the layer specified by its index.
/// </summary>
/// <param name="spriteBatch">Sprite batch.</param>
/// <param name="index">Index.</param>
/// <param name="effects">Effects.</param>
public void Draw(int index, SpriteBatch spriteBatch, SpriteEffects effects)
{
Layers[index].Draw (spriteBatch, effects);
}
/// <summary>
/// Component uses this for updating itself.
/// </summary>
/// <param name="gameTime">Provides snapshot of timing values.</param>
public void Update(GameTime gameTime)
{
Physics.Step ((float)gameTime.ElapsedGameTime.Seconds);
foreach (var o in Objects)
o.Update (gameTime);
}
private Dictionary<int, KeyValuePair<Rectangle, Texture>> ConvertGidDict(IEnumerable<TmxTileset> tilesets)
{
var gidDict = new Dictionary<int, KeyValuePair<Rectangle, Texture>>();
foreach (var ts in tilesets)
{
var sheet = new Texture(ts.Image.Source);
// Loop hoisting
var wStart = ts.Margin;
var wInc = ts.TileWidth + ts.Spacing;
var wEnd = ts.Image.Width;
var hStart = ts.Margin;
var hInc = ts.TileHeight + ts.Spacing;
var hEnd = ts.Image.Height;
// Pre-compute tileset rectangles
var id = ts.FirstGid;
for (var h = hStart; h < hEnd; h += hInc)
{
for (var w = wStart; w < wEnd; w += wInc)
{
var rect = new Rectangle(w, h, ts.TileWidth, ts.TileHeight);
gidDict.Add(id, new KeyValuePair<Rectangle, Texture>(rect, sheet));
id += 1;
}
}
}
return gidDict;
}
private List<Object> ConvertObjects(IEnumerable<TmxObjectGroup> objectGroups, Dictionary<int, KeyValuePair<Rectangle, Texture>> gidDict)
{
var objList = new List<Object>();
foreach (var objectGroup in objectGroups)
{
foreach (var o in objectGroup.Objects)
{
var obj = new Object
{
Name = o.Name,
Type = o.Type,
Position = new Vector2(o.X, o.Y),
Size = new Vector2(o.Width, o.Height),
Properties = o.Properties
};
if (o.Points != null)
foreach (var p in o.Points)
obj.Points.Add (new Point (p.Item1, p.Item2));
if (o.ObjectType == TmxObjectGroup.TmxObjectType.Basic ||
o.ObjectType == TmxObjectGroup.TmxObjectType.Tile)
{
if (obj.Size.X == 0 || obj.Size.Y == 0) continue;
obj.Shape = BodyFactory.CreateRectangle (Physics,
ConvertUnits.ToSimUnits(obj.Size.X),
ConvertUnits.ToSimUnits(obj.Size.Y), 1f);
obj.Position += obj.Size / 2;
if (o.ObjectType == TmxObjectGroup.TmxObjectType.Tile) {
obj.Position.Y -= o.Height;
obj.Shape.UserData = new Sprite (gidDict [o.Tile.Gid].Value) {
Position = obj.Position,
SourceRect = gidDict [o.Tile.Gid].Key,
Origin = obj.Size /2
};
obj.ObjectType = ObjectType.Graphic;
} else
obj.ObjectType = ObjectType.Rectangle;
}
if (o.ObjectType == TmxObjectGroup.TmxObjectType.Ellipse)
{
obj.Shape = BodyFactory.CreateEllipse (Physics,
ConvertUnits.ToSimUnits (obj.Size.X / 2),
ConvertUnits.ToSimUnits (obj.Size.Y / 2),
0, 1f);
obj.ObjectType = ObjectType.Ellipse;
}
if (o.ObjectType == TmxObjectGroup.TmxObjectType.Polyline ||
o.ObjectType == TmxObjectGroup.TmxObjectType.Polygon)
{
var vert = new Vertices ();
vert.AddRange(o.Points.Select(point => new Microsoft.Xna.Framework.Vector2(ConvertUnits.ToSimUnits(point.Item1), ConvertUnits.ToSimUnits(point.Item2))));
if (o.ObjectType == TmxObjectGroup.TmxObjectType.Polyline) {
obj.ObjectType = ObjectType.Polyline;
obj.Shape = BodyFactory.CreateChainShape (Physics, vert);
} else {
obj.ObjectType = ObjectType.Polygon;
var verts = Triangulate.ConvexPartition (vert, TriangulationAlgorithm.Bayazit);
obj.Shape = BodyFactory.CreateCompoundPolygon (Physics, verts, 1f);
}
}
obj.Shape.Position = new Microsoft.Xna.Framework.Vector2 (
ConvertUnits.ToSimUnits(obj.Position.X),
ConvertUnits.ToSimUnits(obj.Position.Y));
if (objectGroup.Name.Contains("Dynamic")) {
obj.Shape.BodyType = BodyType.Dynamic;
obj.Shape.IsStatic = false;
obj.Shape.LinearDamping = 1f;
} else {
obj.Shape.BodyType = BodyType.Static;
obj.Shape.IsStatic = true;
}
objList.Add (obj);
}
}
return objList;
}
}
}
| |
namespace Microsoft.Azure.Management.Blueprint
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for PublishedBlueprintsOperations.
/// </summary>
public static partial class SubscriptionPublishedBlueprintsExtensions
{
/// <summary>
/// Publish a new version of the Blueprint with the latest artifacts. Published
/// Blueprints are immutable.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// azure subscriptionId, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
public static PublishedBlueprint CreateInSubscription(this IPublishedBlueprintsOperations operations, string subscriptionId, string blueprintName, string versionId)
{
var scope = string.Format(Constants.ResourceScopes.SubscriptionScope, subscriptionId);
return operations.CreateAsync(scope, blueprintName, versionId).GetAwaiter().GetResult();
}
/// <summary>
/// Publish a new version of the Blueprint with the latest artifacts. Published
/// Blueprints are immutable.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// azure subscriptionId, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublishedBlueprint> CreateInSubscriptionAsync(this IPublishedBlueprintsOperations operations, string subscriptionId, string blueprintName, string versionId, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.SubscriptionScope, subscriptionId);
using (var _result = await operations.CreateWithHttpMessagesAsync(scope, blueprintName, versionId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a published Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// azure subscriptionId, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
public static PublishedBlueprint GetInSubscription(this IPublishedBlueprintsOperations operations, string subscriptionId, string blueprintName, string versionId)
{
var scope = string.Format(Constants.ResourceScopes.SubscriptionScope, subscriptionId);
return operations.GetAsync(scope, blueprintName, versionId).GetAwaiter().GetResult();
}
/// <summary>
/// Get a published Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// azure subscriptionId, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublishedBlueprint> GetInSubscriptionAsync(this IPublishedBlueprintsOperations operations, string subscriptionId, string blueprintName, string versionId, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.SubscriptionScope, subscriptionId);
using (var _result = await operations.GetWithHttpMessagesAsync(scope, blueprintName, versionId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete a published Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// azure subscriptionId, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
public static PublishedBlueprint DeleteInSubscription(this IPublishedBlueprintsOperations operations, string subscriptionId, string blueprintName, string versionId)
{
var scope = string.Format(Constants.ResourceScopes.SubscriptionScope, subscriptionId);
return operations.DeleteAsync(scope, blueprintName, versionId).GetAwaiter().GetResult();
}
/// <summary>
/// Delete a published Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// azure subscriptionId, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='versionId'>
/// version of the published blueprint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PublishedBlueprint> DeleteInSubscriptionAsync(this IPublishedBlueprintsOperations operations, string subscriptionId, string blueprintName, string versionId, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.SubscriptionScope, subscriptionId);
using (var _result = await operations.DeleteWithHttpMessagesAsync(scope, blueprintName, versionId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List published versions of given Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// azure subscriptionId, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
public static IPage<PublishedBlueprint> ListInSubscription(this IPublishedBlueprintsOperations operations, string subscriptionId, string blueprintName)
{
var scope = string.Format(Constants.ResourceScopes.SubscriptionScope, subscriptionId);
return operations.ListAsync(scope, blueprintName).GetAwaiter().GetResult();
}
/// <summary>
/// List published versions of given Blueprint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// azure subscriptionId, which we save the blueprint to.
/// </param>
/// <param name='blueprintName'>
/// name of the blueprint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PublishedBlueprint>> ListInSubscriptionAsync(this IPublishedBlueprintsOperations operations, string subscriptionId, string blueprintName, CancellationToken cancellationToken = default(CancellationToken))
{
var scope = string.Format(Constants.ResourceScopes.SubscriptionScope, subscriptionId);
using (var _result = await operations.ListWithHttpMessagesAsync(scope, blueprintName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//
// Copyright (C) 2010 The Sanity Engine Development Team
//
// This source code is licensed under the terms of the
// MIT License.
//
// For more information, see the file LICENSE
using System;
using System.Collections.Generic;
namespace SanityEngine.DecisionMaking.FSM
{
public delegate bool Guard();
/// <summary>
/// A finite state machine.
/// </summary>
/// <typeparam name="TData">The data type used for transition guard checks.</typeparam>
public class FiniteStateMachine
{
Dictionary<string, State> states = new Dictionary<string, State>();
State startState;
State currentState;
int nextEvent = 0;
Dictionary<string, FSMEvent> registeredEvents = new Dictionary<string, FSMEvent>();
/// <summary>
/// The current state.
/// </summary>
public State CurrentState
{
get { return currentState; }
}
/// <summary>
/// Create a finite state machine.
/// </summary>
/// <param name="data">The data used for predicate guard checks</param>
public FiniteStateMachine ()
{
}
public FSMEvent RegisterEvent(string name)
{
if(registeredEvents.ContainsKey(name)) {
throw new ArgumentException("Event '" + name + "' already registered");
}
FSMEvent newEvent = new FSMEvent(nextEvent ++, name);
registeredEvents[name] = newEvent;
return newEvent;
}
/// <summary>
/// Add a state.
/// </summary>
/// <param name="name">The name of the state</param>
/// <param name="startState"><code>true</code> if this state is the start state</param>
public void AddState(string name, bool startState)
{
AddState(name, startState, null, null, null);
}
/// <summary>
/// Add a state.
/// </summary>
/// <param name="name">The name of the state</param>
/// <param name="startState"><code>true</code> if this state is the start state</param>
/// <param name="tickAction">An action called when the state is ticked</param>
/// <param name="enterAction">An action called when entering the state</param>
/// <param name="exitAction">An action called when exiting the state</param>
public void AddState(string name, bool startState, Action tickAction, Action enterAction, Action exitAction)
{
State newState = new State(name, tickAction, enterAction, exitAction);
states.Add(name, newState);
if(startState) {
if(this.startState != null) {
throw new ArgumentException("Start state already set!");
}
this.startState = newState;
}
}
/// <summary>
/// Add a transition.
/// </summary>
/// <param name="source">The source state name.</param>
/// <param name="target">The target state name.</param>
/// <param name="eventName">The event name that triggers this transition.</param>
public void AddTransition(string source, string target, FSMEvent trigger)
{
AddTransition(source, target, trigger, null, null);
}
/// <summary>
/// Add a transition.
/// </summary>
/// <param name="source">The source state name.</param>
/// <param name="target">The target state name.</param>
/// <param name="eventName">The event name that triggers this transition.</param>
/// <param name="guard">The guard predicate for this transition.</param>
public void AddTransition(string source, string target, FSMEvent trigger,
Guard guard)
{
AddTransition(source, target, trigger, guard, null);
}
/// <summary>
/// Add a transition.
/// </summary>
/// <param name="source">The source state name.</param>
/// <param name="target">The target state name.</param>
/// <param name="eventName">The event name that triggers this transition.</param>
/// <param name="action">An action callback to be called if this transition is triggered.</param>
public void AddTransition(string source, string target, FSMEvent trigger,
Action action)
{
AddTransition(source, target, trigger, null, action);
}
/// <summary>
/// Add a transition.
/// </summary>
/// <param name="source">The source state name.</param>
/// <param name="target">The target state name.</param>
/// <param name="eventName">The event name that triggers this transition.</param>
/// <param name="predicate">The guard predicate for this transition.</param>
/// <param name="action">An action callback to be called if this transition is triggered.</param>
public void AddTransition(string source, string target, FSMEvent trigger,
Guard guard, Action action)
{
if(!states.ContainsKey(source)) {
throw new ArgumentException("No such source state found");
}
if(!states.ContainsKey(target)) {
throw new ArgumentException("No such target state found");
}
states[source].AddTransition(new Transition(trigger,
states[target], guard, action));
}
/// <summary>
/// Enters the start state.
/// </summary>
public void Start()
{
if(startState == null) {
throw new InvalidOperationException("No start state set!");
}
if(currentState != null) {
throw new InvalidOperationException("FSM already in a state");
}
startState.FireEnterAction();
currentState = startState;
}
/// <summary>
/// Reset this FSM to the start state.
/// </summary>
public void Reset()
{
if(currentState != null) {
currentState.FireExitAction();
currentState = null;
}
Start();
}
/// <summary>
/// Tick the current state's update action (if any).
/// </summary>
public void Tick()
{
if(currentState == null) {
throw new InvalidOperationException("No current state (you may need to call Start)");
}
currentState.Tick();
}
/// <summary>
/// Trigger an event. If a transition exists for this event name in
/// the current state, the state will change to the transition's
/// target state.
/// </summary>
/// <param name="eventName">The event name.</param>
public void TriggerEvent(FSMEvent evt)
{
if(currentState == null) {
throw new InvalidOperationException("No current state (you may need to call Start)");
}
if(!registeredEvents.ContainsKey(evt.Name)) {
throw new InvalidOperationException("Event is not registered");
}
State newState = currentState.TriggerEvent(evt);
if(newState != null) {
currentState = newState;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Spatial.Prefix.Tree;
using Lucene.Net.Spatial.Util;
using Lucene.Net.Util;
using Spatial4n.Core.Shapes;
namespace Lucene.Net.Spatial.Prefix
{
/// <summary>
/// Traverses a
/// <see cref="Lucene.Net.Spatial.Prefix.Tree.SpatialPrefixTree">Lucene.Net.Spatial.Prefix.Tree.SpatialPrefixTree
/// </see>
/// indexed field, using the template &
/// visitor design patterns for subclasses to guide the traversal and collect
/// matching documents.
/// <p/>
/// Subclasses implement
/// <see cref="Lucene.Net.Search.Filter.GetDocIdSet(AtomicReaderContext, Bits)
/// ">Lucene.Search.Filter.GetDocIdSet(AtomicReaderContext, Bits)
/// </see>
/// by instantiating a custom
/// <see cref="VisitorTemplate">VisitorTemplate</see>
/// subclass (i.e. an anonymous inner class) and implement the
/// required methods.
/// </summary>
/// <lucene.internal></lucene.internal>
public abstract class AbstractVisitingPrefixTreeFilter : AbstractPrefixTreeFilter
{
protected internal readonly int prefixGridScanLevel;
public AbstractVisitingPrefixTreeFilter(Shape queryShape
, string fieldName, SpatialPrefixTree grid, int detailLevel,
int prefixGridScanLevel
)
: base(queryShape, fieldName, grid, detailLevel)
{
//Historical note: this code resulted from a refactoring of RecursivePrefixTreeFilter,
// which in turn came out of SOLR-2155
//at least one less than grid.getMaxLevels()
this.prefixGridScanLevel = Math.Max(0, Math.Min(prefixGridScanLevel, grid.MaxLevels - 1));
Debug.Assert(detailLevel <= grid.MaxLevels);
}
public override bool Equals(object o)
{
if (!base.Equals(o))
{
return false;
}
//checks getClass == o.getClass & instanceof
var that = (AbstractVisitingPrefixTreeFilter)o;
if (prefixGridScanLevel != that.prefixGridScanLevel)
{
return false;
}
return true;
}
public override int GetHashCode()
{
int result = base.GetHashCode();
result = 31 * result + prefixGridScanLevel;
return result;
}
#region Nested type: VNode
/// <summary>
/// A Visitor Cell/Cell found via the query shape for
/// <see cref="VisitorTemplate">VisitorTemplate</see>
/// .
/// Sometimes these are reset(cell). It's like a LinkedList node but forms a
/// tree.
/// </summary>
/// <lucene.internal></lucene.internal>
public class VNode
{
internal readonly VNode parent;
internal Cell cell;
internal IEnumerator<VNode> children;
/// <summary>call reset(cell) after to set the cell.</summary>
/// <remarks>call reset(cell) after to set the cell.</remarks>
internal VNode(VNode parent)
{
//Note: The VNode tree adds more code to debug/maintain v.s. a flattened
// LinkedList that we used to have. There is more opportunity here for
// custom behavior (see preSiblings & postSiblings) but that's not
// leveraged yet. Maybe this is slightly more GC friendly.
//only null at the root
//null, then sometimes set, then null
//not null (except initially before reset())
// remember to call reset(cell) after
this.parent = parent;
}
internal virtual void Reset(Cell cell)
{
Debug.Assert(cell != null);
this.cell = cell;
Debug.Assert(children == null);
}
}
#endregion
#region Nested type: VisitorTemplate
/// <summary>
/// An abstract class designed to make it easy to implement predicates or
/// other operations on a
/// <see cref="Lucene.Net.Spatial.Prefix.Tree.SpatialPrefixTree">Lucene.Net.Spatial.Prefix.Tree.SpatialPrefixTree
/// </see>
/// indexed field. An instance
/// of this class is not designed to be re-used across AtomicReaderContext
/// instances so simply create a new one for each call to, say a
/// <see cref="Lucene.Net.Search.Filter.GetDocIdSet(Lucene.Net.Index.AtomicReaderContext, Lucene.Net.Util.Bits)
/// ">Lucene.Net.Search.Filter.GetDocIdSet(Lucene.Net.Index.AtomicReaderContext, Lucene.Net.Util.Bits)
/// </see>
/// .
/// The
/// <see cref="GetDocIdSet()">GetDocIdSet()</see>
/// method here starts the work. It first checks
/// that there are indexed terms; if not it quickly returns null. Then it calls
/// <see cref="Start()">Start()</see>
/// so a subclass can set up a return value, like an
/// <see cref="Lucene.Net.Util.OpenBitSet">Lucene.Net.Util.OpenBitSet</see>
/// . Then it starts the traversal
/// process, calling
/// <see cref="FindSubCellsToVisit(Lucene.Net.Spatial.Prefix.Tree.Cell)">FindSubCellsToVisit(Lucene.Net.Spatial.Prefix.Tree.Cell)
/// </see>
/// which by default finds the top cells that intersect
/// <code>queryShape</code>
/// . If
/// there isn't an indexed cell for a corresponding cell returned for this
/// method then it's short-circuited until it finds one, at which point
/// <see cref="Visit(Lucene.Net.Spatial.Prefix.Tree.Cell)">Visit(Lucene.Net.Spatial.Prefix.Tree.Cell)
/// </see>
/// is called. At
/// some depths, of the tree, the algorithm switches to a scanning mode that
/// finds calls
/// <see cref="VisitScanned(Lucene.Net.Spatial.Prefix.Tree.Cell)">VisitScanned(Lucene.Net.Spatial.Prefix.Tree.Cell)
/// </see>
/// for each leaf cell found.
/// </summary>
/// <lucene.internal></lucene.internal>
public abstract class VisitorTemplate : BaseTermsEnumTraverser
{
private readonly AbstractVisitingPrefixTreeFilter _enclosing;
private readonly BytesRef curVNodeTerm = new BytesRef();
protected internal readonly bool hasIndexedLeaves;
private VNode curVNode;
private Cell scanCell;
private BytesRef thisTerm;
/// <exception cref="System.IO.IOException"></exception>
public VisitorTemplate(AbstractVisitingPrefixTreeFilter _enclosing, AtomicReaderContext
context, IBits acceptDocs,
bool hasIndexedLeaves)
: base(_enclosing, context, acceptDocs)
{
this._enclosing = _enclosing;
//if false then we can skip looking for them
//current pointer, derived from query shape
//curVNode.cell's term.
//the result of termsEnum.term()
this.hasIndexedLeaves = hasIndexedLeaves;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual DocIdSet GetDocIdSet()
{
Debug.Assert(curVNode == null, "Called more than once?");
if (termsEnum == null)
{
return null;
}
//advance
if ((thisTerm = termsEnum.Next()) == null)
{
return null;
}
// all done
curVNode = new VNode(null);
curVNode.Reset(_enclosing.grid.WorldCell);
Start();
AddIntersectingChildren();
while (thisTerm != null)
{
//terminates for other reasons too!
//Advance curVNode pointer
if (curVNode.children != null)
{
//-- HAVE CHILDREN: DESCEND
Debug.Assert(curVNode.children.MoveNext());
//if we put it there then it has something
PreSiblings(curVNode);
curVNode = curVNode.children.Current;
}
else
{
//-- NO CHILDREN: ADVANCE TO NEXT SIBLING
VNode parentVNode = curVNode.parent;
while (true)
{
if (parentVNode == null)
{
goto main_break;
}
// all done
if (parentVNode.children.MoveNext())
{
//advance next sibling
curVNode = parentVNode.children.Current;
break;
}
else
{
//reached end of siblings; pop up
PostSiblings(parentVNode);
parentVNode.children = null;
//GC
parentVNode = parentVNode.parent;
}
}
}
//Seek to curVNode's cell (or skip if termsEnum has moved beyond)
curVNodeTerm.bytes = curVNode.cell.GetTokenBytes().ToSByteArray();
curVNodeTerm.length = curVNodeTerm.bytes.Length;
int compare = termsEnum.Comparator.Compare(thisTerm, curVNodeTerm
);
if (compare > 0)
{
// leap frog (termsEnum is beyond where we would otherwise seek)
Debug.Assert(
!((AtomicReader)context.Reader).Terms(_enclosing.fieldName).Iterator(null).SeekExact(
curVNodeTerm, false), "should be absent"
);
}
else
{
if (compare < 0)
{
// Seek !
TermsEnum.SeekStatus seekStatus = termsEnum.SeekCeil(curVNodeTerm, true
);
if (seekStatus == TermsEnum.SeekStatus.END)
{
break;
}
// all done
thisTerm = termsEnum.Term;
if (seekStatus == TermsEnum.SeekStatus.NOT_FOUND)
{
continue;
}
}
// leap frog
// Visit!
bool descend = Visit(curVNode.cell);
//advance
if ((thisTerm = termsEnum.Next()) == null)
{
break;
}
// all done
if (descend)
{
AddIntersectingChildren();
}
}
;
}
main_break:
;
//main loop
return Finish();
}
/// <summary>
/// Called initially, and whenever
/// <see cref="Visit(Lucene.Net.Spatial.Prefix.Tree.Cell)">Visit(Lucene.Net.Spatial.Prefix.Tree.Cell)
/// </see>
/// returns true.
/// </summary>
/// <exception cref="System.IO.IOException"></exception>
private void AddIntersectingChildren()
{
Debug.Assert(thisTerm != null);
Cell cell = curVNode.cell;
if (cell.Level >= _enclosing.detailLevel)
{
throw new InvalidOperationException("Spatial logic error");
}
//Check for adjacent leaf (happens for indexed non-point shapes)
if (hasIndexedLeaves && cell.Level != 0)
{
//If the next indexed term just adds a leaf marker ('+') to cell,
// then add all of those docs
Debug.Assert(StringHelper.StartsWith(thisTerm, curVNodeTerm
));
scanCell = _enclosing.grid.GetCell(thisTerm.bytes.ToByteArray(), thisTerm.offset
, thisTerm.length, scanCell);
if (scanCell.Level == cell.Level && scanCell.IsLeaf())
{
VisitLeaf(scanCell);
//advance
if ((thisTerm = termsEnum.Next()) == null)
{
return;
}
}
}
// all done
//Decide whether to continue to divide & conquer, or whether it's time to
// scan through terms beneath this cell.
// Scanning is a performance optimization trade-off.
//TODO use termsEnum.docFreq() as heuristic
bool scan = cell.Level >= _enclosing.prefixGridScanLevel;
//simple heuristic
if (!scan)
{
//Divide & conquer (ultimately termsEnum.seek())
IEnumerator<Cell> subCellsIter = FindSubCellsToVisit(cell);
if (!subCellsIter.MoveNext())
{
//not expected
return;
}
curVNode.children = new VNodeCellIterator
(this, subCellsIter, new VNode(curVNode));
}
else
{
//Scan (loop of termsEnum.next())
Scan(_enclosing.detailLevel);
}
}
/// <summary>
/// Called when doing a divide & conquer to find the next intersecting cells
/// of the query shape that are beneath
/// <code>cell</code>
/// .
/// <code>cell</code>
/// is
/// guaranteed to have an intersection and thus this must return some number
/// of nodes.
/// </summary>
protected internal virtual IEnumerator<Cell> FindSubCellsToVisit(Cell cell)
{
return cell.GetSubCells(_enclosing.queryShape).GetEnumerator();
}
/// <summary>
/// Scans (
/// <code>termsEnum.next()</code>
/// ) terms until a term is found that does
/// not start with curVNode's cell. If it finds a leaf cell or a cell at
/// level
/// <code>scanDetailLevel</code>
/// then it calls
/// <see cref="VisitScanned(Lucene.Net.Spatial.Prefix.Tree.Cell)">VisitScanned(Lucene.Net.Spatial.Prefix.Tree.Cell)
/// </see>
/// .
/// </summary>
/// <exception cref="System.IO.IOException"></exception>
protected internal virtual void Scan(int scanDetailLevel)
{
for (;
thisTerm != null && StringHelper.StartsWith(thisTerm, curVNodeTerm
);
thisTerm = termsEnum.Next())
{
scanCell = _enclosing.grid.GetCell(thisTerm.bytes.ToByteArray(), thisTerm.offset
, thisTerm.length, scanCell);
int termLevel = scanCell.Level;
if (termLevel > scanDetailLevel)
{
continue;
}
if (termLevel == scanDetailLevel || scanCell.IsLeaf())
{
VisitScanned(scanCell);
}
}
}
/// <summary>Called first to setup things.</summary>
/// <remarks>Called first to setup things.</remarks>
/// <exception cref="System.IO.IOException"></exception>
protected internal abstract void Start();
/// <summary>Called last to return the result.</summary>
/// <remarks>Called last to return the result.</remarks>
/// <exception cref="System.IO.IOException"></exception>
protected internal abstract DocIdSet Finish();
/// <summary>
/// Visit an indexed cell returned from
/// <see cref="FindSubCellsToVisit(Lucene.Net.Spatial.Prefix.Tree.Cell)">FindSubCellsToVisit(Lucene.Net.Spatial.Prefix.Tree.Cell)
/// </see>
/// .
/// </summary>
/// <param name="cell">An intersecting cell.</param>
/// <returns>
/// true to descend to more levels. It is an error to return true
/// if cell.level == detailLevel
/// </returns>
/// <exception cref="System.IO.IOException"></exception>
protected internal abstract bool Visit(Cell cell);
/// <summary>Called after visit() returns true and an indexed leaf cell is found.</summary>
/// <remarks>
/// Called after visit() returns true and an indexed leaf cell is found. An
/// indexed leaf cell means associated documents generally won't be found at
/// further detail levels.
/// </remarks>
/// <exception cref="System.IO.IOException"></exception>
protected internal abstract void VisitLeaf(Cell cell);
/// <summary>The cell is either indexed as a leaf or is the last level of detail.</summary>
/// <remarks>
/// The cell is either indexed as a leaf or is the last level of detail. It
/// might not even intersect the query shape, so be sure to check for that.
/// </remarks>
/// <exception cref="System.IO.IOException"></exception>
protected internal abstract void VisitScanned(Cell cell);
/// <exception cref="System.IO.IOException"></exception>
protected internal virtual void PreSiblings(VNode vNode)
{
}
/// <exception cref="System.IO.IOException"></exception>
protected internal virtual void PostSiblings(VNode vNode)
{
}
#region Nested type: VNodeCellIterator
/// <summary>
/// Used for
/// <see cref="VNode.children">VNode.children</see>
/// .
/// </summary>
private class VNodeCellIterator : IEnumerator<VNode>
{
private readonly VisitorTemplate _enclosing;
internal readonly IEnumerator<Cell> cellIter;
private readonly VNode vNode;
internal VNodeCellIterator(VisitorTemplate _enclosing, IEnumerator<Cell> cellIter, VNode vNode)
{
this._enclosing = _enclosing;
//term loop
this.cellIter = cellIter;
this.vNode = vNode;
}
//it always removes
#region IEnumerator<VNode> Members
public void Dispose()
{
cellIter.Dispose();
}
public bool MoveNext()
{
return cellIter.MoveNext();
}
public void Reset()
{
cellIter.Reset();
}
public VNode Current
{
get
{
Debug.Assert(cellIter.Current != null);
vNode.Reset(cellIter.Current);
return vNode;
}
}
object IEnumerator.Current
{
get { return Current; }
}
#endregion
}
#endregion
//class VisitorTemplate
}
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Management.Automation.Language;
using System.Text;
namespace System.Management.Automation
{
/// <summary>
/// The base class for the parameter binder controllers. This class and
/// its derived classes control the interaction between the command processor
/// and the parameter binder(s). It holds the state of the arguments and parameters.
/// </summary>
[DebuggerDisplay("InvocationInfo = {InvocationInfo}")]
internal abstract class ParameterBinderController
{
#region ctor
/// <summary>
/// Constructs a parameter binder controller for the specified command
/// in the specified engine context.
/// </summary>
///
/// <param name="invocationInfo">
/// The invocation information about the code being run.
/// </param>
/// <param name="context">
/// The engine context in which the command is being run.
/// </param>
/// <param name="parameterBinder">
/// The default parameter binder for the command.
/// </param>
internal ParameterBinderController(InvocationInfo invocationInfo, ExecutionContext context, ParameterBinderBase parameterBinder)
{
Diagnostics.Assert(invocationInfo != null, "Caller to verify invocationInfo is not null.");
Diagnostics.Assert(parameterBinder != null, "Caller to verify parameterBinder is not null.");
Diagnostics.Assert(context != null, "call to verify context is not null.");
this.DefaultParameterBinder = parameterBinder;
Context = context;
InvocationInfo = invocationInfo;
}
#endregion ctor
#region internal_members
/// <summary>
/// The engine context the command is running in.
/// </summary>
///
internal ExecutionContext Context { get; }
/// <summary>
/// Gets the parameter binder for the command.
/// </summary>
///
internal ParameterBinderBase DefaultParameterBinder { get; private set; }
/// <summary>
/// The invocation information about the code being run.
/// </summary>
internal InvocationInfo InvocationInfo { get; }
/// <summary>
/// All the metadata associated with any of the parameters that
/// are available from the command.
/// </summary>
///
internal MergedCommandParameterMetadata BindableParameters
{
get { return _bindableParameters; }
}
protected MergedCommandParameterMetadata _bindableParameters = new MergedCommandParameterMetadata();
/// <summary>
/// A list of the unbound parameters for the command.
/// </summary>
///
protected List<MergedCompiledCommandParameter> UnboundParameters { get; set; }
/// <summary>
/// A collection of the bound parameters for the command. The collection is
/// indexed based on the name of the parameter.
/// </summary>
///
protected Dictionary<string, MergedCompiledCommandParameter> BoundParameters { get; } = new Dictionary<string, MergedCompiledCommandParameter>(StringComparer.OrdinalIgnoreCase);
internal CommandLineParameters CommandLineParameters
{
get { return this.DefaultParameterBinder.CommandLineParameters; }
}
/// <summary>
/// Set true if the default parameter binding is in use
/// </summary>
protected bool DefaultParameterBindingInUse { get; set; } = false;
// Set true if the default parameter values are applied
/// <summary>
/// A collection of bound default parameters
/// </summary>
protected Collection<string> BoundDefaultParameters { get; } = new Collection<string>();
// Keep record of the bound default parameters
/// <summary>
/// A collection of the unbound arguments.
/// </summary>
/// <value></value>
protected Collection<CommandParameterInternal> UnboundArguments { get; set; } = new Collection<CommandParameterInternal>();
internal void ClearUnboundArguments()
{
UnboundArguments.Clear();
}
/// <summary>
/// A collection of the arguments that have been bound
/// </summary>
///
protected Dictionary<string, CommandParameterInternal> BoundArguments { get; } = new Dictionary<string, CommandParameterInternal>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Reparses the unbound arguments using the parameter metadata of the
/// specified parameter binder as the parsing guide.
/// </summary>
///
/// <exception cref="ParameterBindingException">
/// If a parameter token is not matched with an argument and its not a bool or
/// SwitchParameter.
/// Or
/// The name of the argument matches more than one parameter.
/// </exception>
///
internal void ReparseUnboundArguments()
{
Collection<CommandParameterInternal> result = new Collection<CommandParameterInternal>();
for (int index = 0; index < UnboundArguments.Count; ++index)
{
CommandParameterInternal argument = UnboundArguments[index];
// If the parameter name is not specified, or if it is specified _and_ there is an
// argument, we have nothing to reparse for this argument.
if (!argument.ParameterNameSpecified || argument.ArgumentSpecified)
{
result.Add(argument);
continue;
}
Diagnostics.Assert(argument.ParameterNameSpecified && !argument.ArgumentSpecified,
"At this point, we only process parameters with no arguments");
// Now check the argument name with the binder.
string parameterName = argument.ParameterName;
MergedCompiledCommandParameter matchingParameter =
_bindableParameters.GetMatchingParameter(
parameterName,
false,
true,
new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent));
if (matchingParameter == null)
{
// Since we couldn't find a match, just add the argument as it was
// and continue
result.Add(argument);
continue;
}
// Now that we know we have a single match for the parameter name,
// see if we can figure out what the argument value for the parameter is.
// If its a bool or switch parameter, then set the value to true and continue
if (IsSwitchAndSetValue(parameterName, argument, matchingParameter.Parameter))
{
result.Add(argument);
continue;
}
// Since it's not a bool or a SwitchParameter we need to check the next
// argument.
if (UnboundArguments.Count - 1 > index)
{
CommandParameterInternal nextArgument = UnboundArguments[index + 1];
// Since the argument appears to be a valid parameter, check the
// next argument to see if it is the value for that parameter
if (nextArgument.ParameterNameSpecified)
{
// Since we have a valid parameter we need to see if the next argument is
// an argument value for that parameter or a parameter itself.
MergedCompiledCommandParameter nextMatchingParameter =
_bindableParameters.GetMatchingParameter(
nextArgument.ParameterName,
false,
true,
new InvocationInfo(this.InvocationInfo.MyCommand, nextArgument.ParameterExtent));
if ((nextMatchingParameter != null) || nextArgument.ParameterAndArgumentSpecified)
{
// Since the next argument is a valid parameter that means the current
// argument doesn't have a value
// It is an error to have an argument that is a parameter name
// but doesn't have a value
ParameterBindingException exception =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.InvocationInfo,
GetParameterErrorExtent(argument),
matchingParameter.Parameter.Name,
matchingParameter.Parameter.Type,
null,
ParameterBinderStrings.MissingArgument,
"MissingArgument");
throw exception;
}
++index;
argument.ParameterName = matchingParameter.Parameter.Name;
argument.SetArgumentValue(nextArgument.ArgumentExtent, nextArgument.ParameterText);
result.Add(argument);
continue;
}
// The next argument appears to be the value for this parameter. Set the value,
// increment the index and continue
++index;
argument.ParameterName = matchingParameter.Parameter.Name;
argument.SetArgumentValue(nextArgument.ArgumentExtent, nextArgument.ArgumentValue);
result.Add(argument);
}
else
{
// It is an error to have a argument that is a parameter name
// but doesn't have a value
ParameterBindingException exception =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.InvocationInfo,
GetParameterErrorExtent(argument),
matchingParameter.Parameter.Name,
matchingParameter.Parameter.Type,
null,
ParameterBinderStrings.MissingArgument,
"MissingArgument");
throw exception;
}
}
UnboundArguments = result;
} // ReparseUnboundArgumentsForBinder
private static bool IsSwitchAndSetValue(
String argumentName,
CommandParameterInternal argument,
CompiledCommandParameter matchingParameter)
{
bool result = false;
if (matchingParameter.Type == typeof(SwitchParameter))
{
argument.ParameterName = argumentName;
argument.SetArgumentValue(PositionUtilities.EmptyExtent, SwitchParameter.Present);
result = true;
}
return result;
} // EnsureBoolOrSwitchAndSetValue
/// <summary>
/// The argument looks like a parameter if it is a string
/// and starts with a dash.
/// </summary>
///
/// <param name="arg">
/// The argument to check.
/// </param>
///
/// <returns>
/// True if the argument is a string and starts with a dash,
/// or false otherwise.
/// </returns>
///
internal static bool ArgumentLooksLikeParameter(string arg)
{
bool result = false;
if (!String.IsNullOrEmpty(arg))
{
result = arg[0].IsDash();
}
return result;
}
/// <summary>
/// Reparses the arguments specified in the object[] and generates CommandParameterInternal instances
/// based on whether the arguments look like parameters. The CommandParameterInternal instances then
/// get added to the specified command processor.
/// </summary>
///
/// <param name="commandProcessor">
/// The command processor instance to add the reparsed parameters to.
/// </param>
///
/// <param name="arguments">
/// The arguments that require reparsing.
/// </param>
///
internal static void AddArgumentsToCommandProcessor(CommandProcessorBase commandProcessor, object[] arguments)
{
if ((arguments != null) && (arguments.Length > 0))
{
PSBoundParametersDictionary boundParameters = arguments[0] as PSBoundParametersDictionary;
if ((boundParameters != null) && (arguments.Length == 1))
{
// If they are supplying a dictionary of parameters, use those directly
foreach (KeyValuePair<string, object> boundParameter in boundParameters)
{
CommandParameterInternal param = CommandParameterInternal.CreateParameterWithArgument(
PositionUtilities.EmptyExtent, boundParameter.Key, boundParameter.Key,
PositionUtilities.EmptyExtent, boundParameter.Value, false);
commandProcessor.AddParameter(param);
}
}
else
{
// Otherwise, we need to parse them ourselves
for (int argIndex = 0; argIndex < arguments.Length; ++argIndex)
{
CommandParameterInternal param;
string paramText = arguments[argIndex] as string;
if (ArgumentLooksLikeParameter(paramText))
{
// The argument looks like a parameter.
// Create a parameter with argument if the paramText is like this: -Path:c:\windows
// Combine it with the next argument if there is an argument, and the parameter ends in ':'.
var colonIndex = paramText.IndexOf(':');
if (colonIndex != -1 && colonIndex != paramText.Length - 1)
{
param = CommandParameterInternal.CreateParameterWithArgument(
PositionUtilities.EmptyExtent, paramText.Substring(1, colonIndex - 1), paramText,
PositionUtilities.EmptyExtent, paramText.Substring(colonIndex + 1).Trim(),
false);
}
else if (argIndex == arguments.Length - 1 || paramText[paramText.Length - 1] != ':')
{
param = CommandParameterInternal.CreateParameter(
PositionUtilities.EmptyExtent, paramText.Substring(1), paramText);
}
else
{
param = CommandParameterInternal.CreateParameterWithArgument(
PositionUtilities.EmptyExtent, paramText.Substring(1, paramText.Length - 2), paramText,
PositionUtilities.EmptyExtent, arguments[argIndex + 1],
false);
argIndex++;
}
}
else
{
param = CommandParameterInternal.CreateArgument(
PositionUtilities.EmptyExtent, arguments[argIndex]);
}
commandProcessor.AddParameter(param);
}
}
}
}
/// <summary>
/// Bind the argument to the specified parameter
/// </summary>
///
/// <param name="argument">
/// The argument to be bound.
/// </param>
///
/// <param name="flags">
/// The flags for type coercion, validation, and script block binding.
/// </param>
///
/// <returns>
/// True if the parameter was successfully bound. False if <paramref name="flags"/> does not have the
/// flag <see>ParameterBindingFlags.ShouldCoerceType</see> and the type does not match the parameter type.
/// </returns>
///
/// <exception cref="ParameterBindingException">
/// If argument transformation fails.
/// or
/// The argument could not be coerced to the appropriate type for the parameter.
/// or
/// The parameter argument transformation, prerequisite, or validation failed.
/// or
/// If the binding to the parameter fails.
/// or
/// The parameter has already been bound.
/// </exception>
///
internal virtual bool BindParameter(
CommandParameterInternal argument,
ParameterBindingFlags flags)
{
bool result = false;
MergedCompiledCommandParameter matchingParameter =
BindableParameters.GetMatchingParameter(
argument.ParameterName,
(flags & ParameterBindingFlags.ThrowOnParameterNotFound) != 0,
true,
new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent));
if (matchingParameter != null)
{
// Now check to make sure it hasn't already been
// bound by looking in the boundParameters collection
if (BoundParameters.ContainsKey(matchingParameter.Parameter.Name))
{
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.InvocationInfo,
GetParameterErrorExtent(argument),
argument.ParameterName,
null,
null,
ParameterBinderStrings.ParameterAlreadyBound,
"ParameterAlreadyBound");
throw bindingException;
}
flags = flags & ~ParameterBindingFlags.DelayBindScriptBlock;
result = BindParameter(_currentParameterSetFlag, argument, matchingParameter, flags);
}
return result;
}
/// <summary>
/// Derived classes need to define the binding of multiple arguments.
/// </summary>
///
/// <param name="parameters">
/// The arguments to be bound.
/// </param>
///
/// <returns>
/// The arguments which are still not bound.
/// </returns>
///
internal abstract Collection<CommandParameterInternal> BindParameters(Collection<CommandParameterInternal> parameters);
/// <summary>
/// Bind the argument to the specified parameter
/// </summary>
///
/// <param name="parameterSets">
/// The parameter set used to bind the arguments.
/// </param>
///
/// <param name="argument">
/// The argument to be bound.
/// </param>
///
/// <param name="parameter">
/// The metadata for the parameter to bind the argument to.
/// </param>
///
/// <param name="flags">
/// Flags for type coercion and valiation of the arguments.
/// </param>
///
/// <returns>
/// True if the parameter was successfully bound. False if <paramref name="flags"/>
/// specifies no type coercion and the type does not match the parameter type.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="parameter"/> or <paramref name="argument"/> is null.
/// </exception>
///
/// <exception cref="ParameterBindingException">
/// If argument transformation fails.
/// or
/// The argument could not be coerced to the appropriate type for the parameter.
/// or
/// The parameter argument transformation, prerequisite, or validation failed.
/// or
/// If the binding to the parameter fails.
/// </exception>
///
internal virtual bool BindParameter(
uint parameterSets,
CommandParameterInternal argument,
MergedCompiledCommandParameter parameter,
ParameterBindingFlags flags)
{
bool result = false;
switch (parameter.BinderAssociation)
{
case ParameterBinderAssociation.DeclaredFormalParameters:
result =
this.DefaultParameterBinder.BindParameter(
argument,
parameter.Parameter,
flags);
break;
default:
Diagnostics.Assert(
false,
"Only the formal parameters are available for this type of command");
break;
}
if (result && ((flags & ParameterBindingFlags.IsDefaultValue) == 0))
{
UnboundParameters.Remove(parameter);
BoundParameters.Add(parameter.Parameter.Name, parameter);
}
return result;
}
/// <summary>
/// Binds the unbound arguments to positional parameters
/// </summary>
///
/// <param name="unboundArguments">
/// The unbound arguments to attempt to bind as positional arguments.
/// </param>
///
/// <param name="validParameterSets">
/// The current parameter set flags that are valid.
/// </param>
///
/// <param name="defaultParameterSet">
/// The parameter set to use to disambiguate parameters that have the same position
/// </param>
///
/// <param name="outgoingBindingException">
/// Returns the underlying parameter binding exception if any was generated.
/// </param>
///
/// <returns>
/// The remaining arguments that have not been bound.
/// </returns>
///
/// <remarks>
/// It is assumed that the unboundArguments parameter has already been processed
/// for this parameter binder. All named parameters have been paired with their
/// values. Any arguments that don't have a name are considered positional and
/// will be processed in this method.
/// </remarks>
///
/// <exception cref="ParameterBindingException">
/// If multiple parameters were found for the same position in the specified
/// parameter set.
/// or
/// If argument transformation fails.
/// or
/// The argument could not be coerced to the appropriate type for the parameter.
/// or
/// The parameter argument transformation, prerequisite, or validation failed.
/// or
/// If the binding to the parameter fails.
/// </exception>
internal Collection<CommandParameterInternal> BindPositionalParameters(
Collection<CommandParameterInternal> unboundArguments,
uint validParameterSets,
uint defaultParameterSet,
out ParameterBindingException outgoingBindingException
)
{
Collection<CommandParameterInternal> result = new Collection<CommandParameterInternal>();
outgoingBindingException = null;
if (unboundArguments.Count > 0)
{
// Create a new collection to iterate over so that we can remove
// unbound arguments while binding them.
List<CommandParameterInternal> unboundArgumentsCollection = new List<CommandParameterInternal>(unboundArguments);
// Get a sorted dictionary of the positional parameters with the position
// as the key
SortedDictionary<int, Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>> positionalParameterDictionary;
try
{
positionalParameterDictionary =
EvaluateUnboundPositionalParameters(UnboundParameters, _currentParameterSetFlag);
}
catch (InvalidOperationException)
{
// The parameter set declaration is ambiguous so
// throw an exception.
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.InvocationInfo,
null,
null,
null,
null,
ParameterBinderStrings.AmbiguousPositionalParameterNoName,
"AmbiguousPositionalParameterNoName");
// This exception is thrown because the binder found two positional parameters
// from the same parameter set with the same position defined. This is not caused
// by introducing the default parameter binding.
throw bindingException;
}
if (positionalParameterDictionary.Count > 0)
{
int unboundArgumentsIndex = 0;
foreach (Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> nextPositionalParameters in positionalParameterDictionary.Values)
{
// Only continue if there are parameters at the specified position. Parameters
// can be removed as the parameter set gets narrowed down.
if (nextPositionalParameters.Count == 0)
{
continue;
}
CommandParameterInternal argument = GetNextPositionalArgument(
unboundArgumentsCollection,
result,
ref unboundArgumentsIndex);
if (argument == null)
{
break;
}
// Bind first to defaultParameterSet without type coercion, then to
// other sets without type coercion, then to the defaultParameterSet with
// type coercion and finally to the other sets with type coercion.
bool aParameterWasBound = false;
if (defaultParameterSet != 0 && (validParameterSets & defaultParameterSet) != 0)
{
// Favor the default parameter set.
// First try without type coercion
aParameterWasBound =
BindPositionalParametersInSet(
defaultParameterSet,
nextPositionalParameters,
argument,
ParameterBindingFlags.DelayBindScriptBlock,
out outgoingBindingException);
}
if (!aParameterWasBound)
{
// Try the non-default parameter sets
// without type coercion.
aParameterWasBound =
BindPositionalParametersInSet(
validParameterSets,
nextPositionalParameters,
argument,
ParameterBindingFlags.DelayBindScriptBlock,
out outgoingBindingException);
}
if (!aParameterWasBound)
{
// Now try the default parameter set with type coercion
if (defaultParameterSet != 0 && (validParameterSets & defaultParameterSet) != 0)
{
// Favor the default parameter set.
// First try without type coercion
aParameterWasBound =
BindPositionalParametersInSet(
defaultParameterSet,
nextPositionalParameters,
argument,
ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.DelayBindScriptBlock,
out outgoingBindingException);
}
}
if (!aParameterWasBound)
{
// Try the non-default parameter sets
// with type coercion.
aParameterWasBound =
BindPositionalParametersInSet(
validParameterSets,
nextPositionalParameters,
argument,
ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.DelayBindScriptBlock,
out outgoingBindingException);
}
if (!aParameterWasBound)
{
// Add the unprocessed argument to the results and continue
result.Add(argument);
}
else
{
// Update the parameter sets if necessary
if (validParameterSets != _currentParameterSetFlag)
{
validParameterSets = _currentParameterSetFlag;
UpdatePositionalDictionary(positionalParameterDictionary, validParameterSets);
}
}
}
// Now for any arguments that were not processed, add them to
// the result
for (int index = unboundArgumentsIndex; index < unboundArgumentsCollection.Count; ++index)
{
result.Add(unboundArgumentsCollection[index]);
}
}
else
{
// Since no positional parameters were found, add the arguments
// to the result
result = unboundArguments;
}
}
return result;
} // BindPositionalParameters
/// <summary>
/// This method only updates the collections contained in the dictionary, not the dictionary
/// itself to contain only the parameters that are in the specified parameter set.
/// </summary>
///
/// <param name="positionalParameterDictionary">
/// The sorted dictionary of positional parameters.
/// </param>
///
/// <param name="validParameterSets">
/// Valid parameter sets
/// </param>
///
internal static void UpdatePositionalDictionary(
SortedDictionary<int, Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>> positionalParameterDictionary,
uint validParameterSets)
{
foreach (Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> parameterCollection in positionalParameterDictionary.Values)
{
Collection<MergedCompiledCommandParameter> paramToRemove = new Collection<MergedCompiledCommandParameter>();
foreach (PositionalCommandParameter positionalParameter in parameterCollection.Values)
{
Collection<ParameterSetSpecificMetadata> parameterSetData = positionalParameter.ParameterSetData;
for (int index = parameterSetData.Count - 1; index >= 0; --index)
{
if ((parameterSetData[index].ParameterSetFlag & validParameterSets) == 0 &&
!parameterSetData[index].IsInAllSets)
{
// The parameter is not in the valid parameter sets so remove it from the collection.
parameterSetData.RemoveAt(index);
}
}
if (parameterSetData.Count == 0)
{
paramToRemove.Add(positionalParameter.Parameter);
}
}
// Now remove all the parameters that no longer have parameter set data
foreach (MergedCompiledCommandParameter removeParam in paramToRemove)
{
parameterCollection.Remove(removeParam);
}
}
}
private bool BindPositionalParametersInSet(
uint validParameterSets,
Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> nextPositionalParameters,
CommandParameterInternal argument,
ParameterBindingFlags flags,
out ParameterBindingException bindingException
)
{
bool result = false;
bindingException = null;
foreach (PositionalCommandParameter parameter in nextPositionalParameters.Values)
{
foreach (ParameterSetSpecificMetadata parameterSetData in parameter.ParameterSetData)
{
// if the parameter is not in the specified parameter set, don't consider it
if ((validParameterSets & parameterSetData.ParameterSetFlag) == 0 &&
!parameterSetData.IsInAllSets)
{
continue;
}
bool bindResult = false;
string parameterName = parameter.Parameter.Parameter.Name;
ParameterBindingException parameterBindingExceptionToThrown = null;
try
{
CommandParameterInternal bindableArgument =
CommandParameterInternal.CreateParameterWithArgument(
PositionUtilities.EmptyExtent, parameterName, "-" + parameterName + ":",
argument.ArgumentExtent, argument.ArgumentValue,
false);
bindResult =
BindParameter(
validParameterSets,
bindableArgument,
parameter.Parameter,
flags);
}
catch (ParameterBindingArgumentTransformationException pbex)
{
parameterBindingExceptionToThrown = pbex;
}
catch (ParameterBindingValidationException pbex)
{
if (pbex.SwallowException)
{
// Just ignore and continue
bindResult = false;
bindingException = pbex;
}
else
{
parameterBindingExceptionToThrown = pbex;
}
}
catch (ParameterBindingParameterDefaultValueException pbex)
{
parameterBindingExceptionToThrown = pbex;
}
catch (ParameterBindingException e)
{
// Just ignore and continue;
bindResult = false;
bindingException = e;
}
if (parameterBindingExceptionToThrown != null)
{
if (!DefaultParameterBindingInUse)
{
throw parameterBindingExceptionToThrown;
}
else
{
ThrowElaboratedBindingException(parameterBindingExceptionToThrown);
}
}
if (bindResult)
{
result = true;
this.CommandLineParameters.MarkAsBoundPositionally(parameterName);
break;
}
}
}
return result;
}
/// <summary>
/// Generate elaborated binding exception so that the user will know the default binding might cause the failure
/// </summary>
/// <param name="pbex"></param>
protected void ThrowElaboratedBindingException(ParameterBindingException pbex)
{
if (pbex == null)
{
throw PSTraceSource.NewArgumentNullException("pbex");
}
Diagnostics.Assert(pbex.ErrorRecord != null, "ErrorRecord should not be null in a ParameterBindingException");
// Original error message
string oldMsg = pbex.Message;
// Default parameters get bound so far
StringBuilder defaultParamsGetBound = new StringBuilder();
foreach (string paramName in BoundDefaultParameters)
{
defaultParamsGetBound.AppendFormat(CultureInfo.InvariantCulture, " -{0}", paramName);
}
string resourceString = ParameterBinderStrings.DefaultBindingErrorElaborationSingle;
if (BoundDefaultParameters.Count > 1)
{
resourceString = ParameterBinderStrings.DefaultBindingErrorElaborationMultiple;
}
ParameterBindingException newBindingException =
new ParameterBindingException(
pbex.InnerException,
pbex,
resourceString,
oldMsg, defaultParamsGetBound);
throw newBindingException;
}
private static CommandParameterInternal GetNextPositionalArgument(
List<CommandParameterInternal> unboundArgumentsCollection,
Collection<CommandParameterInternal> nonPositionalArguments,
ref int unboundArgumentsIndex)
{
// Find the next positional argument
// An argument without a name is considered to be positional since
// we are assuming the unboundArguments have been reparsed using
// the merged metadata from this parameter binder controller.
CommandParameterInternal result = null;
while (unboundArgumentsIndex < unboundArgumentsCollection.Count)
{
CommandParameterInternal argument = unboundArgumentsCollection[unboundArgumentsIndex++];
if (!argument.ParameterNameSpecified)
{
result = argument;
break;
}
nonPositionalArguments.Add(argument);
// Now check to see if the next argument needs to be consumed as well.
if (unboundArgumentsCollection.Count - 1 >= unboundArgumentsIndex)
{
argument = unboundArgumentsCollection[unboundArgumentsIndex];
if (!argument.ParameterNameSpecified)
{
// Since the next argument doesn't appear to be a parameter name
// consume it as well.
nonPositionalArguments.Add(argument);
unboundArgumentsIndex++;
}
}
}
return result;
}
/// <summary>
/// Gets the unbound positional parameters in a sorted dictionary in the order of their
/// positions.
/// </summary>
///
/// <returns>
/// The sorted dictionary of MergedCompiledCommandParameter metadata with the position
/// as the key.
/// </returns>
///
internal static SortedDictionary<int, Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>> EvaluateUnboundPositionalParameters(
ICollection<MergedCompiledCommandParameter> unboundParameters, uint validParameterSetFlag)
{
SortedDictionary<int, Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>> result =
new SortedDictionary<int, Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>>();
if (unboundParameters.Count > 0)
{
// Loop through the unbound parameters and find a parameter in the specified parameter set
// that has a position greater than or equal to the positionalParameterIndex
foreach (MergedCompiledCommandParameter parameter in unboundParameters)
{
bool isInParameterSet = (parameter.Parameter.ParameterSetFlags & validParameterSetFlag) != 0 || parameter.Parameter.IsInAllSets;
if (isInParameterSet)
{
var parameterSetDataCollection = parameter.Parameter.GetMatchingParameterSetData(validParameterSetFlag);
foreach (ParameterSetSpecificMetadata parameterSetData in parameterSetDataCollection)
{
// Skip ValueFromRemainingArguments parameters
if (parameterSetData.ValueFromRemainingArguments)
{
continue;
}
// Check the position in the parameter set
int positionInParameterSet = parameterSetData.Position;
if (positionInParameterSet == int.MinValue)
{
// The parameter is not positional so go to the next one
continue;
}
AddNewPosition(result, positionInParameterSet, parameter, parameterSetData);
}
}
}
}
return result;
} // EvaluateUnboundPositionalParameters
private static void AddNewPosition(
SortedDictionary<int, Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>> result,
int positionInParameterSet,
MergedCompiledCommandParameter parameter,
ParameterSetSpecificMetadata parameterSetData)
{
Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> positionalCommandParameters;
if (result.TryGetValue(positionInParameterSet, out positionalCommandParameters))
{
// Check to see if any of the other parameters in this position are in the same parameter set.
if (ContainsPositionalParameterInSet(positionalCommandParameters, parameter, parameterSetData.ParameterSetFlag))
{
// Multiple parameters were found with the same
// position. This means the parameter set is ambiguous.
// positional parameter could not be resolved
// We throw InvalidOperationException, which the
// caller will catch and throw a more
// appropriate exception.
throw PSTraceSource.NewInvalidOperationException();
}
PositionalCommandParameter positionalCommandParameter;
if (!positionalCommandParameters.TryGetValue(parameter, out positionalCommandParameter))
{
positionalCommandParameter = new PositionalCommandParameter(parameter);
positionalCommandParameters.Add(parameter, positionalCommandParameter);
}
positionalCommandParameter.ParameterSetData.Add(parameterSetData);
}
else
{
Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> newPositionDictionary =
new Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>();
PositionalCommandParameter newPositionalParameter = new PositionalCommandParameter(parameter);
newPositionalParameter.ParameterSetData.Add(parameterSetData);
newPositionDictionary.Add(parameter, newPositionalParameter);
result.Add(positionInParameterSet, newPositionDictionary);
}
}
private static bool ContainsPositionalParameterInSet(
Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> positionalCommandParameters,
MergedCompiledCommandParameter parameter,
uint parameterSet)
{
bool result = false;
foreach (KeyValuePair<MergedCompiledCommandParameter, PositionalCommandParameter> pair in positionalCommandParameters)
{
// It's OK to have the same parameter
if (pair.Key == parameter)
{
continue;
}
foreach (ParameterSetSpecificMetadata parameterSetData in pair.Value.ParameterSetData)
{
if ((parameterSetData.ParameterSetFlag & parameterSet) != 0 ||
parameterSetData.ParameterSetFlag == parameterSet)
{
result = true;
break;
}
}
if (result)
{
break;
}
}
return result;
}
/// <summary>
/// Keeps track of the parameters that get bound through pipeline input, so that their
/// previous values can be restored before the next pipeline input comes.
/// </summary>
///
internal Collection<MergedCompiledCommandParameter> ParametersBoundThroughPipelineInput { get; } = new Collection<MergedCompiledCommandParameter>();
/// <summary>
/// For any unbound parameters, this method checks to see if the
/// parameter has a default value specified, and evaluates the expression
/// (if the expression is not constant) and binds the result to the parameter.
/// If not, we bind null to the parameter (which may go through type coercion).
/// </summary>
internal void BindUnboundScriptParameters()
{
foreach (MergedCompiledCommandParameter parameter in UnboundParameters)
{
BindUnboundScriptParameterWithDefaultValue(parameter);
}
}
/// <summary>
/// If the parameter binder might use the value more than once, this it can save the value to avoid
/// re-evalauting complicated expressions.
/// </summary>
protected virtual void SaveDefaultScriptParameterValue(string name, object value)
{
// By default, parameter binders don't need to remember the value, the exception being the cmdlet parameter binder.
}
/// <summary>
/// Bind the default value for an unbound parameter to script (used by both the script binder
/// and the cmdlet binder).
/// </summary>
internal void BindUnboundScriptParameterWithDefaultValue(MergedCompiledCommandParameter parameter)
{
ScriptParameterBinder spb = (ScriptParameterBinder)this.DefaultParameterBinder;
ScriptBlock script = spb.Script;
RuntimeDefinedParameter runtimeDefinedParameter;
if (script.RuntimeDefinedParameters.TryGetValue(parameter.Parameter.Name, out runtimeDefinedParameter))
{
bool oldRecordParameters = spb.RecordBoundParameters;
try
{
spb.RecordBoundParameters = false;
// We may pass a magic parameter from the remote end with the values for the using expressions.
// In this case, we want to use those values to evaluate the default value. e.g. param($a = $using:date)
System.Collections.IDictionary implicitUsingParameters = null;
if (DefaultParameterBinder.CommandLineParameters != null)
{
implicitUsingParameters = DefaultParameterBinder.CommandLineParameters.GetImplicitUsingParameters();
}
object result = spb.GetDefaultScriptParameterValue(runtimeDefinedParameter, implicitUsingParameters);
SaveDefaultScriptParameterValue(parameter.Parameter.Name, result);
CommandParameterInternal argument = CommandParameterInternal.CreateParameterWithArgument(
PositionUtilities.EmptyExtent, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":",
PositionUtilities.EmptyExtent, result,
false);
ParameterBindingFlags flags = ParameterBindingFlags.IsDefaultValue;
// Only coerce explicit values. We default to null, which isn't always convertible.
if (runtimeDefinedParameter.IsSet)
{
flags |= ParameterBindingFlags.ShouldCoerceType;
}
BindParameter(uint.MaxValue, argument, parameter, flags);
}
finally
{
spb.RecordBoundParameters = oldRecordParameters;
}
}
}
internal uint _currentParameterSetFlag = uint.MaxValue;
internal uint _prePipelineProcessingParameterSetFlags = uint.MaxValue;
protected IScriptExtent GetErrorExtent(CommandParameterInternal cpi)
{
var result = cpi.ErrorExtent;
if (result == PositionUtilities.EmptyExtent)
result = InvocationInfo.ScriptPosition;
// Can't use this assertion - we don't have useful positions when invoked via PowerShell API
//Diagnostics.Assert(result != PositionUtilities.EmptyExtent, "We are missing a valid position somewhere");
return result;
}
protected IScriptExtent GetParameterErrorExtent(CommandParameterInternal cpi)
{
var result = cpi.ParameterExtent;
if (result == PositionUtilities.EmptyExtent)
result = InvocationInfo.ScriptPosition;
// Can't use this assertion - we don't have useful positions when invoked via PowerShell API
//Diagnostics.Assert(result != PositionUtilities.EmptyExtent, "We are missing a valid position somewhere");
return result;
}
#endregion internal_members
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Oranikle.Report.Engine;
namespace Oranikle.Report.Engine
{
/// <summary>
/// Base class for all aggregate functions
/// </summary>
[Serializable]
public abstract class FunctionAggr
{
public IExpr _Expr; // aggregate expression
public object _Scope; // DataSet or Grouping or DataRegion that contains (directly or
// indirectly) the report item that the aggregate
// function is used in
// Can also hold the Matrix object
bool _LevelCheck; // row processing requires level check
// i.e. simple specified on recursive row check
/// <summary>
/// Base class of all aggregate functions
/// </summary>
public FunctionAggr(IExpr e, object scp)
{
_Expr = e;
_Scope = scp;
_LevelCheck = false;
}
public bool IsConstant()
{
return false;
}
public IExpr ConstantOptimization()
{
if (_Expr != null)
_Expr = _Expr.ConstantOptimization();
return (IExpr) this;
}
public bool EvaluateBoolean(Report rpt, Row row)
{
return false;
}
public IExpr Expr
{
get { return _Expr; }
}
public object Scope
{
get { return _Scope; }
}
public bool LevelCheck
{
get { return _LevelCheck; }
set { _LevelCheck = value; }
}
// return an IEnumerable that represents the scope of the data
protected RowEnumerable GetDataScope(Report rpt, Row row, out bool bSave)
{
bSave=true;
RowEnumerable re=null;
if (this._Scope != null)
{
Type t = this._Scope.GetType();
//150208AJM GJL Trying - And Succeeding!!! to get data from chart
if (t == typeof(Chart)) {
Chart c = (Chart)this._Scope;
this._Scope = c.ChartMatrix;
t = this._Scope.GetType();
}
if (t == typeof(Grouping))
{
bSave=false;
Grouping g = (Grouping) (this._Scope);
if (g.InMatrix)
{
Rows rows = g.GetRows(rpt);
if (rows == null)
return null;
re = new RowEnumerable(0, rows.Data.Count-1, rows.Data, _LevelCheck);
}
else
{
if (row == null || row.R.CurrentGroups == null) // currentGroups can be null when reference Textbox in header/footer that has a scoped aggr function reference (TODO: this is a problem!)
return null;
GroupEntry ge = row.R.CurrentGroups[g.GetIndex(rpt)];
re = new RowEnumerable (ge.StartRow, ge.EndRow, row.R.Data, _LevelCheck);
}
}
else if (t == typeof(Matrix))
{
bSave=false;
Matrix m = (Matrix) (this._Scope);
Rows mData = m.GetMyData(rpt);
re = new RowEnumerable(0, mData.Data.Count-1, mData.Data, false);
}
else if (t == typeof(string))
{ // happens on page header/footer scope
if (row != null)
re = new RowEnumerable (0, row.R.Data.Count-1, row.R.Data, false);
bSave = false;
}
else if (row != null)
{
re = new RowEnumerable (0, row.R.Data.Count-1, row.R.Data, false);
}
else
{
DataSetDefn ds = this._Scope as DataSetDefn;
if (ds != null && ds.Query != null)
{
Rows rows = ds.Query.GetMyData(rpt);
if (rows != null)
re = new RowEnumerable(0, rows.Data.Count-1, rows.Data, false);
}
}
}
else if (row != null)
{
re = new RowEnumerable (0, row.R.Data.Count-1, row.R.Data, false);
}
return re;
}
}
public class RowEnumerable : IEnumerable
{
int startRow;
int endRow;
List<Row> data;
bool _LevelCheck;
public RowEnumerable(int start, int end, List<Row> d, bool levelCheck)
{
startRow = start;
endRow = end;
data = d;
_LevelCheck = levelCheck;
}
public List<Row> Data
{
get{return data;}
}
public int FirstRow
{
get{return startRow;}
}
public int LastRow
{
get{return endRow;}
}
public bool LevelCheck
{
get{return _LevelCheck;}
}
// Methods
public IEnumerator GetEnumerator()
{
return new RowEnumerator(this);
}
}
public class RowEnumerator : IEnumerator
{
private RowEnumerable re;
private int index = -1;
public RowEnumerator(RowEnumerable rea)
{
re = rea;
}
//Methods
public bool MoveNext()
{
index++;
while (true)
{
if (index + re.FirstRow > re.LastRow)
return false;
else
{
if (re.LevelCheck)
{ //
Row r1 = re.Data[re.FirstRow] as Row;
Row r2 = re.Data[index + re.FirstRow] as Row;
if (r1.Level == r1.Level)
return true;
index++;
}
else
return true;
}
}
}
public void Reset()
{
index=-1;
}
public object Current
{
get{return(re.Data[index + re.FirstRow]);}
}
}
}
| |
using System;
using System.Collections.Generic;
using ALinq;
using ALinq.Mapping;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace ALinq.SqlClient
{
internal class SqlBinder
{
// Fields
private SqlColumnizer columnizer;
private bool optimizeLinkExpansions = true;
private Func<SqlNode, SqlNode> prebinder;
private bool simplifyCaseStatements = true;
private SqlFactory sql;
private Visitor visitor;
private ConstColumns c;
// Methods
internal SqlBinder(Translator translator, SqlFactory sqlFactory, MetaModel model,
DataLoadOptions shape, SqlColumnizer columnizer)
{
this.sql = sqlFactory;
this.columnizer = columnizer;
this.visitor = new Visitor(this, translator, this.columnizer, this.sql, model, shape);
c = new ConstColumns(translator.Provider.Mode);
}
internal SqlNode Bind(SqlNode node)
{
node = this.Prebind(node);
node = this.visitor.Visit(node);
return node;
}
private SqlNode Prebind(SqlNode node)
{
if (this.prebinder != null)
{
node = this.prebinder(node);
}
return node;
}
// Properties
internal bool OptimizeLinkExpansions
{
get
{
return this.optimizeLinkExpansions;
}
set
{
this.optimizeLinkExpansions = value;
}
}
internal Func<SqlNode, SqlNode> PreBinder
{
get
{
return this.prebinder;
}
set
{
this.prebinder = value;
}
}
internal bool SimplifyCaseStatements
{
get
{
return this.simplifyCaseStatements;
}
set
{
this.simplifyCaseStatements = value;
}
}
// Nested Types
private class LinkOptimizationScope
{
// Fields
private Dictionary<object, SqlExpression> map;
private SqlBinder.LinkOptimizationScope previous;
// Methods
internal LinkOptimizationScope(SqlBinder.LinkOptimizationScope previous)
{
this.previous = previous;
}
internal void Add(object linkId, SqlExpression expr)
{
if (this.map == null)
{
this.map = new Dictionary<object, SqlExpression>();
}
this.map.Add(linkId, expr);
}
internal bool TryGetValue(object linkId, out SqlExpression expr)
{
expr = null;
return (((this.map != null) && this.map.TryGetValue(linkId, out expr)) || ((this.previous != null) && this.previous.TryGetValue(linkId, out expr)));
}
}
private class Visitor : SqlVisitor
{
// Fields
private SqlAggregateChecker aggregateChecker;
private HashSet<MetaType> alreadyIncluded;
private SqlBinder binder;
private SqlColumnizer columnizer;
private SqlAlias currentAlias;
private SqlSelect currentSelect;
private bool disableInclude;
private SqlExpander expander;
private bool inGroupBy;
private SqlBinder.LinkOptimizationScope linkMap;
private MetaModel model;
private Dictionary<SqlAlias, SqlAlias> outerAliasMap;
private DataLoadOptions shape;
private SqlFactory sql;
private Translator translator;
private ITypeSystemProvider typeProvider;
private ConstColumns c;
// Methods
internal Visitor(SqlBinder binder, Translator translator, SqlColumnizer columnizer, SqlFactory sqlFactory, MetaModel model, DataLoadOptions shape)
{
this.binder = binder;
this.translator = translator;
this.columnizer = columnizer;
this.sql = sqlFactory;
this.typeProvider = sqlFactory.TypeProvider;
this.expander = new SqlExpander(this.sql);
this.aggregateChecker = new SqlAggregateChecker();
this.linkMap = new SqlBinder.LinkOptimizationScope(null);
this.outerAliasMap = new Dictionary<SqlAlias, SqlAlias>();
this.model = model;
this.shape = shape;
c = new ConstColumns(translator.Provider.Mode);
}
private SqlNode AccessMember(SqlMember m, SqlExpression expo)
{
SqlNew typeBinding;
SqlValue value2;
Func<MetaDataMember, bool> predicate = null;
SqlExpression expr = expo;
switch (expr.NodeType)
{
case SqlNodeType.Element:
case SqlNodeType.ScalarSubSelect:
{
var select = (SqlSubSelect)expr;
var alias = new SqlAlias(select.Select);
var selection = new SqlAliasRef(alias);
SqlSelect currentSelect = this.currentSelect;
try
{
var select3 = new SqlSelect(selection, alias, select.SourceExpression);
this.currentSelect = select3;
SqlNode node2 = this.Visit(this.sql.Member(selection, m.Member));
SqlExpression expression10 = node2 as SqlExpression;
if (expression10 != null)
{
select3.Selection = this.ConvertLinks(expression10);
SqlNodeType nt = ((expression10 is SqlTypeCase) || !expression10.SqlType.CanBeColumn) ? SqlNodeType.Element : SqlNodeType.ScalarSubSelect;
SqlSubSelect ss = this.sql.SubSelect(nt, select3);
return this.FoldSubquery(ss);
}
SqlSelect select5 = node2 as SqlSelect;
if (select5 == null)
{
throw Error.UnexpectedNode(node2.NodeType);
}
SqlAlias alias2 = new SqlAlias(select5);
SqlAliasRef exp = new SqlAliasRef(alias2);
select3.Selection = this.ConvertLinks(this.VisitExpression(exp));
select3.From = new SqlJoin(SqlJoinType.CrossApply, alias, alias2, null, m.SourceExpression);
return select3;
}
finally
{
this.currentSelect = currentSelect;
}
goto Label_07B9;
}
case SqlNodeType.Lift:
return this.AccessMember(m, ((SqlLift)expr).Expression);
case SqlNodeType.Grouping:
{
var grouping = (SqlGrouping)expr;
if (m.Member.Name == ConstColumns.Key)//ConstColumns.GetKey(translator.Provider.Mode))//"Key")
{
return grouping.Key;
}
goto Label_098C;
}
case SqlNodeType.ClientCase:
{
SqlClientCase @case = (SqlClientCase)expr;
Type clrType = null;
List<SqlExpression> matches = new List<SqlExpression>();
List<SqlExpression> values = new List<SqlExpression>();
foreach (SqlClientWhen when in @case.Whens)
{
SqlExpression item = (SqlExpression)this.AccessMember(m, when.Value);
if (clrType == null)
{
clrType = item.ClrType;
}
else if (clrType != item.ClrType)
{
throw Error.ExpectedClrTypesToAgree(clrType, item.ClrType);
}
matches.Add(when.Match);
values.Add(item);
}
return this.sql.Case(clrType, @case.Expression, matches, values, @case.SourceExpression);
}
case SqlNodeType.ClientParameter:
{
SqlClientParameter parameter = (SqlClientParameter)expr;
return new SqlClientParameter(m.ClrType, m.SqlType, Expression.Lambda(typeof(Func<,>).MakeGenericType(new Type[] { typeof(object[]), m.ClrType }), Expression.MakeMemberAccess(parameter.Accessor.Body, m.Member), parameter.Accessor.Parameters), parameter.SourceExpression);
}
case SqlNodeType.AliasRef:
{
SqlAliasRef ref2 = (SqlAliasRef)expr;
SqlTable table = ref2.Alias.Node as SqlTable;
if (table != null)
{
MetaDataMember member = GetRequiredInheritanceDataMember(table.RowType, m.Member);
string columnName = member.MappedName;
SqlColumn column = table.Find(columnName);
if (column == null)
{
IProviderType sqlType = this.sql.Default(member);
column = new SqlColumn(m.ClrType, sqlType, columnName, member, null, m.SourceExpression);
column.Alias = ref2.Alias;
table.Columns.Add(column);
}
return new SqlColumnRef(column);
}
SqlTableValuedFunctionCall call = ref2.Alias.Node as SqlTableValuedFunctionCall;
if (call == null)
{
goto Label_098C;
}
MetaDataMember requiredInheritanceDataMember = GetRequiredInheritanceDataMember(call.RowType, m.Member);
string mappedName = requiredInheritanceDataMember.MappedName;
SqlColumn column2 = call.Find(mappedName);
if (column2 == null)
{
IProviderType type4 = this.sql.Default(requiredInheritanceDataMember);
column2 = new SqlColumn(m.ClrType, type4, mappedName, requiredInheritanceDataMember, null, m.SourceExpression);
column2.Alias = ref2.Alias;
call.Columns.Add(column2);
}
return new SqlColumnRef(column2);
}
case SqlNodeType.OptionalValue:
return this.AccessMember(m, ((SqlOptionalValue)expr).Value);
case SqlNodeType.OuterJoinedValue:
{
SqlNode node = this.AccessMember(m, ((SqlUnary)expr).Operand);
SqlExpression expression = node as SqlExpression;
if (expression != null)
{
return this.sql.Unary(SqlNodeType.OuterJoinedValue, expression);
}
return node;
}
case SqlNodeType.New:
{
SqlNew new4 = (SqlNew)expr;
SqlExpression find = new4.Find(m.Member);
#region MyRegion
//if (find is SqlColumnRef && ((SqlColumnRef)find).Column is MySqlColumn)
//{
// var match = ((SqlColumnRef)find).Column;
// foreach (var alias in this.outerAliasMap.Keys)
// {
// //var alias = item.Value;
// var tab = alias.Node as SqlTable;
// if (tab != null)
// {
// var t1 = match.MetaMember.DeclaringType.Type;
// var t2 = tab.RowType.Type;
// if (t1 == t2 || t1.IsSubclassOf(t2))
// {
// tab.Columns.Add(match);
// //SqlAlias alias;
// //if (aliases.TryGetValue(tab, out alias))
// match.Alias = alias;
// }
// }
// }
//}
#endregion
if (find != null)
{
return find;
}
if (predicate == null)
{
predicate = delegate(MetaDataMember p)
{
return p.Member == m.Member;
};
}
MetaDataMember member4 = new4.MetaType.PersistentDataMembers.FirstOrDefault<MetaDataMember>(predicate);
if (!new4.SqlType.CanBeColumn && (member4 != null))
{
throw Error.MemberNotPartOfProjection(m.Member.DeclaringType, m.Member.Name);
}
goto Label_098C;
}
case SqlNodeType.SearchedCase:
{
SqlSearchedCase case3 = (SqlSearchedCase)expr;
List<SqlWhen> list5 = new List<SqlWhen>(case3.Whens.Count);
foreach (SqlWhen when3 in case3.Whens)
{
SqlExpression expression6 = (SqlExpression)this.AccessMember(m, when3.Value);
list5.Add(new SqlWhen(when3.Match, expression6));
}
SqlExpression @else = (SqlExpression)this.AccessMember(m, case3.Else);
return this.sql.SearchedCase(list5.ToArray(), @else, case3.SourceExpression);
}
case SqlNodeType.UserRow:
{
SqlUserRow row = (SqlUserRow)expr;
SqlUserQuery query = row.Query;
MetaDataMember member3 = GetRequiredInheritanceDataMember(row.RowType, m.Member);
string name = member3.MappedName;
SqlUserColumn column3 = query.Find(name);
if (column3 == null)
{
IProviderType type5 = this.sql.Default(member3);
column3 = new SqlUserColumn(m.ClrType, type5, query, name, member3.IsPrimaryKey, m.SourceExpression);
query.Columns.Add(column3);
}
return column3;
}
case SqlNodeType.Value:
goto Label_07B9;
case SqlNodeType.TypeCase:
{
SqlTypeCase case4 = (SqlTypeCase)expr;
typeBinding = case4.Whens[0].TypeBinding as SqlNew;
foreach (SqlTypeCaseWhen when4 in case4.Whens)
{
if (when4.TypeBinding.NodeType == SqlNodeType.New)
{
SqlNew new3 = (SqlNew)when4.TypeBinding;
if (m.Member.DeclaringType.IsAssignableFrom(new3.ClrType))
{
typeBinding = new3;
break;
}
}
}
break;
}
case SqlNodeType.SimpleCase:
{
SqlSimpleCase case2 = (SqlSimpleCase)expr;
Type type2 = null;
List<SqlExpression> list3 = new List<SqlExpression>();
List<SqlExpression> list4 = new List<SqlExpression>();
foreach (SqlWhen when2 in case2.Whens)
{
SqlExpression expression4 = (SqlExpression)this.AccessMember(m, when2.Value);
if (type2 == null)
{
type2 = expression4.ClrType;
}
else if (type2 != expression4.ClrType)
{
throw Error.ExpectedClrTypesToAgree(type2, expression4.ClrType);
}
list3.Add(when2.Match);
list4.Add(expression4);
}
return this.sql.Case(type2, case2.Expression, list3, list4, case2.SourceExpression);
}
default:
goto Label_098C;
}
return this.AccessMember(m, typeBinding);
Label_07B9:
value2 = (SqlValue)expr;
if (value2.Value == null)
{
return this.sql.Value(m.ClrType, m.SqlType, null, value2.IsClientSpecified, m.SourceExpression);
}
if (m.Member is PropertyInfo)
{
PropertyInfo info = (PropertyInfo)m.Member;
return this.sql.Value(m.ClrType, m.SqlType, info.GetValue(value2.Value, null), value2.IsClientSpecified, m.SourceExpression);
}
FieldInfo info2 = (FieldInfo)m.Member;
return this.sql.Value(m.ClrType, m.SqlType, info2.GetValue(value2.Value), value2.IsClientSpecified, m.SourceExpression);
Label_098C:
if (m.Expression == expr)
{
return m;
}
return this.sql.Member(expr, m.Member);
}
private SqlExpression ApplyTreat(SqlExpression target, Type type)
{
switch (target.NodeType)
{
case SqlNodeType.OptionalValue:
{
SqlOptionalValue value2 = (SqlOptionalValue)target;
return this.ApplyTreat(value2.Value, type);
}
case SqlNodeType.OuterJoinedValue:
{
SqlUnary unary = (SqlUnary)target;
return this.ApplyTreat(unary.Operand, type);
}
case SqlNodeType.TypeCase:
{
SqlTypeCase @case = (SqlTypeCase)target;
int num = 0;
foreach (SqlTypeCaseWhen when in @case.Whens)
{
when.TypeBinding = this.ApplyTreat(when.TypeBinding, type);
if (this.IsConstNull(when.TypeBinding))
{
num++;
}
}
if (num == @case.Whens.Count)
{
@case.Whens[0].TypeBinding.SetClrType(type);
return @case.Whens[0].TypeBinding;
}
@case.SetClrType(type);
return target;
}
case SqlNodeType.New:
{
SqlNew new2 = (SqlNew)target;
if (!type.IsAssignableFrom(new2.ClrType))
{
return this.sql.TypedLiteralNull(type, target.SourceExpression);
}
return target;
}
}
SqlExpression expression = target;
if (((expression != null) && !type.IsAssignableFrom(expression.ClrType)) && !expression.ClrType.IsAssignableFrom(type))
{
return this.sql.TypedLiteralNull(type, target.SourceExpression);
}
return target;
}
private SqlExpression ConvertLinks(SqlExpression node)
{
if (node == null)
{
return null;
}
SqlNodeType nodeType = node.NodeType;
if (nodeType <= SqlNodeType.Column)
{
switch (nodeType)
{
case SqlNodeType.ClientCase:
{
SqlClientCase @case = (SqlClientCase)node;
foreach (SqlClientWhen when in @case.Whens)
{
SqlExpression expression3 = this.ConvertLinks(when.Value);
when.Value = expression3;
if (!@case.ClrType.IsAssignableFrom(when.Value.ClrType))
{
throw Error.DidNotExpectTypeChange(when.Value.ClrType, @case.ClrType);
}
}
return node;
}
case SqlNodeType.Column:
{
SqlColumn column = (SqlColumn)node;
if (column.Expression != null)
{
column.Expression = this.ConvertLinks(column.Expression);
}
return node;
}
}
return node;
}
switch (nodeType)
{
case SqlNodeType.Link:
return this.ConvertToFetchedExpression((SqlLink)node);
case SqlNodeType.OuterJoinedValue:
{
SqlExpression operand = ((SqlUnary)node).Operand;
SqlExpression expression = this.ConvertLinks(operand);
if (expression == operand)
{
return node;
}
if (expression.NodeType != SqlNodeType.OuterJoinedValue)
{
return this.sql.Unary(SqlNodeType.OuterJoinedValue, expression);
}
return expression;
}
}
return node;
}
internal SqlExpression ConvertToExpression(SqlNode node)
{
if (node == null)
{
return null;
}
SqlExpression expression = node as SqlExpression;
if (expression != null)
{
return expression;
}
SqlSelect select = node as SqlSelect;
if (select == null)
{
throw Error.UnexpectedNode(node.NodeType);
}
return this.sql.SubSelect(SqlNodeType.Multiset, select);
}
internal SqlExpression ConvertToFetchedExpression(SqlNode node)
{
if (node == null)
{
return null;
}
switch (node.NodeType)
{
case SqlNodeType.ClientCase:
{
SqlClientCase clientCase = (SqlClientCase)node;
List<SqlNode> sequences = new List<SqlNode>();
bool flag = true;
foreach (SqlClientWhen when in clientCase.Whens)
{
SqlNode item = this.ConvertToFetchedExpression(when.Value);
flag = flag && (item is SqlExpression);
sequences.Add(item);
}
if (flag)
{
List<SqlExpression> matches = new List<SqlExpression>();
List<SqlExpression> values = new List<SqlExpression>();
int num = 0;
int count = sequences.Count;
while (num < count)
{
SqlExpression expression3 = (SqlExpression)sequences[num];
if (!clientCase.ClrType.IsAssignableFrom(expression3.ClrType))
{
throw Error.DidNotExpectTypeChange(clientCase.ClrType, expression3.ClrType);
}
matches.Add(clientCase.Whens[num].Match);
values.Add(expression3);
num++;
}
node = this.sql.Case(clientCase.ClrType, clientCase.Expression, matches, values, clientCase.SourceExpression);
}
else
{
node = this.SimulateCaseOfSequences(clientCase, sequences);
}
goto Label_04DE;
}
case SqlNodeType.Link:
{
SqlExpression expression5;
SqlLink link = (SqlLink)node;
if (link.Expansion != null)
{
return this.VisitLinkExpansion(link);
}
if (this.linkMap.TryGetValue(link.Id, out expression5))
{
return this.VisitExpression(expression5);
}
node = this.translator.TranslateLink(link, true);
node = this.binder.Prebind(node);
node = this.ConvertToExpression(node);
node = this.Visit(node);
if ((((this.currentSelect != null) && (node != null)) && ((node.NodeType == SqlNodeType.Element) && link.Member.IsAssociation)) && this.binder.OptimizeLinkExpansions)
{
if (link.Member.Association.IsNullable || !link.Member.Association.IsForeignKey)
{
var select = (SqlSubSelect)node;
select.Select.Selection = new SqlOptionalValue(new SqlColumn(ConstColumns.Test, sql.Unary(SqlNodeType.OuterJoinedValue, sql.Value(typeof(int?), typeProvider.From(typeof(int)), 1, false, link.SourceExpression))), select.Select.Selection);
SqlExpression cond = select.Select.Where;
select.Select.Where = null;
var alias = new SqlAlias(select.Select);
this.currentSelect.From = new SqlJoin(SqlJoinType.LeftOuter, this.currentSelect.From, alias, cond, select.SourceExpression);
SqlExpression expression7 = new SqlAliasRef(alias);
this.linkMap.Add(link.Id, expression7);
return this.VisitExpression(expression7);
}
var select2 = (SqlSubSelect)node;
SqlExpression where = select2.Select.Where;
select2.Select.Where = null;
var right = new SqlAlias(select2.Select);
this.currentSelect.From = new SqlJoin(SqlJoinType.Inner, this.currentSelect.From, right, where, select2.SourceExpression);
SqlExpression expr = new SqlAliasRef(right);
this.linkMap.Add(link.Id, expr);
return this.VisitExpression(expr);
}
goto Label_04DE;
}
case SqlNodeType.OuterJoinedValue:
{
SqlExpression operand = ((SqlUnary)node).Operand;
SqlExpression expression2 = this.ConvertLinks(operand);
if (expression2 == operand)
{
return (SqlExpression)node;
}
return expression2;
}
case SqlNodeType.SearchedCase:
{
SqlSearchedCase case3 = (SqlSearchedCase)node;
foreach (SqlWhen when3 in case3.Whens)
{
when3.Match = this.ConvertToFetchedExpression(when3.Match);
when3.Value = this.ConvertToFetchedExpression(when3.Value);
}
case3.Else = this.ConvertToFetchedExpression(case3.Else);
break;
}
case SqlNodeType.TypeCase:
{
SqlTypeCase case2 = (SqlTypeCase)node;
List<SqlNode> list4 = new List<SqlNode>();
foreach (SqlTypeCaseWhen when2 in case2.Whens)
{
SqlNode node3 = this.ConvertToFetchedExpression(when2.TypeBinding);
list4.Add(node3);
}
int num3 = 0;
int num4 = list4.Count;
while (num3 < num4)
{
SqlExpression expression4 = (SqlExpression)list4[num3];
case2.Whens[num3].TypeBinding = expression4;
num3++;
}
goto Label_04DE;
}
}
Label_04DE:
return (SqlExpression)node;
}
internal SqlNode ConvertToFetchedSequence(SqlNode node)
{
if (node != null)
{
while (node.NodeType == SqlNodeType.OuterJoinedValue)
{
node = ((SqlUnary)node).Operand;
}
SqlExpression expression = node as SqlExpression;
if (expression != null)
{
if (!TypeSystem.IsSequenceType(expression.ClrType))
{
throw Error.SequenceOperatorsNotSupportedForType(expression.ClrType);
}
if (expression.NodeType == SqlNodeType.Value)
{
throw Error.QueryOnLocalCollectionNotSupported();
}
if (expression.NodeType == SqlNodeType.Link)
{
SqlLink link = (SqlLink)expression;
if (link.Expansion != null)
{
return this.VisitLinkExpansion(link);
}
node = this.translator.TranslateLink(link, false);
node = this.binder.Prebind(node);
node = this.Visit(node);
}
else if (expression.NodeType == SqlNodeType.Grouping)
{
node = ((SqlGrouping)expression).Group;
}
else if (expression.NodeType == SqlNodeType.ClientCase)
{
SqlClientCase clientCase = (SqlClientCase)expression;
List<SqlNode> sequences = new List<SqlNode>();
bool flag = false;
bool flag2 = true;
foreach (SqlClientWhen when in clientCase.Whens)
{
SqlNode item = this.ConvertToFetchedSequence(when.Value);
flag = flag || (item != when.Value);
sequences.Add(item);
flag2 = flag2 && SqlComparer.AreEqual(when.Value, clientCase.Whens[0].Value);
}
if (flag)
{
if (flag2)
{
node = sequences[0];
}
else
{
node = this.SimulateCaseOfSequences(clientCase, sequences);
}
}
}
SqlSubSelect select = node as SqlSubSelect;
if (select != null)
{
node = select.Select;
}
}
return node;
}
return node;
}
internal SqlExpression ExpandExpression(SqlExpression expression)
{
SqlExpression exp = this.expander.Expand(expression);
if (exp != expression)
{
exp = this.VisitExpression(exp);
}
return exp;
}
internal SqlExpression FetchExpression(SqlExpression expr)
{
return this.ConvertToExpression(this.ConvertToFetchedExpression(this.ConvertLinks(this.VisitExpression(expr))));
}
private SqlExpression FoldSubquery(SqlSubSelect ss)
{
Label_0000:
while ((ss.NodeType == SqlNodeType.Element) && (ss.Select.Selection.NodeType == SqlNodeType.Multiset))
{
SqlSubSelect selection = (SqlSubSelect)ss.Select.Selection;
SqlAlias alias = new SqlAlias(selection.Select);
SqlAliasRef exp = new SqlAliasRef(alias);
SqlSelect select = ss.Select;
select.Selection = this.ConvertLinks(this.VisitExpression(exp));
select.From = new SqlJoin(SqlJoinType.CrossApply, select.From, alias, null, ss.SourceExpression);
ss = this.sql.SubSelect(SqlNodeType.Multiset, select, ss.ClrType);
}
if ((ss.NodeType == SqlNodeType.Element) && (ss.Select.Selection.NodeType == SqlNodeType.Element))
{
SqlSubSelect select4 = (SqlSubSelect)ss.Select.Selection;
SqlAlias alias2 = new SqlAlias(select4.Select);
SqlAliasRef ref3 = new SqlAliasRef(alias2);
SqlSelect select5 = ss.Select;
select5.Selection = this.ConvertLinks(this.VisitExpression(ref3));
select5.From = new SqlJoin(SqlJoinType.CrossApply, select5.From, alias2, null, ss.SourceExpression);
ss = this.sql.SubSelect(SqlNodeType.Element, select5);
goto Label_0000;
}
return ss;
}
private MetaType[] GetPossibleTypes(SqlExpression typeExpression)
{
if (!typeof(Type).IsAssignableFrom(typeExpression.ClrType))
{
return new MetaType[0];
}
if (typeExpression.NodeType == SqlNodeType.DiscriminatedType)
{
SqlDiscriminatedType type = (SqlDiscriminatedType)typeExpression;
List<MetaType> list = new List<MetaType>();
foreach (MetaType type2 in type.TargetType.InheritanceTypes)
{
if (!type2.Type.IsAbstract)
{
list.Add(type2);
}
}
return list.ToArray();
}
if (typeExpression.NodeType == SqlNodeType.Value)
{
SqlValue value2 = (SqlValue)typeExpression;
MetaType metaType = this.model.GetMetaType((Type)value2.Value);
return new MetaType[] { metaType };
}
if (typeExpression.NodeType != SqlNodeType.SearchedCase)
{
throw Error.UnexpectedNode(typeExpression.NodeType);
}
SqlSearchedCase @case = (SqlSearchedCase)typeExpression;
HashSet<MetaType> source = new HashSet<MetaType>();
foreach (SqlWhen when in @case.Whens)
{
source.UnionWith(this.GetPossibleTypes(when.Value));
}
return source.ToArray<MetaType>();
}
private static MetaDataMember GetRequiredInheritanceDataMember(MetaType type, MemberInfo mi)
{
MetaType inheritanceType = type.GetInheritanceType(mi.DeclaringType);
if (inheritanceType == null)
{
throw Error.UnmappedDataMember(mi, mi.DeclaringType, type);
}
return inheritanceType.GetDataMember(mi);
}
private SqlSelect GetSourceSelect(SqlSource source)
{
SqlAlias alias = source as SqlAlias;
if (alias == null)
{
return null;
}
return (alias.Node as SqlSelect);
}
private bool IsConstNull(SqlExpression sqlExpr)
{
SqlValue value2 = sqlExpr as SqlValue;
if (value2 == null)
{
return false;
}
return ((value2.Value == null) && !value2.IsClientSpecified);
}
private SqlExpression PushDownExpression(SqlExpression expr)
{
if ((expr.NodeType == SqlNodeType.Value) && expr.SqlType.CanBeColumn)
{
expr = new SqlColumn(expr.ClrType, expr.SqlType, null, null, expr, expr.SourceExpression);
}
else
{
expr = this.columnizer.ColumnizeSelection(expr);
}
SqlSelect node = new SqlSelect(expr, this.currentSelect.From, expr.SourceExpression);
this.currentSelect.From = new SqlAlias(node);
return this.ExpandExpression(expr);
}
private SqlSelect SimulateCaseOfSequences(SqlClientCase clientCase, List<SqlNode> sequences)
{
if (sequences.Count == 1)
{
return (SqlSelect)sequences[0];
}
SqlNode right = null;
SqlSelect left = null;
int num = clientCase.Whens.Count - 1;
int num2 = (clientCase.Whens[num].Match == null) ? 1 : 0;
SqlExpression expression = null;
for (int i = 0; i < (sequences.Count - num2); i++)
{
left = (SqlSelect)sequences[i];
SqlExpression expression2 = this.sql.Binary(SqlNodeType.EQ, clientCase.Expression, clientCase.Whens[i].Match);
left.Where = this.sql.AndAccumulate(left.Where, expression2);
expression = this.sql.AndAccumulate(expression, this.sql.Binary(SqlNodeType.NE, clientCase.Expression, clientCase.Whens[i].Match));
if (right == null)
{
right = left;
}
else
{
right = new SqlUnion(left, right, true);
}
}
if (num2 == 1)
{
left = (SqlSelect)sequences[num];
left.Where = this.sql.AndAccumulate(left.Where, expression);
if (right == null)
{
right = left;
}
else
{
right = new SqlUnion(left, right, true);
}
}
SqlAlias from = new SqlAlias(right);
return new SqlSelect(new SqlAliasRef(from), from, right.SourceExpression);
}
internal override SqlAlias VisitAlias(SqlAlias a)
{
SqlAlias alias2;
SqlAlias currentAlias = this.currentAlias;
if (a.Node.NodeType == SqlNodeType.Table)
{
this.outerAliasMap[a] = this.currentAlias;
}
this.currentAlias = a;
try
{
a.Node = this.ConvertToFetchedSequence(this.Visit(a.Node));
alias2 = a;
}
finally
{
this.currentAlias = currentAlias;
}
return alias2;
}
internal override SqlExpression VisitAliasRef(SqlAliasRef aref)
{
return this.ExpandExpression(aref);
}
internal override SqlStatement VisitAssign(SqlAssign sa)
{
sa.LValue = this.FetchExpression(sa.LValue);
sa.RValue = this.FetchExpression(sa.RValue);
return sa;
}
internal override SqlExpression VisitBinaryOperator(SqlBinary bo)
{
switch (bo.NodeType)
{
case SqlNodeType.EQ:
case SqlNodeType.EQ2V:
if (!this.IsConstNull(bo.Left) || TypeSystem.IsNullableType(bo.ClrType))
{
if (!this.IsConstNull(bo.Right) || TypeSystem.IsNullableType(bo.ClrType))
{
break;
}
return this.VisitUnaryOperator(this.sql.Unary(SqlNodeType.IsNull, bo.Left, bo.SourceExpression));
}
return this.VisitUnaryOperator(this.sql.Unary(SqlNodeType.IsNull, bo.Right, bo.SourceExpression));
case SqlNodeType.NE:
case SqlNodeType.NE2V:
if (!this.IsConstNull(bo.Left) || TypeSystem.IsNullableType(bo.ClrType))
{
if (this.IsConstNull(bo.Right) && !TypeSystem.IsNullableType(bo.ClrType))
{
return this.VisitUnaryOperator(this.sql.Unary(SqlNodeType.IsNotNull, bo.Left, bo.SourceExpression));
}
break;
}
return this.VisitUnaryOperator(this.sql.Unary(SqlNodeType.IsNotNull, bo.Right, bo.SourceExpression));
}
bo.Left = this.VisitExpression(bo.Left);
bo.Right = this.VisitExpression(bo.Right);
switch (bo.NodeType)
{
case SqlNodeType.EQ:
case SqlNodeType.EQ2V:
case SqlNodeType.NE:
case SqlNodeType.NE2V:
{
SqlValue left = bo.Left as SqlValue;
SqlValue right = bo.Right as SqlValue;
bool flag = (left != null) && (left.Value is bool);
bool flag2 = (right != null) && (right.Value is bool);
if (!flag && !flag2)
{
break;
}
bool flag3 = (bo.NodeType != SqlNodeType.NE) && (bo.NodeType != SqlNodeType.NE2V);
SqlNodeType nt = ((bo.NodeType == SqlNodeType.EQ2V) || (bo.NodeType == SqlNodeType.NE2V)) ? SqlNodeType.Not2V : SqlNodeType.Not;
if (!flag || flag2)
{
if (!flag && flag2)
{
bool flag6 = (bool)right.Value;
if (flag6 ^ flag3)
{
return this.VisitUnaryOperator(new SqlUnary(nt, bo.ClrType, bo.SqlType, this.sql.DoNotVisitExpression(bo.Left), bo.SourceExpression));
}
if (bo.Left.ClrType == typeof(bool))
{
return bo.Left;
}
}
else if (flag && flag2)
{
bool flag7 = (bool)left.Value;
bool flag8 = (bool)right.Value;
if (flag3)
{
return this.sql.ValueFromObject(flag7 == flag8, false, bo.SourceExpression);
}
return this.sql.ValueFromObject(flag7 != flag8, false, bo.SourceExpression);
}
break;
}
bool flag5 = (bool)left.Value;
if (flag5 ^ flag3)
{
return this.VisitUnaryOperator(new SqlUnary(nt, bo.ClrType, bo.SqlType, this.sql.DoNotVisitExpression(bo.Right), bo.SourceExpression));
}
if (bo.Right.ClrType != typeof(bool))
{
break;
}
return bo.Right;
}
}
switch (bo.NodeType)
{
case SqlNodeType.NE:
case SqlNodeType.NE2V:
case SqlNodeType.EQ:
case SqlNodeType.EQ2V:
{
SqlExpression exp = this.translator.TranslateLinkEquals(bo);
if (exp != bo)
{
return this.VisitExpression(exp);
}
break;
}
case SqlNodeType.Or:
{
SqlValue value6 = bo.Left as SqlValue;
SqlValue value7 = bo.Right as SqlValue;
if ((value6 == null) || (value7 != null))
{
if ((value6 == null) && (value7 != null))
{
if (!((bool)value7.Value))
{
return bo.Left;
}
return this.sql.ValueFromObject(true, false, bo.SourceExpression);
}
if ((value6 != null) && (value7 != null))
{
return this.sql.ValueFromObject(((bool)value6.Value) || ((bool)value7.Value), false, bo.SourceExpression);
}
break;
}
if (!((bool)value6.Value))
{
return bo.Right;
}
return this.sql.ValueFromObject(true, false, bo.SourceExpression);
}
case SqlNodeType.And:
{
SqlValue value4 = bo.Left as SqlValue;
SqlValue value5 = bo.Right as SqlValue;
if ((value4 != null) && (value5 == null))
{
if ((bool)value4.Value)
{
return bo.Right;
}
return this.sql.ValueFromObject(false, false, bo.SourceExpression);
}
if ((value4 == null) && (value5 != null))
{
if ((bool)value5.Value)
{
return bo.Left;
}
return this.sql.ValueFromObject(false, false, bo.SourceExpression);
}
if ((value4 == null) || (value5 == null))
{
break;
}
return this.sql.ValueFromObject(((bool)value4.Value) && ((bool)value5.Value), false, bo.SourceExpression);
}
}
bo.Left = this.ConvertToFetchedExpression(bo.Left);
bo.Right = this.ConvertToFetchedExpression(bo.Right);
switch (bo.NodeType)
{
case SqlNodeType.EQ:
case SqlNodeType.EQ2V:
case SqlNodeType.NE:
case SqlNodeType.NE2V:
{
SqlExpression expression2 = this.translator.TranslateEquals(bo);
if (expression2 != bo)
{
return this.VisitExpression(expression2);
}
if (typeof(Type).IsAssignableFrom(bo.Left.ClrType))
{
SqlExpression typeSource = TypeSource.GetTypeSource(bo.Left);
SqlExpression typeExpression = TypeSource.GetTypeSource(bo.Right);
MetaType[] possibleTypes = this.GetPossibleTypes(typeSource);
MetaType[] typeArray2 = this.GetPossibleTypes(typeExpression);
bool flag9 = false;
for (int i = 0; i < possibleTypes.Length; i++)
{
for (int j = 0; j < typeArray2.Length; j++)
{
if (possibleTypes[i] == typeArray2[j])
{
flag9 = true;
break;
}
}
}
if (!flag9)
{
return this.VisitExpression(this.sql.ValueFromObject(bo.NodeType == SqlNodeType.NE, false, bo.SourceExpression));
}
if ((possibleTypes.Length == 1) && (typeArray2.Length == 1))
{
return this.VisitExpression(this.sql.ValueFromObject((bo.NodeType == SqlNodeType.EQ) == (possibleTypes[0] == typeArray2[0]), false, bo.SourceExpression));
}
SqlDiscriminatedType type2 = bo.Left as SqlDiscriminatedType;
SqlDiscriminatedType type3 = bo.Right as SqlDiscriminatedType;
if ((type2 != null) && (type3 != null))
{
return this.VisitExpression(this.sql.Binary(bo.NodeType, type2.Discriminator, type3.Discriminator));
}
}
if (TypeSystem.IsSequenceType(bo.Left.ClrType))
{
throw Error.ComparisonNotSupportedForType(bo.Left.ClrType);
}
if (TypeSystem.IsSequenceType(bo.Right.ClrType))
{
throw Error.ComparisonNotSupportedForType(bo.Right.ClrType);
}
return bo;
}
}
return bo;
}
internal override SqlExpression VisitDiscriminatorOf(SqlDiscriminatorOf dof)
{
SqlExpression operand = this.FetchExpression(dof.Object);
while ((operand.NodeType == SqlNodeType.OptionalValue) || (operand.NodeType == SqlNodeType.OuterJoinedValue))
{
if (operand.NodeType == SqlNodeType.OptionalValue)
{
operand = ((SqlOptionalValue)operand).Value;
}
else
{
operand = ((SqlUnary)operand).Operand;
}
}
if (operand.NodeType == SqlNodeType.TypeCase)
{
SqlTypeCase @case = (SqlTypeCase)operand;
List<SqlExpression> matches = new List<SqlExpression>();
List<SqlExpression> values = new List<SqlExpression>();
MetaType inheritanceDefault = @case.RowType.InheritanceDefault;
object inheritanceCode = inheritanceDefault.InheritanceCode;
foreach (SqlTypeCaseWhen when in @case.Whens)
{
matches.Add(when.Match);
if (when.Match == null)
{
SqlExpression item = this.sql.Value(inheritanceCode.GetType(), @case.Whens[0].Match.SqlType, inheritanceDefault.InheritanceCode, true, @case.SourceExpression);
values.Add(item);
}
else
{
values.Add(this.sql.Value(inheritanceCode.GetType(), when.Match.SqlType, ((SqlValue)when.Match).Value, true, @case.SourceExpression));
}
}
return this.sql.Case(@case.Discriminator.ClrType, @case.Discriminator, matches, values, @case.SourceExpression);
}
MetaType inheritanceRoot = this.model.GetMetaType(operand.ClrType).InheritanceRoot;
if (inheritanceRoot.HasInheritance)
{
return this.VisitExpression(this.sql.Member(dof.Object, inheritanceRoot.Discriminator.Member));
}
return this.sql.TypedLiteralNull(dof.ClrType, dof.SourceExpression);
}
internal override SqlExpression VisitExpression(SqlExpression expr)
{
return this.ConvertToExpression(this.Visit(expr));
}
internal override SqlExpression VisitFunctionCall(SqlFunctionCall fc)
{
int num = 0;
int count = fc.Arguments.Count;
while (num < count)
{
fc.Arguments[num] = this.FetchExpression(fc.Arguments[num]);
num++;
}
return fc;
}
internal override SqlExpression VisitGrouping(SqlGrouping g)
{
g.Key = this.FetchExpression(g.Key);
g.Group = this.FetchExpression(g.Group);
return g;
}
internal override SqlNode VisitIncludeScope(SqlIncludeScope scope)
{
SqlNode node;
this.alreadyIncluded = new HashSet<MetaType>();
try
{
node = this.Visit(scope.Child);
}
finally
{
this.alreadyIncluded = null;
}
return node;
}
internal override SqlSource VisitJoin(SqlJoin join)
{
if ((join.JoinType == SqlJoinType.CrossApply) || (join.JoinType == SqlJoinType.OuterApply))
{
join.Left = this.VisitSource(join.Left);
SqlSelect currentSelect = this.currentSelect;
try
{
this.currentSelect = this.GetSourceSelect(join.Left);
join.Right = this.VisitSource(join.Right);
this.currentSelect = null;
join.Condition = this.VisitExpression(join.Condition);
return join;
}
finally
{
this.currentSelect = currentSelect;
}
}
return base.VisitJoin(join);
}
internal override SqlExpression VisitLike(SqlLike like)
{
like.Expression = this.FetchExpression(like.Expression);
like.Pattern = this.FetchExpression(like.Pattern);
return base.VisitLike(like);
}
internal override SqlNode VisitLink(SqlLink link)
{
link = (SqlLink)base.VisitLink(link);
if ((!this.disableInclude && (this.shape != null)) && (this.alreadyIncluded != null))
{
MetaDataMember member = link.Member;
MemberInfo info = member.Member;
if (this.shape.IsPreloaded(info) && (member.LoadMethod == null))
{
MetaType inheritanceRoot = member.DeclaringType.InheritanceRoot;
if (!this.alreadyIncluded.Contains(inheritanceRoot))
{
this.alreadyIncluded.Add(inheritanceRoot);
SqlNode node = this.ConvertToFetchedExpression(link);
this.alreadyIncluded.Remove(inheritanceRoot);
return node;
}
}
}
if (this.inGroupBy && (link.Expansion != null))
{
return this.VisitLinkExpansion(link);
}
return link;
}
private SqlExpression VisitLinkExpansion(SqlLink link)
{
SqlAlias alias;
SqlAliasRef expansion = link.Expansion as SqlAliasRef;
if (((expansion != null) && (expansion.Alias.Node.NodeType == SqlNodeType.Table)) && this.outerAliasMap.TryGetValue(expansion.Alias, out alias))
{
return this.VisitAliasRef(new SqlAliasRef(alias));
}
return this.VisitExpression(link.Expansion);
}
protected override SqlNode VisitMember(SqlMember m)
{
return this.AccessMember(m, this.FetchExpression(m.Expression));
}
internal override SqlExpression VisitMethodCall(SqlMethodCall mc)
{
mc.Object = this.FetchExpression(mc.Object);
int num = 0;
int count = mc.Arguments.Count;
while (num < count)
{
mc.Arguments[num] = this.FetchExpression(mc.Arguments[num]);
num++;
}
return mc;
}
internal override SqlExpression VisitNew(SqlNew sox)
{
int num = 0;
int count = sox.Args.Count;
while (num < count)
{
if (this.inGroupBy)
{
sox.Args[num] = this.VisitExpression(sox.Args[num]);
}
else
{
sox.Args[num] = this.FetchExpression(sox.Args[num]);
}
num++;
}
int num3 = 0;
int num4 = sox.Members.Count;
while (num3 < num4)
{
SqlMemberAssign assign = sox.Members[num3];
MetaDataMember dataMember = sox.MetaType.GetDataMember(assign.Member);
MetaType inheritanceRoot = dataMember.DeclaringType.InheritanceRoot;
if (((dataMember.IsAssociation && (assign.Expression != null)) && ((assign.Expression.NodeType != SqlNodeType.Link) && (this.shape != null))) && ((this.shape.IsPreloaded(dataMember.Member) && (dataMember.LoadMethod == null)) && ((this.alreadyIncluded != null) && !this.alreadyIncluded.Contains(inheritanceRoot))))
{
this.alreadyIncluded.Add(inheritanceRoot);
assign.Expression = this.VisitExpression(assign.Expression);
this.alreadyIncluded.Remove(inheritanceRoot);
}
else if (dataMember.IsAssociation || dataMember.IsDeferred)
{
assign.Expression = this.VisitExpression(assign.Expression);
}
else
{
assign.Expression = this.FetchExpression(assign.Expression);
}
num3++;
}
return sox;
}
internal override SqlExpression VisitSearchedCase(SqlSearchedCase c)
{
if (((c.ClrType == typeof(bool)) || (c.ClrType == typeof(bool?))) && ((c.Whens.Count == 1) && (c.Else != null)))
{
SqlValue @else = c.Else as SqlValue;
SqlValue value3 = c.Whens[0].Value as SqlValue;
if ((@else != null) && !((bool)@else.Value))
{
return this.VisitExpression(this.sql.Binary(SqlNodeType.And, c.Whens[0].Match, c.Whens[0].Value));
}
if ((value3 != null) && ((bool)value3.Value))
{
return this.VisitExpression(this.sql.Binary(SqlNodeType.Or, c.Whens[0].Match, c.Else));
}
}
return base.VisitSearchedCase(c);
}
internal override SqlSelect VisitSelect(SqlSelect select)
{
SqlBinder.LinkOptimizationScope linkMap = this.linkMap;
SqlSelect currentSelect = this.currentSelect;
bool inGroupBy = this.inGroupBy;
this.inGroupBy = false;
try
{
bool flag2 = true;
if (this.binder.optimizeLinkExpansions && (((select.GroupBy.Count > 0) || this.aggregateChecker.HasAggregates(select)) || select.IsDistinct))
{
flag2 = false;
this.linkMap = new SqlBinder.LinkOptimizationScope(this.linkMap);
}
select.From = this.VisitSource(select.From);
this.currentSelect = select;
select.Where = this.VisitExpression(select.Where);
this.inGroupBy = true;
int num = 0;
int count = select.GroupBy.Count;
while (num < count)
{
select.GroupBy[num] = this.VisitExpression(select.GroupBy[num]);
num++;
}
this.inGroupBy = false;
select.Having = this.VisitExpression(select.Having);
int num3 = 0;
int num4 = select.OrderBy.Count;
while (num3 < num4)
{
select.OrderBy[num3].Expression = this.VisitExpression(select.OrderBy[num3].Expression);
num3++;
}
select.Top = this.VisitExpression(select.Top);
select.Row = (SqlRow)this.Visit(select.Row);
select.Selection = this.VisitExpression(select.Selection);
select.Selection = this.columnizer.ColumnizeSelection(select.Selection);
if (flag2)
{
select.Selection = this.ConvertLinks(select.Selection);
}
if (((select.Where != null) && (select.Where.NodeType == SqlNodeType.Value)) && ((bool)((SqlValue)select.Where).Value))
{
select.Where = null;
}
}
finally
{
this.currentSelect = currentSelect;
this.linkMap = linkMap;
this.inGroupBy = inGroupBy;
}
return select;
}
internal override SqlExpression VisitSharedExpression(SqlSharedExpression shared)
{
shared.Expression = this.VisitExpression(shared.Expression);
if (shared.Expression.NodeType != SqlNodeType.ColumnRef)
{
shared.Expression = this.PushDownExpression(shared.Expression);
}
return shared.Expression;
}
internal override SqlExpression VisitSharedExpressionRef(SqlSharedExpressionRef sref)
{
return (SqlExpression)SqlDuplicator.Copy(sref.SharedExpression.Expression);
}
internal override SqlExpression VisitSimpleExpression(SqlSimpleExpression simple)
{
simple.Expression = this.VisitExpression(simple.Expression);
if (SimpleExpression.IsSimple(simple.Expression))
{
return simple.Expression;
}
return this.PushDownExpression(simple.Expression);
}
internal override SqlExpression VisitSubSelect(SqlSubSelect ss)
{
SqlExpression expression;
SqlBinder.LinkOptimizationScope linkMap = this.linkMap;
SqlSelect currentSelect = this.currentSelect;
try
{
this.linkMap = new SqlBinder.LinkOptimizationScope(this.linkMap);
this.currentSelect = null;
expression = base.VisitSubSelect(ss);
}
finally
{
this.linkMap = linkMap;
this.currentSelect = currentSelect;
}
return expression;
}
internal override SqlExpression VisitTreat(SqlUnary a)
{
return this.VisitUnaryOperator(a);
}
internal override SqlExpression VisitUnaryOperator(SqlUnary uo)
{
uo.Operand = this.VisitExpression(uo.Operand);
if ((uo.NodeType == SqlNodeType.IsNull) || (uo.NodeType == SqlNodeType.IsNotNull))
{
SqlExpression exp = this.translator.TranslateLinkIsNull(uo);
if (exp != uo)
{
return this.VisitExpression(exp);
}
if (uo.Operand.NodeType == SqlNodeType.OuterJoinedValue)
{
SqlUnary unary = uo.Operand as SqlUnary;
if (unary.Operand.NodeType == SqlNodeType.OptionalValue)
{
SqlOptionalValue value2 = (SqlOptionalValue)unary.Operand;
return this.VisitUnaryOperator(new SqlUnary(uo.NodeType, uo.ClrType, uo.SqlType, new SqlUnary(SqlNodeType.OuterJoinedValue, value2.ClrType, value2.SqlType, value2.HasValue, value2.SourceExpression), uo.SourceExpression));
}
if (unary.Operand.NodeType == SqlNodeType.TypeCase)
{
SqlTypeCase @case = (SqlTypeCase)unary.Operand;
return new SqlUnary(uo.NodeType, uo.ClrType, uo.SqlType, new SqlUnary(SqlNodeType.OuterJoinedValue, @case.Discriminator.ClrType, @case.Discriminator.SqlType, @case.Discriminator, @case.SourceExpression), uo.SourceExpression);
}
}
}
uo.Operand = this.ConvertToFetchedExpression(uo.Operand);
if (((uo.NodeType == SqlNodeType.Not) || (uo.NodeType == SqlNodeType.Not2V)) && (uo.Operand.NodeType == SqlNodeType.Value))
{
SqlValue value3 = (SqlValue)uo.Operand;
return this.sql.Value(typeof(bool), value3.SqlType, !((bool)value3.Value), value3.IsClientSpecified, value3.SourceExpression);
}
if (uo.NodeType == SqlNodeType.Not2V)
{
if (SqlExpressionNullability.CanBeNull(uo.Operand) != false)
{
SqlSearchedCase left = new SqlSearchedCase(typeof(int), new SqlWhen[] { new SqlWhen(uo.Operand, this.sql.ValueFromObject(1, false, uo.SourceExpression)) }, this.sql.ValueFromObject(0, false, uo.SourceExpression), uo.SourceExpression);
return this.sql.Binary(SqlNodeType.EQ, left, this.sql.ValueFromObject(0, false, uo.SourceExpression));
}
return this.sql.Unary(SqlNodeType.Not, uo.Operand);
}
if ((uo.NodeType == SqlNodeType.Convert) && (uo.Operand.NodeType == SqlNodeType.Value))
{
SqlValue value4 = (SqlValue)uo.Operand;
return this.sql.Value(uo.ClrType, uo.SqlType, DBConvert.ChangeType(value4.Value, uo.ClrType), value4.IsClientSpecified, value4.SourceExpression);
}
if ((uo.NodeType != SqlNodeType.IsNull) && (uo.NodeType != SqlNodeType.IsNotNull))
{
if (uo.NodeType == SqlNodeType.Treat)
{
return this.ApplyTreat(this.VisitExpression(uo.Operand), uo.ClrType);
}
return uo;
}
if (SqlExpressionNullability.CanBeNull(uo.Operand) == false)
{
return this.sql.ValueFromObject(uo.NodeType == SqlNodeType.IsNotNull, false, uo.SourceExpression);
}
SqlExpression operand = uo.Operand;
SqlNodeType nodeType = operand.NodeType;
if (nodeType <= SqlNodeType.Element)
{
switch (nodeType)
{
case SqlNodeType.ClientCase:
{
SqlClientCase case3 = (SqlClientCase)uo.Operand;
List<SqlExpression> matches = new List<SqlExpression>();
List<SqlExpression> values = new List<SqlExpression>();
foreach (SqlClientWhen when in case3.Whens)
{
matches.Add(when.Match);
values.Add(this.VisitUnaryOperator(this.sql.Unary(uo.NodeType, when.Value, when.Value.SourceExpression)));
}
return this.sql.Case(case3.ClrType, case3.Expression, matches, values, case3.SourceExpression);
}
case SqlNodeType.ClientParameter:
return uo;
case SqlNodeType.ClientQuery:
{
SqlClientQuery query = (SqlClientQuery)operand;
if (query.Query.NodeType != SqlNodeType.Element)
{
return this.sql.ValueFromObject(uo.NodeType == SqlNodeType.IsNotNull, false, uo.SourceExpression);
}
operand = this.sql.SubSelect(SqlNodeType.Exists, query.Query.Select);
if (uo.NodeType == SqlNodeType.IsNull)
{
operand = this.sql.Unary(SqlNodeType.Not, operand, operand.SourceExpression);
}
return operand;
}
case SqlNodeType.Element:
operand = this.sql.SubSelect(SqlNodeType.Exists, ((SqlSubSelect)operand).Select);
if (uo.NodeType == SqlNodeType.IsNull)
{
operand = this.sql.Unary(SqlNodeType.Not, operand, operand.SourceExpression);
}
return operand;
}
return uo;
}
switch (nodeType)
{
case SqlNodeType.OptionalValue:
uo.Operand = ((SqlOptionalValue)operand).HasValue;
return uo;
case SqlNodeType.TypeCase:
{
SqlTypeCase case4 = (SqlTypeCase)uo.Operand;
List<SqlExpression> list3 = new List<SqlExpression>();
List<SqlExpression> list4 = new List<SqlExpression>();
foreach (SqlTypeCaseWhen when2 in case4.Whens)
{
SqlUnary unary2 = new SqlUnary(uo.NodeType, uo.ClrType, uo.SqlType, when2.TypeBinding, when2.TypeBinding.SourceExpression);
SqlExpression item = this.VisitUnaryOperator(unary2);
if (item is SqlNew)
{
throw Error.DidNotExpectTypeBinding();
}
list3.Add(when2.Match);
list4.Add(item);
}
return this.sql.Case(uo.ClrType, case4.Discriminator, list3, list4, case4.SourceExpression);
}
case SqlNodeType.Value:
{
SqlValue value5 = (SqlValue)uo.Operand;
return this.sql.Value(typeof(bool), this.typeProvider.From(typeof(int)), (value5.Value == null) == (uo.NodeType == SqlNodeType.IsNull), value5.IsClientSpecified, uo.SourceExpression);
}
}
return uo;
}
internal override SqlUserQuery VisitUserQuery(SqlUserQuery suq)
{
this.disableInclude = true;
return base.VisitUserQuery(suq);
}
}
private class SqlFetcher : SqlVisitor
{
readonly List<SqlTable> tables;
SqlFetcher()
{
tables = new List<SqlTable>();
}
public static List<SqlTable> FetchTables(SqlNode node)
{
var instance = new SqlFetcher();
instance.Visit(node);
return instance.tables;
}
internal override SqlTable VisitTable(SqlTable tab)
{
tables.Add(tab);
return base.VisitTable(tab);
}
}
}
}
| |
//
// Copyright (c) XSharp B.V. All Rights Reserved.
// Licensed under the Apache License, Version 2.0.
// See License.txt in the project root for license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Utilities;
using XSharpModel;
using Microsoft.VisualStudio.Shell;
using System.Windows.Media;
using LanguageService.SyntaxTree;
using LanguageService.CodeAnalysis.XSharp.SyntaxParser;
using Microsoft.VisualStudio;
using LanguageService.CodeAnalysis.XSharp;
using Microsoft.VisualStudio.Text.Tagging;
#if ! ASYNCCOMPLETION
namespace XSharp.LanguageService
{
partial class XSharpCompletionSource : ICompletionSource
{
private ITextBuffer _buffer;
private bool _disposed = false;
private XSharpCompletionSourceProvider _provider;
private XFile _file;
private bool _showTabs;
private bool _keywordsInAll;
private IBufferTagAggregatorFactoryService aggregator;
private XSharpDialect _dialect;
private CompletionHelpers helpers ;
internal static bool StringEquals(string lhs, string rhs)
{
if (string.Equals(lhs, rhs, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
public XSharpCompletionSource(XSharpCompletionSourceProvider provider, ITextBuffer buffer, IBufferTagAggregatorFactoryService aggregator, XFile file)
{
_provider = provider;
_buffer = buffer;
_file = file;
var prj = _file.Project.ProjectNode;
_dialect = _file.Project.Dialect;
helpers = new CompletionHelpers(_dialect, provider.GlyphService, file, !prj.ParseOptions.CaseSensitive);
this.aggregator = aggregator;
}
internal static void WriteOutputMessage(string strMessage)
{
if (XSettings.EnableCodeCompletionLog && XSettings.EnableLogging )
{
XSettings.LogMessage(strMessage);
}
}
public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
{
WriteOutputMessage("-->> AugmentCompletionSessions");
try
{
if (XSettings.DisableCodeCompletion)
return;
XSharpModel.ModelWalker.Suspend();
if (_disposed)
throw new ObjectDisposedException("XSharpCompletionSource");
_showTabs = XSettings.EditorCompletionListTabs;
_keywordsInAll = XSettings.EditorKeywordsInAll;
// Where does the StartSession has been triggered ?
ITextSnapshot snapshot = _buffer.CurrentSnapshot;
var triggerPoint = (SnapshotPoint)session.GetTriggerPoint(snapshot);
if (triggerPoint == null)
return;
// What is the character were it starts ?
var line = triggerPoint.GetContainingLine();
//var triggerposinline = triggerPoint.Position - 2 - line.Start;
//var afterChar = line.GetText()[triggerposinline];
//if (afterChar == ' ' || afterChar == '\t')
// return;
// The "parameters" coming from CommandFilter
uint cmd = 0;
char typedChar = '\0';
bool autoType = false;
session.Properties.TryGetProperty(XsCompletionProperties.Command, out cmd);
VSConstants.VSStd2KCmdID nCmdId = (VSConstants.VSStd2KCmdID)cmd;
session.Properties.TryGetProperty(XsCompletionProperties.Char, out typedChar);
session.Properties.TryGetProperty(XsCompletionProperties.AutoType, out autoType);
bool showInstanceMembers = (typedChar == ':') || ((typedChar == '.') && _file.Project.ParseOptions.AllowDotForInstanceMembers);
////////////////////////////////////////////
//
SnapshotSpan lineSpan = new SnapshotSpan(line.Start, line.Length);
SnapshotPoint caret = triggerPoint;
var tagAggregator = aggregator.CreateTagAggregator<IClassificationTag>(_buffer);
var tags = tagAggregator.GetTags(lineSpan);
IMappingTagSpan<IClassificationTag> lastTag = null;
foreach (var tag in tags)
{
//tagList.Add(tag);
SnapshotPoint ptStart = tag.Span.Start.GetPoint(_buffer, PositionAffinity.Successor).Value;
SnapshotPoint ptEnd = tag.Span.End.GetPoint(_buffer, PositionAffinity.Successor).Value;
if ((ptStart != null) && (ptEnd != null))
{
if (caret.Position >= ptEnd)
{
lastTag = tag;
}
}
}
if (lastTag != null)
{
var name = lastTag.Tag.ClassificationType.Classification.ToLower();
// No Intellisense in Comment
if (name == "comment" || name == "xsharp.text")
return;
}
////////////////////////////////////////////
SnapshotPoint start = triggerPoint;
var applicableTo = snapshot.CreateTrackingSpan(new SnapshotSpan(start, triggerPoint), SpanTrackingMode.EdgeInclusive);
//
if (_file == null)
{
// Uhh !??, Something went wrong
return;
}
// The Completion list we are building
XCompletionList compList = new XCompletionList(_file);
XCompletionList kwdList = new XCompletionList(_file);
IXTypeSymbol type = null;
if (session.Properties.ContainsProperty(XsCompletionProperties.Type))
{
type = (IXTypeSymbol)session.Properties[XsCompletionProperties.Type];
}
// Start of Process
string filterText = "";
// Check if we can get the member where we are
// Standard TokenList Creation (based on colon Selector )
bool includeKeywords;
session.Properties.TryGetProperty(XsCompletionProperties.IncludeKeywords, out includeKeywords);
CompletionState state;
var member = session.TextView.FindMember(triggerPoint);
var location = session.TextView.TextBuffer.FindLocation(triggerPoint);
if (location == null)
return;
var tokenList = XSharpTokenTools.GetTokenList(location, out state, includeKeywords);
// We might be here due to a COMPLETEWORD command, so we have no typedChar
// but we "may" have a incomplete word like System.String.To
// Try to Guess what TypedChar could be
if (typedChar == '\0' && autoType)
{
if (tokenList.Count > 0)
{
string extract = tokenList[tokenList.Count - 1].Text;
typedChar = extract[extract.Length - 1];
if ((typedChar != '.') && (typedChar != ':'))
{
if (tokenList.Count == 1)
{
//
filterText = tokenList[0].Text;
int dotPos = extract.LastIndexOf(".");
if (dotPos > -1)
{
string startToken = extract.Substring(0, dotPos);
filterText = extract.Substring(dotPos + 1);
typedChar = '.';
tokenList[0].Text = startToken + ".";
}
}
else
{
// So, we get the last Token as a Filter
filterText = tokenList[tokenList.Count - 1].Text;
}
// Include the filter as the text to replace
start -= filterText.Length;
applicableTo = snapshot.CreateTrackingSpan(new SnapshotSpan(start, triggerPoint), SpanTrackingMode.EdgeInclusive);
}
}
}
bool dotSelector = (typedChar == '.');
// TODO: Based on the Project.Settings, we should add the Vulcan.VO namespace
int tokenType = XSharpLexer.UNRECOGNIZED;
var symbol = XSharpLookup.RetrieveElement(location, tokenList, CompletionState.General, out var notProcessed).FirstOrDefault();
var memberName = "";
// Check for members, locals etc and convert the type of these to IXTypeSymbol
if (symbol != null)
{
if (symbol is IXTypeSymbol xtype)
{
type = xtype;
}
else if (symbol is IXMemberSymbol xmember)
{
var typeName = xmember.TypeName;
if (xmember is XSourceMemberSymbol sourcemem)
{
type = sourcemem.File.FindType(typeName);
}
else
{
type = location.FindType(typeName);
}
memberName = xmember.Name;
}
else if (symbol is IXVariableSymbol xvar)
{
var typeName = "";
if (xvar is XSourceUndeclaredVariableSymbol)
{
type = null;
state = CompletionState.General;
filterText = xvar.Name;
}
else if (xvar is XSourceVariableSymbol sourcevar)
{
typeName = sourcevar.TypeName;
if (sourcevar.ResolvedType != null)
{
type = sourcevar.ResolvedType;
typeName = type.FullName;
}
else
{
type = sourcevar.File.FindType(typeName);
}
}
else if (xvar is XPEParameterSymbol par)
{
typeName = par.TypeName;
type = location.FindType(typeName);
}
memberName = xvar.Name;
}
else if (symbol.Kind == Kind.Keyword)
{
filterText = symbol.Name;
}
else if (symbol.Kind == Kind.Namespace)
{
filterText = symbol.Name+".";
}
if (type != null)
{
switch (type.FullName)
{
case XSharpTypeNames.XSharpUsual:
case XSharpTypeNames.VulcanUsual:
type = null;
break;
}
}
session.Properties[XsCompletionProperties.Type] = type;
}
if (type == null)
{
showInstanceMembers = false;
}
if ((dotSelector || state != CompletionState.None) )
{
if (string.IsNullOrEmpty(filterText) && type ==null)
{
filterText = helpers.TokenListAsString(tokenList);
if (filterText.Length > 0 && !filterText.EndsWith(".") && state != CompletionState.General)
filterText += ".";
}
if (type == null && state.HasFlag(CompletionState.Namespaces))
{
helpers.AddNamespaces(compList, location, filterText);
}
if (type == null && state.HasFlag(CompletionState.Interfaces))
{
helpers.AddTypeNames(compList, location, filterText, afterDot:true, onlyInterfaces: true);
helpers.AddXSharpKeywordTypeNames(kwdList, filterText);
}
if (type == null && state.HasFlag(CompletionState.Types) )
{
helpers.AddTypeNames(compList, location, filterText, afterDot: true, onlyInterfaces: false);
helpers.AddXSharpKeywordTypeNames(kwdList, filterText);
}
if (state.HasFlag(CompletionState.StaticMembers))
{
if (type != null && symbol is IXTypeSymbol)
{
// First we need to keep only the text AFTER the last dot
int dotPos = filterText.LastIndexOf('.');
filterText = filterText.Substring(dotPos + 1, filterText.Length - dotPos - 1);
helpers.BuildCompletionListMembers(location, compList, type, Modifiers.Public, true, filterText);
}
}
if (type.IsVoStruct() && typedChar == '.')
{
// vostruct or union in other assembly
showInstanceMembers = true;
filterText = "";
}
if (state.HasFlag(CompletionState.InstanceMembers) )
{
showInstanceMembers = true;
filterText = "";
}
}
if (showInstanceMembers )
{
// Member call
if (type != null)
{
Modifiers visibleAs = Modifiers.Public;
if (type is XSourceTypeSymbol sourceType && sourceType.File.Project == member.File.Project)
{
visibleAs = Modifiers.Internal;
switch (memberName.ToLower())
{
case "self":
case "this":
visibleAs = Modifiers.Private;
break;
case "super":
visibleAs = Modifiers.Protected;
break;
default:
if (member.ParentName == type.FullName)
{
visibleAs = Modifiers.Private;
}
break;
}
}
// Now, Fill the CompletionList with the available members, from there
helpers.BuildCompletionListMembers(location, compList, type, visibleAs, false, filterText);
}
}
//
if (!dotSelector && !showInstanceMembers)
{
switch (tokenType)
{
case XSharpLexer.USING:
// It can be a namespace
helpers.AddNamespaces(compList, location, filterText);
break;
case XSharpLexer.AS:
case XSharpLexer.IS:
case XSharpLexer.REF:
case XSharpLexer.INHERIT:
// It can be a namespace
helpers.AddNamespaces(compList, location, filterText);
// It can be Type, FullyQualified
// we should also walk all the USINGs, and the current Namespace if any, to search Types
helpers.AddTypeNames(compList, location, filterText, onlyInterfaces: false, afterDot: false);
//
helpers.AddXSharpKeywordTypeNames(kwdList, filterText);
break;
case XSharpLexer.IMPLEMENTS:
// It can be a namespace
helpers.AddNamespaces(compList, location, filterText);
helpers.AddTypeNames(compList, location, filterText,onlyInterfaces: true, afterDot: false);
break;
default:
//if (state.HasFlag(CompletionState.General))
//{
// filterText = notProcessed;
// helpers.AddGenericCompletion(compList, location, filterText);
//}
break;
}
}
if ((kwdList.Count > 0) && _keywordsInAll /*&& XSettings.CompleteKeywords*/)
{
foreach (var item in kwdList.Values)
compList.Add(item);
}
// Sort in alphabetical order
// and put in the SelectionList
var values = compList.Values;
// Create the All Tab
completionSets.Add(new CompletionSet("All", "All", applicableTo, values, Enumerable.Empty<Completion>()));
if (_showTabs)
{
helpers.BuildTabs(compList, completionSets, applicableTo);
}
// Keywords are ALWAYS in a separate Tab anyway
if (kwdList.Count > 0)
{
completionSets.Add(new CompletionSet("Keywords", "Keywords", applicableTo, kwdList.Values, Enumerable.Empty<Completion>()));
}
}
catch (Exception ex)
{
XSettings.LogException(ex, "AugmentCompletionSessions failed");
}
finally
{
XSharpModel.ModelWalker.Resume();
}
WriteOutputMessage("<<-- AugmentCompletionSessions");
}
public void Dispose()
{
if (!_disposed)
{
// Was missing, but doesn't solved the Deadlock with Intellisense
GC.SuppressFinalize(this);
_disposed = true;
}
}
}
}
#endif
| |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using GitMind.ApplicationHandling.Installation.StarMenuHandling;
using GitMind.Common.MessageDialogs;
using GitMind.Common.ProgressHandling;
using GitMind.Common.Tracking;
using GitMind.Utils;
using GitMind.Utils.Git;
using Microsoft.Win32;
namespace GitMind.ApplicationHandling.Installation
{
internal class Installer : IInstaller
{
private readonly ICommandLine commandLine;
public static readonly string ProductGuid = "0000278d-5c40-4973-aad9-1c33196fd1a2";
private static readonly string UninstallSubKey =
$"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{{{ProductGuid}}}_is1";
private static readonly string UninstallRegKey = "HKEY_CURRENT_USER\\" + UninstallSubKey;
private static readonly string subFolderContextMenuPath =
"Software\\Classes\\Folder\\shell\\gitmind";
private static readonly string subDirectoryBackgroundContextMenuPath =
"Software\\Classes\\Directory\\Background\\shell\\gitmind";
private static readonly string folderContextMenuPath =
"HKEY_CURRENT_USER\\" + subFolderContextMenuPath;
private static readonly string directoryContextMenuPath =
"HKEY_CURRENT_USER\\" + subDirectoryBackgroundContextMenuPath;
private static readonly string folderCommandContextMenuPath =
folderContextMenuPath + "\\command";
private static readonly string directoryCommandContextMenuPath =
directoryContextMenuPath + "\\command";
private static readonly string SetupTitle = "GitMind - Setup";
private static readonly string ProgramShortcutFileName = ProgramInfo.ProgramName + ".lnk";
private readonly ICmd cmd;
private readonly IGitEnvironmentService gitEnvironmentService;
private readonly IProgressService progressService;
public Installer(
ICommandLine commandLine,
ICmd cmd,
IGitEnvironmentService gitEnvironmentService,
IProgressService progressService)
{
this.commandLine = commandLine;
this.cmd = cmd;
this.gitEnvironmentService = gitEnvironmentService;
this.progressService = progressService;
}
public bool InstallOrUninstall()
{
if (commandLine.IsInstall && !commandLine.IsSilent)
{
Track.Request("Install-Normal");
InstallNormal();
return false;
}
else if (commandLine.IsInstall && commandLine.IsSilent)
{
Track.Request("Install-Silent");
Task.Run(async () => await InstallSilentAsync(s => Log.Info(s)).ConfigureAwait(false)).Wait();
if (commandLine.IsRunInstalled)
{
StartInstalled();
}
return false;
}
else if (commandLine.IsUninstall && !commandLine.IsSilent)
{
Track.Event("Uninstall-Normal");
UninstallNormal();
return false;
}
else if (commandLine.IsUninstall && commandLine.IsSilent)
{
Track.Request("Uninstall-Silent");
UninstallSilent();
return false;
}
return true;
}
private void InstallNormal()
{
Log.Usage("Install normal.");
InstallDialog dialog = null;
bool isCanceled = false;
async Task InstallActionAsync()
{
if (!EnsureNoOtherInstancesAreRunning(dialog))
{
isCanceled = true;
return;
}
dialog.Message = "";
dialog.IsButtonsVisible = false;
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
using (Progress progress = progressService.ShowDialog("", dialog))
{
await InstallSilentAsync(text => dispatcher.Invoke(() => progress.SetText(text)));
}
Message.ShowInfo(
"Setup has finished installing GitMind.",
SetupTitle,
dialog);
Log.Usage("Installed normal.");
}
dialog = new InstallDialog(
null,
"Welcome to the GitMind setup.\n\n" +
" This will:\n" +
" - Add a GitMind shortcut in the Start Menu.\n" +
" - Add a 'GitMind' context menu item in Windows File Explorer.\n" +
" - Make GitMind command available in Command Prompt window.\n\n" +
"Click Install to install GitMind or Cancel to exit Setup.",
SetupTitle,
(InstallActionAsync)
);
bool? showDialog = dialog.ShowDialog();
Log.Debug($"Dialog result: {showDialog}");
if (showDialog != true)
{
Log.Usage("Install canceled.");
Log.Warn("Dialog canceled");
return;
}
if (isCanceled)
{
Log.Usage("Install canceled.");
Log.Warn("Is canceled");
return;
}
StartInstalled();
}
private void StartInstalled()
{
string targetPath = ProgramInfo.GetInstallFilePath();
cmd.Start(targetPath, "/run /d:Open");
}
private static bool EnsureNoOtherInstancesAreRunning(Window owner = null)
{
while (true)
{
bool created = false;
using (new Mutex(true, ProductGuid, out created))
{
if (created)
{
return true;
}
Log.Debug("GitMind instance is already running, needs to be closed.");
if (!Message.ShowAskOkCancel(
"Please close all instances of GitMind before continue the installation.",
"GitMind",
owner))
{
return false;
}
Thread.Sleep(1000);
}
}
}
private async Task<R> InstallSilentAsync(Action<string> progress)
{
Log.Usage("Installing ...");
progress("Installing GitMind ...");
string path = CopyFileToProgramFiles();
await Task.Yield();
AddUninstallSupport(path);
await Task.Yield();
CreateStartMenuShortcut(path);
await Task.Yield();
AddToPathVariable(path);
await Task.Yield();
AddFolderContextMenu();
await Task.Yield();
progress.Invoke("Downloading git ...");
R gitResult = await gitEnvironmentService.InstallGitAsync(progress);
Log.Usage("Installed");
if (gitResult.IsFaulted)
{
Track.Error($"Failed to install git {gitResult}");
return gitResult;
}
return R.Ok;
}
private void UninstallNormal()
{
Log.Usage("Uninstall normal");
if (IsInstalledInstance())
{
// The running instance is the file, which should be deleted and would block deletion,
// Copy the file to temp and run uninstallation from that file.
string tempPath = CopyFileToTemp();
Log.Debug("Start uninstaller in tmp folder");
cmd.Start(tempPath, "/uninstall");
return;
}
if (!Message.ShowAskOkCancel(
"Do you want to uninstall GitMind?"))
{
return;
}
if (!EnsureNoOtherInstancesAreRunning())
{
return;
}
UninstallSilent();
Log.Usage("Uninstalled normal");
Message.ShowInfo("Uninstallation of GitMind is completed.");
}
private void UninstallSilent()
{
Log.Debug("Uninstalling...");
DeleteProgramFilesFolder();
DeleteProgramDataFolder();
DeleteStartMenuShortcut();
DeleteInPathVariable();
DeleteFolderContextMenu();
DeleteUninstallSupport();
Log.Debug("Uninstalled");
}
private string CopyFileToProgramFiles()
{
string sourcePath = ProgramInfo.GetCurrentInstancePath();
Version sourceVersion = ProgramInfo.GetVersion(sourcePath);
string targetFolder = ProgramInfo.GetProgramFolderPath();
EnsureDirectoryIsCreated(targetFolder);
string targetPath = ProgramInfo.GetInstallFilePath();
try
{
if (sourcePath != targetPath)
{
CopyFile(sourcePath, targetPath);
WriteInstalledVersion(sourceVersion);
}
}
catch (Exception e) when (e.IsNotFatal())
{
Log.Debug($"Failed to copy {sourcePath} to target {targetPath} {e.Message}");
try
{
string oldFilePath = ProgramInfo.GetTempFilePath();
Log.Debug($"Moving {targetPath} to {oldFilePath}");
File.Move(targetPath, oldFilePath);
Log.Debug($"Moved {targetPath} to target {oldFilePath}");
CopyFile(sourcePath, targetPath);
WriteInstalledVersion(sourceVersion);
}
catch (Exception ex) when (e.IsNotFatal())
{
Log.Exception(ex, $"Failed to copy {sourcePath} to target {targetPath}");
throw;
}
}
return targetPath;
}
private void WriteInstalledVersion(Version sourceVersion)
{
try
{
string path = ProgramInfo.GetVersionFilePath();
File.WriteAllText(path, sourceVersion.ToString());
Log.Debug($"Installed {sourceVersion}");
}
catch (Exception e)
{
Log.Exception(e, "Failed to write version");
}
}
private static void CopyFile(string sourcePath, string targetPath)
{
// Not using File.Copy, to avoid copying possible "downloaded from internet flag"
byte[] fileData = File.ReadAllBytes(sourcePath);
File.WriteAllBytes(targetPath, fileData);
Log.Debug($"Copied {sourcePath} to target {targetPath}");
}
private static void EnsureDirectoryIsCreated(string targetFolder)
{
if (!Directory.Exists(targetFolder))
{
Directory.CreateDirectory(targetFolder);
}
}
private static void DeleteProgramFilesFolder()
{
Thread.Sleep(300);
string folderPath = ProgramInfo.GetProgramFolderPath();
for (int i = 0; i < 5; i++)
{
try
{
if (Directory.Exists(folderPath))
{
Directory.Delete(folderPath, true);
}
else
{
return;
}
}
catch (Exception e) when (e.IsNotFatal())
{
Log.Debug($"Failed to delete {folderPath}");
Thread.Sleep(1000);
}
}
}
private static void DeleteProgramDataFolder()
{
string programDataFolderPath = ProgramInfo.GetProgramDataFolderPath();
if (Directory.Exists(programDataFolderPath))
{
Directory.Delete(programDataFolderPath, true);
}
}
private static void CreateStartMenuShortcut(string pathToExe)
{
string shortcutLocation = GetStartMenuShortcutPath();
StartMenuWrapper.CreateStartMenuShortCut(
shortcutLocation,
pathToExe,
"",
pathToExe,
ProgramInfo.ProgramName);
}
private static void DeleteStartMenuShortcut()
{
string shortcutLocation = GetStartMenuShortcutPath();
File.Delete(shortcutLocation);
}
private static void AddToPathVariable(string path)
{
string folderPath = Path.GetDirectoryName(path);
string keyName = @"Environment\";
string pathsVariables = (string)Registry.CurrentUser.OpenSubKey(keyName)
.GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
pathsVariables = pathsVariables.Trim();
if (!pathsVariables.Contains(folderPath))
{
if (!string.IsNullOrEmpty(pathsVariables) && !pathsVariables.EndsWith(";"))
{
pathsVariables += ";";
}
pathsVariables += folderPath;
Environment.SetEnvironmentVariable(
"PATH", pathsVariables, EnvironmentVariableTarget.User);
}
}
private static void DeleteInPathVariable()
{
string programFilesFolderPath = ProgramInfo.GetProgramFolderPath();
string keyName = @"Environment\";
string pathsVariables = (string)Registry.CurrentUser.OpenSubKey(keyName)
.GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
string pathPart = programFilesFolderPath;
if (pathsVariables.Contains(pathPart))
{
pathsVariables = pathsVariables.Replace(pathPart, "");
pathsVariables = pathsVariables.Replace(";;", ";");
pathsVariables = pathsVariables.Trim(";".ToCharArray());
Registry.SetValue("HKEY_CURRENT_USER\\" + keyName, "PATH", pathsVariables);
}
}
private static void AddUninstallSupport(string path)
{
string version = ProgramInfo.GetVersion(path).ToString();
Registry.SetValue(UninstallRegKey, "DisplayName", ProgramInfo.ProgramName);
Registry.SetValue(UninstallRegKey, "DisplayIcon", path);
Registry.SetValue(UninstallRegKey, "Publisher", "Michael Reichenauer");
Registry.SetValue(UninstallRegKey, "DisplayVersion", version);
Registry.SetValue(UninstallRegKey, "UninstallString", path + " /uninstall");
Registry.SetValue(UninstallRegKey, "EstimatedSize", 1000);
}
private static void DeleteUninstallSupport()
{
try
{
Registry.CurrentUser.DeleteSubKeyTree(UninstallSubKey);
}
catch (Exception e) when (e.IsNotFatal())
{
Log.Exception(e, "Failed to delete uninstall support");
}
}
private static void AddFolderContextMenu()
{
string programFilePath = ProgramInfo.GetInstallFilePath();
Registry.SetValue(folderContextMenuPath, "", ProgramInfo.ProgramName);
Registry.SetValue(folderContextMenuPath, "Icon", programFilePath);
Registry.SetValue(folderCommandContextMenuPath, "", "\"" + programFilePath + "\" \"/d:%1\"");
Registry.SetValue(directoryContextMenuPath, "", ProgramInfo.ProgramName);
Registry.SetValue(directoryContextMenuPath, "Icon", programFilePath);
Registry.SetValue(
directoryCommandContextMenuPath, "", "\"" + programFilePath + "\" \"/d:%V\"");
}
private static void DeleteFolderContextMenu()
{
try
{
Registry.CurrentUser.DeleteSubKeyTree(subFolderContextMenuPath);
Registry.CurrentUser.DeleteSubKeyTree(subDirectoryBackgroundContextMenuPath);
}
catch (Exception e) when (e.IsNotFatal())
{
Log.Exception(e, "Failed to delete folder context menu");
}
}
private static bool IsInstalledInstance()
{
string folderPath = Path.GetDirectoryName(ProgramInfo.GetCurrentInstancePath());
string programFolderGitMind = ProgramInfo.GetProgramFolderPath();
return folderPath == programFolderGitMind;
}
private static string CopyFileToTemp()
{
string sourcePath = ProgramInfo.GetCurrentInstancePath();
string targetPath = Path.Combine(Path.GetTempPath(), ProgramInfo.ProgramFileName);
File.Copy(sourcePath, targetPath, true);
return targetPath;
}
public static string GetStartMenuShortcutPath()
{
string commonStartMenuPath = Environment.GetFolderPath(
Environment.SpecialFolder.StartMenu);
string startMenuPath = Path.Combine(commonStartMenuPath, "Programs");
return Path.Combine(startMenuPath, ProgramShortcutFileName);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Linq.Expressions;
using System;
using System.Diagnostics;
using System.Dynamic;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
namespace IronPython.Runtime.Types {
using Ast = Expression;
using AstUtils = Microsoft.Scripting.Ast.Utils;
[PythonType("field#")]
public sealed class ReflectedField : PythonTypeSlot, ICodeFormattable {
private readonly NameType _nameType;
internal readonly FieldInfo/*!*/ _info;
internal const string UpdateValueTypeFieldWarning = "Setting field {0} on value type {1} may result in updating a copy. Use {1}.{0}.SetValue(instance, value) if this is safe. For more information help({1}.{0}.SetValue).";
public ReflectedField(FieldInfo/*!*/ info, NameType nameType) {
Debug.Assert(info != null);
_nameType = nameType;
_info = info;
}
public ReflectedField(FieldInfo/*!*/ info)
: this(info, NameType.PythonField) {
}
#region Public Python APIs
public FieldInfo Info {
[PythonHidden]
get {
return _info;
}
}
/// <summary>
/// Convenience function for users to call directly
/// </summary>
public object GetValue(CodeContext context, object instance) {
object value;
if (TryGetValue(context, instance, DynamicHelpers.GetPythonType(instance), out value)) {
return value;
}
throw new InvalidOperationException("cannot get field");
}
/// <summary>
/// This function can be used to set a field on a value type without emitting a warning. Otherwise it is provided only to have symmetry with properties which have GetValue/SetValue for supporting explicitly implemented interfaces.
///
/// Setting fields on value types usually warns because it can silently fail to update the value you expect. For example consider this example where Point is a value type with the public fields X and Y:
///
/// arr = System.Array.CreateInstance(Point, 10)
/// arr[0].X = 42
/// print arr[0].X
///
/// prints 0. This is because reading the value from the array creates a copy of the value. Setting the value then mutates the copy and the array does not get updated. The same problem exists when accessing members of a class.
/// </summary>
public void SetValue(CodeContext context, object instance, object value) {
if (!TrySetValueWorker(context, instance, DynamicHelpers.GetPythonType(instance), value, true)) {
throw new InvalidOperationException("cannot set field");
}
}
public void __set__(CodeContext/*!*/ context, object instance, object value) {
if (instance == null && _info.IsStatic) {
DoSet(context, null, value, false);
} else if (!_info.IsStatic) {
DoSet(context, instance, value, false);
} else {
throw PythonOps.AttributeErrorForReadonlyAttribute(_info.DeclaringType.Name, _info.Name);
}
}
[SpecialName]
public void __delete__(object instance) {
throw PythonOps.AttributeErrorForBuiltinAttributeDeletion(_info.DeclaringType.Name, _info.Name);
}
public string __doc__ {
get {
return DocBuilder.DocOneInfo(_info);
}
}
public PythonType FieldType {
[PythonHidden]
get {
return DynamicHelpers.GetPythonTypeFromType(_info.FieldType);
}
}
#endregion
#region Internal APIs
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
PerfTrack.NoteEvent(PerfTrack.Categories.Fields, this);
if (instance == null) {
value = _info.IsStatic ? _info.GetValue(null) : this;
} else {
value = _info.GetValue(context.LanguageContext.Binder.Convert(instance, _info.DeclaringType));
}
return true;
}
internal override bool GetAlwaysSucceeds {
get {
return true;
}
}
internal override bool CanOptimizeGets {
get {
return !_info.IsLiteral;
}
}
internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) {
return TrySetValueWorker(context, instance, owner, value, false);
}
private bool TrySetValueWorker(CodeContext context, object instance, PythonType owner, object value, bool suppressWarning) {
if (ShouldSetOrDelete(owner)) {
DoSet(context, instance, value, suppressWarning);
return true;
}
return false;
}
internal override bool IsSetDescriptor(CodeContext context, PythonType owner) {
// field is settable if it is not readonly
return (_info.Attributes & FieldAttributes.InitOnly) == 0 && !_info.IsLiteral;
}
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) {
if (ShouldSetOrDelete(owner)) {
throw PythonOps.AttributeErrorForBuiltinAttributeDeletion(_info.DeclaringType.Name, _info.Name);
}
return false;
}
internal override bool IsAlwaysVisible {
get {
return _nameType == NameType.PythonField;
}
}
internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, DynamicMetaObject instance, DynamicMetaObject/*!*/ owner, ConditionalBuilder/*!*/ builder) {
if (!_info.IsPublic || _info.DeclaringType.ContainsGenericParameters) {
// fallback to reflection
base.MakeGetExpression(binder, codeContext, instance, owner, builder);
} else if (instance == null) {
if (_info.IsStatic) {
builder.FinishCondition(AstUtils.Convert(Ast.Field(null, _info), typeof(object)));
} else {
builder.FinishCondition(Ast.Constant(this));
}
} else {
builder.FinishCondition(
AstUtils.Convert(
Ast.Field(
binder.ConvertExpression(
instance.Expression,
_info.DeclaringType,
ConversionResultKind.ExplicitCast,
new PythonOverloadResolverFactory(binder, codeContext)
),
_info
),
typeof(object)
)
);
}
}
#endregion
#region Private helpers
private void DoSet(CodeContext context, object instance, object val, bool suppressWarning) {
PerfTrack.NoteEvent(PerfTrack.Categories.Fields, this);
if (_info.IsInitOnly || _info.IsLiteral) {
throw PythonOps.AttributeErrorForReadonlyAttribute(_info.DeclaringType.Name, _info.Name);
} else if (!suppressWarning && instance != null && instance.GetType().IsValueType) {
PythonOps.Warn(context, PythonExceptions.RuntimeWarning, UpdateValueTypeFieldWarning, _info.Name, _info.DeclaringType.Name);
}
_info.SetValue(instance, context.LanguageContext.Binder.Convert(val, _info.FieldType));
}
private bool ShouldSetOrDelete(PythonType type) {
// statics must be assigned through their type, not a derived type. Non-statics can
// be assigned through their instances.
return (type is PythonType dt && _info.DeclaringType == dt.UnderlyingSystemType) || !_info.IsStatic || _info.IsLiteral || _info.IsInitOnly;
}
#endregion
#region ICodeFormattable Members
public string/*!*/ __repr__(CodeContext/*!*/ context) {
return string.Format("<field# {0} on {1}>", _info.Name, _info.DeclaringType.Name);
}
#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.
/******************************************************************************
* 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 FloorDouble()
{
var test = new SimpleUnaryOpTest__FloorDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.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();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.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();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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 SimpleUnaryOpTest__FloorDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
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<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__FloorDouble testClass)
{
var result = Avx.Floor(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__FloorDouble testClass)
{
fixed (Vector256<Double>* pFld1 = &_fld1)
{
var result = Avx.Floor(
Avx.LoadVector256((Double*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Vector256<Double> _clsVar1;
private Vector256<Double> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__FloorDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public SimpleUnaryOpTest__FloorDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Floor(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Floor(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Floor(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Floor), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Floor), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Floor), new Type[] { typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Floor(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Double>* pClsVar1 = &_clsVar1)
{
var result = Avx.Floor(
Avx.LoadVector256((Double*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var result = Avx.Floor(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var result = Avx.Floor(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var result = Avx.Floor(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__FloorDouble();
var result = Avx.Floor(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__FloorDouble();
fixed (Vector256<Double>* pFld1 = &test._fld1)
{
var result = Avx.Floor(
Avx.LoadVector256((Double*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Floor(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Double>* pFld1 = &_fld1)
{
var result = Avx.Floor(
Avx.LoadVector256((Double*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Floor(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.Floor(
Avx.LoadVector256((Double*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(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(Vector256<Double> op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Floor(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(Math.Floor(firstOp[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Floor)}<Double>(Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DBSchemaRow.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
sealed internal class DbSchemaRow {
internal const string SchemaMappingUnsortedIndex = "SchemaMapping Unsorted Index";
DbSchemaTable schemaTable;
DataRow dataRow;
static internal DbSchemaRow[] GetSortedSchemaRows(DataTable dataTable, bool returnProviderSpecificTypes) { // MDAC 60609
DataColumn sortindex= dataTable.Columns[SchemaMappingUnsortedIndex];
if (null == sortindex) { // WebData 100390
sortindex = new DataColumn(SchemaMappingUnsortedIndex, typeof(Int32)); // MDAC 67050
dataTable.Columns.Add(sortindex);
}
int count = dataTable.Rows.Count;
for (int i = 0; i < count; ++i) {
dataTable.Rows[i][sortindex] = i;
};
DbSchemaTable schemaTable = new DbSchemaTable(dataTable, returnProviderSpecificTypes);
const DataViewRowState rowStates = DataViewRowState.Unchanged | DataViewRowState.Added | DataViewRowState.ModifiedCurrent;
DataRow[] dataRows = dataTable.Select(null, "ColumnOrdinal ASC", rowStates);
Debug.Assert(null != dataRows, "GetSchemaRows: unexpected null dataRows");
DbSchemaRow[] schemaRows = new DbSchemaRow[dataRows.Length];
for (int i = 0; i < dataRows.Length; ++i) {
schemaRows[i] = new DbSchemaRow(schemaTable, dataRows[i]);
}
return schemaRows;
}
internal DbSchemaRow(DbSchemaTable schemaTable, DataRow dataRow) {
this.schemaTable = schemaTable;
this.dataRow = dataRow;
}
internal DataRow DataRow {
get {
return dataRow;
}
}
internal string ColumnName {
get {
Debug.Assert(null != schemaTable.ColumnName, "no column ColumnName");
object value = dataRow[schemaTable.ColumnName, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
return "";
}
/*set {
Debug.Assert(null != schemaTable.ColumnName, "missing column ColumnName");
dataRow[schemaTable.ColumnName] = value;
}*/
}
//internal Int32 Ordinal {
/*get {
Debug.Assert(null != schemaTable.Ordinal, "no column Ordinal");
return Convert.ToInt32(dataRow[schemaTable.Ordinal, DataRowVersion.Default], CultureInfo.InvariantCulture);
}*/
/*set {
Debug.Assert(null != schemaTable.Ordinal, "missing column Ordinal");
dataRow[schemaTable.Ordinal] = value;
}*/
//}
internal Int32 Size {
get {
Debug.Assert(null != schemaTable.Size, "no column Size");
object value = dataRow[schemaTable.Size, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToInt32(value, CultureInfo.InvariantCulture);
}
return 0;
}
/*set {
Debug.Assert(null != schemaTable.Size, "missing column Size");
dataRow[schemaTable.Size] = value;
}*/
}
internal string BaseColumnName {
get {
if (null != schemaTable.BaseColumnName) {
object value = dataRow[schemaTable.BaseColumnName, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
return "";
}
/*set {
Debug.Assert(null != schemaTable.BaseColumnName, "missing column BaseColumnName");
dataRow[schemaTable.BaseColumnName] = value;
}*/
}
internal string BaseServerName {
get {
if (null != schemaTable.BaseServerName) {
object value = dataRow[schemaTable.BaseServerName, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
return "";
}
/*set {
Debug.Assert(null != schemaTable.BaseServerName, "missing column BaseServerName");
dataRow[schemaTable.BaseServerName] = value;
}*/
}
internal string BaseCatalogName {
get {
if (null != schemaTable.BaseCatalogName) {
object value = dataRow[schemaTable.BaseCatalogName, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
return "";
}
/*set {
Debug.Assert(null != schemaTable.BaseCatalogName, "missing column BaseCatalogName");
dataRow[schemaTable.BaseCatalogName] = value;
}*/
}
internal string BaseSchemaName {
get {
if (null != schemaTable.BaseSchemaName) {
object value = dataRow[schemaTable.BaseSchemaName, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
return "";
}
/*set {
Debug.Assert(null != schemaTable.BaseSchemaName, "missing column BaseSchemaName");
dataRow[schemaTable.BaseSchemaName] = value;
}*/
}
internal string BaseTableName {
get {
if (null != schemaTable.BaseTableName) {
object value = dataRow[schemaTable.BaseTableName, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
return "";
}
/*set {
Debug.Assert(null != schemaTable.BaseTableName, "missing column BaseTableName");
dataRow[schemaTable.BaseTableName] = value;
}*/
}
internal bool IsAutoIncrement {
get {
if (null != schemaTable.IsAutoIncrement) {
object value = dataRow[schemaTable.IsAutoIncrement, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return false;
}
/*set {
Debug.Assert(null != schemaTable.IsAutoIncrement, "missing column IsAutoIncrement");
dataRow[schemaTable.IsAutoIncrement] = (bool)value;
}*/
}
internal bool IsUnique {
get {
if (null != schemaTable.IsUnique) {
object value = dataRow[schemaTable.IsUnique, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return false;
}
/*set {
Debug.Assert(null != schemaTable.IsUnique, "missing column IsUnique");
dataRow[schemaTable.IsUnique] = (bool)value;
}*/
}
internal bool IsRowVersion {
get {
if (null != schemaTable.IsRowVersion) {
object value = dataRow[schemaTable.IsRowVersion, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return false;
}
/*set {
Debug.Assert(null != schemaTable.IsRowVersion, "missing column IsRowVersion");
dataRow[schemaTable.IsRowVersion] = value;
}*/
}
internal bool IsKey {
get {
if (null != schemaTable.IsKey) {
object value = dataRow[schemaTable.IsKey, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return false;
}
/*set {
Debug.Assert(null != schemaTable.IsKey, "missing column IsKey");
dataRow[schemaTable.IsKey] = value;
}*/
}
// consider: just do comparison directly -> (object)(baseColumnName) == (object)(columnName)
//internal bool IsAliased {
/*get {
if (null != schemaTable.IsAliased) { // MDAC 62336
object value = dataRow[schemaTable.IsAliased, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return false;
}*/
/*set {
Debug.Assert(null != schemaTable.IsAliased, "missing column IsAliased");
dataRow[schemaTable.IsAliased] = value;
}*/
//}
internal bool IsExpression {
get {
if (null != schemaTable.IsExpression) { // MDAC 62336
object value = dataRow[schemaTable.IsExpression, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return false;
}
/*set {
Debug.Assert(null != schemaTable.IsExpression, "missing column IsExpression");
dataRow[schemaTable.IsExpression] = value;
}*/
}
//internal bool IsIdentity {
/*get {
if (null != schemaTable.IsIdentity) { // MDAC 62336
object value = dataRow[schemaTable.IsIdentity, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return false;
}*/
/*set {
Debug.Assert(null != schemaTable.IsIdentity, "missing column IsIdentity");
dataRow[schemaTable.IsIdentity] = value;
}*/
//}
internal bool IsHidden {
get {
if (null != schemaTable.IsHidden) { // MDAC 62336
object value = dataRow[schemaTable.IsHidden, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return false;
}
/*set {
Debug.Assert(null != schemaTable.IsHidden, "missing column IsHidden");
dataRow[schemaTable.IsHidden] = value;
}*/
}
internal bool IsLong {
get {
if (null != schemaTable.IsLong) { // MDAC 62336
object value = dataRow[schemaTable.IsLong, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return false;
}
/*set {
Debug.Assert(null != schemaTable.IsLong, "missing column IsHidden");
dataRow[schemaTable.IsLong] = value;
}*/
}
internal bool IsReadOnly {
get {
if (null != schemaTable.IsReadOnly) { // MDAC 62336
object value = dataRow[schemaTable.IsReadOnly, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return false;
}
/*set {
Debug.Assert(null != schemaTable.IsReadOnly, "missing column IsReadOnly");
dataRow[schemaTable.IsReadOnly] = value;
}*/
}
internal System.Type DataType {
get {
if (null != schemaTable.DataType) {
object value = dataRow[schemaTable.DataType, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return(System.Type) value;
}
}
return null;
}
/*set {
Debug.Assert(null != schemaTable.DataType, "missing column DataType");
dataRow[schemaTable.DataType] = value;
}*/
}
internal bool AllowDBNull {
get {
if (null != schemaTable.AllowDBNull) {
object value = dataRow[schemaTable.AllowDBNull, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
}
return true;
}
/*set {
Debug.Assert(null != schemaTable.AllowDBNull, "missing column MaybeNull");
dataRow[schemaTable.AllowDBNull] = value;
}*/
}
/*internal Int32 ProviderType {
get {
if (null != schemaTable.ProviderType) {
object value = dataRow[schemaTable.ProviderType, DataRowVersion.Default];
if (!Convert.IsDBNull(value)) {
return Convert.ToInt32(value);
}
}
return 0;
}
set {
Debug.Assert(null != schemaTable.ProviderType, "missing column ProviderType");
dataRow[schemaTable.ProviderType] = value;
}
}*/
internal Int32 UnsortedIndex {
get {
return (Int32) dataRow[schemaTable.UnsortedIndex, DataRowVersion.Default];
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
public static class CookieTest
{
[Fact]
public static void Ctor_Empty_Success()
{
Cookie c = new Cookie();
}
[Fact]
public static void Ctor_NameValue_Success()
{
Cookie c = new Cookie("hello", "goodbye");
Assert.Equal("hello", c.Name);
Assert.Equal("goodbye", c.Value);
}
[Fact]
public static void Ctor_NameValuePath_Success()
{
Cookie c = new Cookie("hello", "goodbye", "foo");
Assert.Equal("hello", c.Name);
Assert.Equal("goodbye", c.Value);
Assert.Equal("foo", c.Path);
}
[Fact]
public static void Ctor_NameValuePathDomain_Success()
{
Cookie c = new Cookie("hello", "goodbye", "foo", "bar");
Assert.Equal("hello", c.Name);
Assert.Equal("goodbye", c.Value);
Assert.Equal("foo", c.Path);
Assert.Equal("bar", c.Domain);
}
[Fact]
public static void CookieException_Ctor_Success()
{
CookieException c = new CookieException();
}
[Fact]
public static void Comment_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Comment);
c.Comment = "hello";
Assert.Equal("hello", c.Comment);
c.Comment = null;
Assert.Equal(string.Empty, c.Comment);
}
[Fact]
public static void CommentUri_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Null(c.CommentUri);
c.CommentUri = new Uri("http://hello.com");
Assert.Equal(new Uri("http://hello.com"), c.CommentUri);
}
[Fact]
public static void HttpOnly_GetSet_Success()
{
Cookie c = new Cookie();
Assert.False(c.HttpOnly);
c.HttpOnly = true;
Assert.True(c.HttpOnly);
c.HttpOnly = false;
Assert.False(c.HttpOnly);
}
[Fact]
public static void Discard_GetSet_Success()
{
Cookie c = new Cookie();
Assert.False(c.Discard);
c.Discard = true;
Assert.True(c.Discard);
c.Discard = false;
Assert.False(c.Discard);
}
[Fact]
public static void Domain_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Domain);
c.Domain = "hello";
Assert.Equal("hello", c.Domain);
c.Domain = null;
Assert.Equal(string.Empty, c.Domain);
}
[Fact]
public static void Expired_GetSet_Success()
{
Cookie c = new Cookie();
Assert.False(c.Expired);
c.Expires = DateTime.Now.AddDays(-1);
Assert.True(c.Expired);
c.Expires = DateTime.Now.AddDays(1);
Assert.False(c.Expired);
c.Expired = true;
Assert.True(c.Expired);
c.Expired = true;
Assert.True(c.Expired);
}
[Fact]
public static void Expires_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(c.Expires, DateTime.MinValue);
DateTime dt = DateTime.Now;
c.Expires = dt;
Assert.Equal(dt, c.Expires);
}
[Fact]
public static void Name_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Name);
c.Name = "hello";
Assert.Equal("hello", c.Name);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("$hello")]
[InlineData("hello ")]
[InlineData("hello\t")]
[InlineData("hello\r")]
[InlineData("hello\n")]
[InlineData("hello=")]
[InlineData("hello;")]
[InlineData("hello,")]
public static void Name_Set_Invalid(string name)
{
Cookie c = new Cookie();
Assert.Throws<CookieException>(() => c.Name = name);
}
[Fact]
public static void Path_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Path);
c.Path = "path";
Assert.Equal("path", c.Path);
c.Path = null;
Assert.Equal(string.Empty, c.Path);
}
[Fact]
public static void Port_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Port);
c.Port = "\"80 110, 1050, 1090 ,110\"";
Assert.Equal("\"80 110, 1050, 1090 ,110\"", c.Port);
c.Port = null;
Assert.Equal(string.Empty, c.Port);
}
[Theory]
[InlineData("80, 80 \"")] //No leading quotation mark
[InlineData("\"80, 80")] //No trailing quotation mark
[InlineData("\"80, hello\"")] //Invalid port
[InlineData("\"-1, hello\"")] //Port out of range, < 0
[InlineData("\"80, 65536\"")] //Port out of range, > 65535
public static void Port_Set_Invalid(string port)
{
Cookie c = new Cookie();
Assert.Throws<CookieException>(() => c.Port = port);
}
[Fact]
public static void Secure_GetSet_Success()
{
Cookie c = new Cookie();
Assert.False(c.Secure);
c.Secure = true;
Assert.True(c.Secure);
c.Secure = false;
Assert.False(c.Secure);
}
[Fact]
public static void Timestamp_GetSet_Success()
{
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0); //DateTime.Now changes as the test runs
Cookie c = new Cookie();
Assert.True(c.TimeStamp >= dt);
}
[Fact]
public static void Value_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.Value);
c.Value = "hello";
Assert.Equal("hello", c.Value);
c.Value = null;
Assert.Equal(string.Empty, c.Value);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.NetcoreUwp)]
public static void Value_PassNullToCtor_GetReturnsEmptyString_net46()
{
var cookie = new Cookie("SomeName", null);
// Cookie.Value returns null on full framework.
Assert.Null(cookie.Value);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void Value_PassNullToCtor_GetReturnsEmptyString()
{
var cookie = new Cookie("SomeName", null);
// Cookie.Value returns empty string on netcore.
Assert.Equal(string.Empty, cookie.Value);
}
[Fact]
public static void Version_GetSet_Success()
{
Cookie c = new Cookie();
Assert.Equal(0, c.Version);
c.Version = 100;
Assert.Equal(100, c.Version);
}
[Fact]
public static void Version_Set_Invalid()
{
Cookie c = new Cookie();
Assert.Throws<ArgumentOutOfRangeException>(() => c.Version = -1);
}
[Fact]
public static void Equals_Compare_Success()
{
Cookie c1 = new Cookie();
Cookie c2 = new Cookie("name", "value");
Cookie c3 = new Cookie("Name", "value");
Cookie c4 = new Cookie("different-name", "value");
Cookie c5 = new Cookie("name", "different-value");
Cookie c6 = new Cookie("name", "value", "path");
Cookie c7 = new Cookie("name", "value", "path");
Cookie c8 = new Cookie("name", "value", "different-path");
Cookie c9 = new Cookie("name", "value", "path", "domain");
Cookie c10 = new Cookie("name", "value", "path", "domain");
Cookie c11 = new Cookie("name", "value", "path", "Domain");
Cookie c12 = new Cookie("name", "value", "path", "different-domain");
Cookie c13 = new Cookie("name", "value", "path", "domain") { Version = 5 };
Cookie c14 = new Cookie("name", "value", "path", "domain") { Version = 5 };
Cookie c15 = new Cookie("name", "value", "path", "domain") { Version = 100 };
Assert.False(c2.Equals(null));
Assert.False(c2.Equals(""));
Assert.NotEqual(c1, c2);
Assert.Equal(c2, c3);
Assert.Equal(c3, c2);
Assert.NotEqual(c2, c4);
Assert.NotEqual(c2, c5);
Assert.NotEqual(c2, c6);
Assert.NotEqual(c2, c9);
Assert.NotEqual(c2.GetHashCode(), c4.GetHashCode());
Assert.NotEqual(c2.GetHashCode(), c5.GetHashCode());
Assert.NotEqual(c2.GetHashCode(), c6.GetHashCode());
Assert.NotEqual(c2.GetHashCode(), c9.GetHashCode());
Assert.Equal(c6, c7);
Assert.NotEqual(c6, c8);
Assert.NotEqual(c6, c9);
Assert.NotEqual(c6.GetHashCode(), c8.GetHashCode());
Assert.NotEqual(c6.GetHashCode(), c9.GetHashCode());
Assert.Equal(c9, c10);
Assert.Equal(c9, c11);
Assert.NotEqual(c9, c12);
Assert.Equal(c9.GetHashCode(), c10.GetHashCode());
Assert.NotEqual(c9.GetHashCode(), c12.GetHashCode());
Assert.Equal(c13, c14);
Assert.NotEqual(c13, c15);
Assert.Equal(c13.GetHashCode(), c14.GetHashCode());
Assert.NotEqual(c13.GetHashCode(), c15.GetHashCode());
}
[Fact]
public static void ToString_Compare_Success()
{
Cookie c = new Cookie();
Assert.Equal(string.Empty, c.ToString());
c = new Cookie("name", "value");
Assert.Equal("name=value", c.ToString());
c = new Cookie("name", "value", "path", "domain");
c.Port = "\"80\"";
c.Version = 100;
Assert.Equal("$Version=100; name=value; $Path=path; $Domain=domain; $Port=\"80\"", c.ToString());
c.Version = 0;
Assert.Equal("name=value; $Path=path; $Domain=domain; $Port=\"80\"", c.ToString());
c.Port = "";
Assert.Equal("name=value; $Path=path; $Domain=domain; $Port", c.ToString());
}
}
}
| |
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Documents;
using NUnit.Framework;
using System;
using System.IO;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AttributeSource = Lucene.Net.Util.AttributeSource;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using StringField = StringField;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
[TestFixture]
public class TestDocumentWriter : LuceneTestCase
{
private Directory dir;
[SetUp]
public override void SetUp()
{
base.SetUp();
dir = NewDirectory();
}
[TearDown]
public override void TearDown()
{
dir.Dispose();
base.TearDown();
}
[Test]
public virtual void Test()
{
Assert.IsTrue(dir != null);
}
[Test]
public virtual void TestAddDocument()
{
Document testDoc = new Document();
DocHelper.SetupDoc(testDoc);
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
writer.AddDocument(testDoc);
writer.Commit();
SegmentCommitInfo info = writer.NewestSegment();
writer.Dispose();
//After adding the document, we should be able to read it back in
SegmentReader reader = new SegmentReader(info, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, NewIOContext(Random));
Assert.IsTrue(reader != null);
Document doc = reader.Document(0);
Assert.IsTrue(doc != null);
//System.out.println("Document: " + doc);
IIndexableField[] fields = doc.GetFields("textField2");
Assert.IsTrue(fields != null && fields.Length == 1);
Assert.IsTrue(fields[0].GetStringValue().Equals(DocHelper.FIELD_2_TEXT, StringComparison.Ordinal));
Assert.IsTrue(fields[0].IndexableFieldType.StoreTermVectors);
fields = doc.GetFields("textField1");
Assert.IsTrue(fields != null && fields.Length == 1);
Assert.IsTrue(fields[0].GetStringValue().Equals(DocHelper.FIELD_1_TEXT, StringComparison.Ordinal));
Assert.IsFalse(fields[0].IndexableFieldType.StoreTermVectors);
fields = doc.GetFields("keyField");
Assert.IsTrue(fields != null && fields.Length == 1);
Assert.IsTrue(fields[0].GetStringValue().Equals(DocHelper.KEYWORD_TEXT, StringComparison.Ordinal));
fields = doc.GetFields(DocHelper.NO_NORMS_KEY);
Assert.IsTrue(fields != null && fields.Length == 1);
Assert.IsTrue(fields[0].GetStringValue().Equals(DocHelper.NO_NORMS_TEXT, StringComparison.Ordinal));
fields = doc.GetFields(DocHelper.TEXT_FIELD_3_KEY);
Assert.IsTrue(fields != null && fields.Length == 1);
Assert.IsTrue(fields[0].GetStringValue().Equals(DocHelper.FIELD_3_TEXT, StringComparison.Ordinal));
// test that the norms are not present in the segment if
// omitNorms is true
foreach (FieldInfo fi in reader.FieldInfos)
{
if (fi.IsIndexed)
{
Assert.IsTrue(fi.OmitsNorms == (reader.GetNormValues(fi.Name) == null));
}
}
reader.Dispose();
}
[Test]
public virtual void TestPositionIncrementGap()
{
Analyzer analyzer = new AnalyzerAnonymousInnerClassHelper();
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
Document doc = new Document();
doc.Add(NewTextField("repeated", "repeated one", Field.Store.YES));
doc.Add(NewTextField("repeated", "repeated two", Field.Store.YES));
writer.AddDocument(doc);
writer.Commit();
SegmentCommitInfo info = writer.NewestSegment();
writer.Dispose();
SegmentReader reader = new SegmentReader(info, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, NewIOContext(Random));
DocsAndPositionsEnum termPositions = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), "repeated", new BytesRef("repeated"));
Assert.IsTrue(termPositions.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
int freq = termPositions.Freq;
Assert.AreEqual(2, freq);
Assert.AreEqual(0, termPositions.NextPosition());
Assert.AreEqual(502, termPositions.NextPosition());
reader.Dispose();
}
private class AnalyzerAnonymousInnerClassHelper : Analyzer
{
protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
return new TokenStreamComponents(new MockTokenizer(reader, MockTokenizer.WHITESPACE, false));
}
public override int GetPositionIncrementGap(string fieldName)
{
return 500;
}
}
[Test]
public virtual void TestTokenReuse()
{
Analyzer analyzer = new AnalyzerAnonymousInnerClassHelper2(this);
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
Document doc = new Document();
doc.Add(NewTextField("f1", "a 5 a a", Field.Store.YES));
writer.AddDocument(doc);
writer.Commit();
SegmentCommitInfo info = writer.NewestSegment();
writer.Dispose();
SegmentReader reader = new SegmentReader(info, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, NewIOContext(Random));
DocsAndPositionsEnum termPositions = MultiFields.GetTermPositionsEnum(reader, reader.LiveDocs, "f1", new BytesRef("a"));
Assert.IsTrue(termPositions.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
int freq = termPositions.Freq;
Assert.AreEqual(3, freq);
Assert.AreEqual(0, termPositions.NextPosition());
Assert.IsNotNull(termPositions.GetPayload());
Assert.AreEqual(6, termPositions.NextPosition());
Assert.IsNull(termPositions.GetPayload());
Assert.AreEqual(7, termPositions.NextPosition());
Assert.IsNull(termPositions.GetPayload());
reader.Dispose();
}
private class AnalyzerAnonymousInnerClassHelper2 : Analyzer
{
private readonly TestDocumentWriter outerInstance;
public AnalyzerAnonymousInnerClassHelper2(TestDocumentWriter outerInstance)
{
this.outerInstance = outerInstance;
}
protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new TokenFilterAnonymousInnerClassHelper(this, tokenizer));
}
private class TokenFilterAnonymousInnerClassHelper : TokenFilter
{
private readonly AnalyzerAnonymousInnerClassHelper2 outerInstance;
public TokenFilterAnonymousInnerClassHelper(AnalyzerAnonymousInnerClassHelper2 outerInstance, Tokenizer tokenizer)
: base(tokenizer)
{
this.outerInstance = outerInstance;
first = true;
termAtt = AddAttribute<ICharTermAttribute>();
payloadAtt = AddAttribute<IPayloadAttribute>();
posIncrAtt = AddAttribute<IPositionIncrementAttribute>();
}
internal bool first;
internal AttributeSource.State state;
public sealed override bool IncrementToken()
{
if (state != null)
{
RestoreState(state);
payloadAtt.Payload = null;
posIncrAtt.PositionIncrement = 0;
termAtt.SetEmpty().Append("b");
state = null;
return true;
}
bool hasNext = m_input.IncrementToken();
if (!hasNext)
{
return false;
}
if (char.IsDigit(termAtt.Buffer[0]))
{
posIncrAtt.PositionIncrement = termAtt.Buffer[0] - '0';
}
if (first)
{
// set payload on first position only
payloadAtt.Payload = new BytesRef(new byte[] { 100 });
first = false;
}
// index a "synonym" for every token
state = CaptureState();
return true;
}
public sealed override void Reset()
{
base.Reset();
first = true;
state = null;
}
internal readonly ICharTermAttribute termAtt;
internal readonly IPayloadAttribute payloadAtt;
internal readonly IPositionIncrementAttribute posIncrAtt;
}
}
[Test]
public virtual void TestPreAnalyzedField()
{
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document doc = new Document();
doc.Add(new TextField("preanalyzed", new TokenStreamAnonymousInnerClassHelper(this)));
writer.AddDocument(doc);
writer.Commit();
SegmentCommitInfo info = writer.NewestSegment();
writer.Dispose();
SegmentReader reader = new SegmentReader(info, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, NewIOContext(Random));
DocsAndPositionsEnum termPositions = reader.GetTermPositionsEnum(new Term("preanalyzed", "term1"));
Assert.IsTrue(termPositions.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(1, termPositions.Freq);
Assert.AreEqual(0, termPositions.NextPosition());
termPositions = reader.GetTermPositionsEnum(new Term("preanalyzed", "term2"));
Assert.IsTrue(termPositions.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(2, termPositions.Freq);
Assert.AreEqual(1, termPositions.NextPosition());
Assert.AreEqual(3, termPositions.NextPosition());
termPositions = reader.GetTermPositionsEnum(new Term("preanalyzed", "term3"));
Assert.IsTrue(termPositions.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(1, termPositions.Freq);
Assert.AreEqual(2, termPositions.NextPosition());
reader.Dispose();
}
private class TokenStreamAnonymousInnerClassHelper : TokenStream
{
private readonly TestDocumentWriter outerInstance;
public TokenStreamAnonymousInnerClassHelper(TestDocumentWriter outerInstance)
{
this.outerInstance = outerInstance;
tokens = new string[] { "term1", "term2", "term3", "term2" };
index = 0;
termAtt = AddAttribute<ICharTermAttribute>();
}
private string[] tokens;
private int index;
private ICharTermAttribute termAtt;
public sealed override bool IncrementToken()
{
if (index == tokens.Length)
{
return false;
}
else
{
ClearAttributes();
termAtt.SetEmpty().Append(tokens[index++]);
return true;
}
}
}
/// <summary>
/// Test adding two fields with the same name, but
/// with different term vector setting (LUCENE-766).
/// </summary>
[Test]
public virtual void TestMixedTermVectorSettingsSameField()
{
Document doc = new Document();
// f1 first without tv then with tv
doc.Add(NewStringField("f1", "v1", Field.Store.YES));
FieldType customType2 = new FieldType(StringField.TYPE_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorOffsets = true;
customType2.StoreTermVectorPositions = true;
doc.Add(NewField("f1", "v2", customType2));
// f2 first with tv then without tv
doc.Add(NewField("f2", "v1", customType2));
doc.Add(NewStringField("f2", "v2", Field.Store.YES));
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
writer.AddDocument(doc);
writer.Dispose();
TestUtil.CheckIndex(dir);
IndexReader reader = DirectoryReader.Open(dir);
// f1
Terms tfv1 = reader.GetTermVectors(0).GetTerms("f1");
Assert.IsNotNull(tfv1);
Assert.AreEqual(2, tfv1.Count, "the 'with_tv' setting should rule!");
// f2
Terms tfv2 = reader.GetTermVectors(0).GetTerms("f2");
Assert.IsNotNull(tfv2);
Assert.AreEqual(2, tfv2.Count, "the 'with_tv' setting should rule!");
reader.Dispose();
}
/// <summary>
/// Test adding two fields with the same name, one indexed
/// the other stored only. The omitNorms and omitTermFreqAndPositions setting
/// of the stored field should not affect the indexed one (LUCENE-1590)
/// </summary>
[Test]
public virtual void TestLUCENE_1590()
{
Document doc = new Document();
// f1 has no norms
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
FieldType customType2 = new FieldType();
customType2.IsStored = true;
doc.Add(NewField("f1", "v1", customType));
doc.Add(NewField("f1", "v2", customType2));
// f2 has no TF
FieldType customType3 = new FieldType(TextField.TYPE_NOT_STORED);
customType3.IndexOptions = IndexOptions.DOCS_ONLY;
Field f = NewField("f2", "v1", customType3);
doc.Add(f);
doc.Add(NewField("f2", "v2", customType2));
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
writer.AddDocument(doc);
writer.ForceMerge(1); // be sure to have a single segment
writer.Dispose();
TestUtil.CheckIndex(dir);
SegmentReader reader = GetOnlySegmentReader(DirectoryReader.Open(dir));
FieldInfos fi = reader.FieldInfos;
// f1
Assert.IsFalse(fi.FieldInfo("f1").HasNorms, "f1 should have no norms");
Assert.AreEqual(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, fi.FieldInfo("f1").IndexOptions, "omitTermFreqAndPositions field bit should not be set for f1");
// f2
Assert.IsTrue(fi.FieldInfo("f2").HasNorms, "f2 should have norms");
Assert.AreEqual(IndexOptions.DOCS_ONLY, fi.FieldInfo("f2").IndexOptions, "omitTermFreqAndPositions field bit should be set for f2");
reader.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.ComponentModel;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Components
{
/// <summary>
/// A factory for creating <see cref="EventCallback"/> and <see cref="EventCallback{T}"/>
/// instances.
/// </summary>
public sealed class EventCallbackFactory
{
/// <summary>
/// Returns the provided <paramref name="callback"/>. For internal framework use only.
/// </summary>
/// <param name="receiver"></param>
/// <param name="callback"></param>
/// <returns></returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public EventCallback Create(object receiver, EventCallback callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return callback;
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
public EventCallback Create(object receiver, Action callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return CreateCore(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
public EventCallback Create(object receiver, Action<object> callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return CreateCore(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
public EventCallback Create(object receiver, Func<Task> callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return CreateCore(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
public EventCallback Create(object receiver, Func<object, Task> callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return CreateCore(receiver, callback);
}
/// <summary>
/// Returns the provided <paramref name="callback"/>. For internal framework use only.
/// </summary>
/// <param name="receiver"></param>
/// <param name="callback"></param>
/// <returns></returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public EventCallback<TValue> Create<TValue>(object receiver, EventCallback callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return new EventCallback<TValue>(callback.Receiver, callback.Delegate);
}
/// <summary>
/// Returns the provided <paramref name="callback"/>. For internal framework use only.
/// </summary>
/// <param name="receiver"></param>
/// <param name="callback"></param>
/// <returns></returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public EventCallback<TValue> Create<TValue>(object receiver, EventCallback<TValue> callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return callback;
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
public EventCallback<TValue> Create<TValue>(object receiver, Action callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return CreateCore<TValue>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
public EventCallback<TValue> Create<TValue>(object receiver, Action<TValue> callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return CreateCore<TValue>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
public EventCallback<TValue> Create<TValue>(object receiver, Func<Task> callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return CreateCore<TValue>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
public EventCallback<TValue> Create<TValue>(object receiver, Func<TValue, Task> callback)
{
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
return CreateCore<TValue>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>. For internal framework use only.
/// </summary>
/// <param name="receiver"></param>
/// <param name="callback"></param>
/// <param name="value"></param>
/// <returns></returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public EventCallback<TValue> CreateInferred<TValue>(object receiver, Action<TValue> callback, TValue value)
{
return Create(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>. For internal framework use only.
/// </summary>
/// <param name="receiver"></param>
/// <param name="callback"></param>
/// <param name="value"></param>
/// <returns></returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public EventCallback<TValue> CreateInferred<TValue>(object receiver, Func<TValue, Task> callback, TValue value)
{
return Create(receiver, callback);
}
private EventCallback CreateCore(object receiver, MulticastDelegate callback)
{
return new EventCallback(callback?.Target as IHandleEvent ?? receiver as IHandleEvent, callback);
}
private EventCallback<TValue> CreateCore<TValue>(object receiver, MulticastDelegate callback)
{
return new EventCallback<TValue>(callback?.Target as IHandleEvent ?? receiver as IHandleEvent, callback);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using Content.Server.Access;
using Content.Server.AI.Pathfinding.Pathfinders;
using Content.Server.CPUJob.JobQueues;
using Content.Server.CPUJob.JobQueues.Queues;
using Content.Shared.Access.Systems;
using Content.Shared.GameTicking;
using Content.Shared.Physics;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Utility;
namespace Content.Server.AI.Pathfinding
{
/*
// TODO: IMO use rectangular symmetry reduction on the nodes with collision at all. (currently planned to be implemented via AiReachableSystem and expanded later).
alternatively store all rooms and have an alternative graph for humanoid mobs (same collision mask, needs access etc). You could also just path from room to room as needed.
// TODO: Longer term -> Handle collision layer changes?
TODO: Handle container entities so they're not tracked.
*/
/// <summary>
/// This system handles pathfinding graph updates as well as dispatches to the pathfinder
/// (90% of what it's doing is graph updates so not much point splitting the 2 roles)
/// </summary>
public sealed class PathfindingSystem : EntitySystem
{
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly IEntityManager _entityManager = default!;
[Dependency] private readonly AccessReaderSystem _accessReader = default!;
public IReadOnlyDictionary<GridId, Dictionary<Vector2i, PathfindingChunk>> Graph => _graph;
private readonly Dictionary<GridId, Dictionary<Vector2i, PathfindingChunk>> _graph = new();
private readonly PathfindingJobQueue _pathfindingQueue = new();
// Queued pathfinding graph updates
private readonly Queue<CollisionChangeMessage> _collidableUpdateQueue = new();
private readonly Queue<MoveEvent> _moveUpdateQueue = new();
private readonly Queue<AccessReaderChangeMessage> _accessReaderUpdateQueue = new();
private readonly Queue<TileRef> _tileUpdateQueue = new();
// Need to store previously known entity positions for collidables for when they move
private readonly Dictionary<EntityUid, PathfindingNode> _lastKnownPositions = new();
public const int TrackedCollisionLayers = (int)
(CollisionGroup.Impassable |
CollisionGroup.MobImpassable |
CollisionGroup.SmallImpassable |
CollisionGroup.VaultImpassable);
/// <summary>
/// Ask for the pathfinder to gimme somethin
/// </summary>
/// <param name="pathfindingArgs"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Job<Queue<TileRef>> RequestPath(PathfindingArgs pathfindingArgs, CancellationToken cancellationToken)
{
var startNode = GetNode(pathfindingArgs.Start);
var endNode = GetNode(pathfindingArgs.End);
var job = new AStarPathfindingJob(0.003, startNode, endNode, pathfindingArgs, cancellationToken);
_pathfindingQueue.EnqueueJob(job);
return job;
}
public override void Update(float frameTime)
{
base.Update(frameTime);
// Make sure graph is updated, then get pathfinders
ProcessGraphUpdates();
_pathfindingQueue.Process();
}
private void ProcessGraphUpdates()
{
var totalUpdates = 0;
foreach (var update in _collidableUpdateQueue)
{
if (!EntityManager.EntityExists(update.Owner)) continue;
if (update.CanCollide)
{
HandleEntityAdd(update.Owner);
}
else
{
HandleEntityRemove(update.Owner);
}
totalUpdates++;
}
_collidableUpdateQueue.Clear();
foreach (var update in _accessReaderUpdateQueue)
{
if (update.Enabled)
{
HandleEntityAdd(update.Sender);
}
else
{
HandleEntityRemove(update.Sender);
}
totalUpdates++;
}
_accessReaderUpdateQueue.Clear();
foreach (var tile in _tileUpdateQueue)
{
HandleTileUpdate(tile);
totalUpdates++;
}
_tileUpdateQueue.Clear();
var moveUpdateCount = Math.Max(50 - totalUpdates, 0);
// Other updates are high priority so for this we'll just defer it if there's a spike (explosion, etc.)
// If the move updates grow too large then we'll just do it
if (_moveUpdateQueue.Count > 100)
{
moveUpdateCount = _moveUpdateQueue.Count - 100;
}
moveUpdateCount = Math.Min(moveUpdateCount, _moveUpdateQueue.Count);
for (var i = 0; i < moveUpdateCount; i++)
{
HandleEntityMove(_moveUpdateQueue.Dequeue());
}
DebugTools.Assert(_moveUpdateQueue.Count < 1000);
}
public PathfindingChunk GetChunk(TileRef tile)
{
var chunkX = (int) (Math.Floor((float) tile.X / PathfindingChunk.ChunkSize) * PathfindingChunk.ChunkSize);
var chunkY = (int) (Math.Floor((float) tile.Y / PathfindingChunk.ChunkSize) * PathfindingChunk.ChunkSize);
var vector2i = new Vector2i(chunkX, chunkY);
if (_graph.TryGetValue(tile.GridIndex, out var chunks))
{
if (!chunks.ContainsKey(vector2i))
{
CreateChunk(tile.GridIndex, vector2i);
}
return chunks[vector2i];
}
var newChunk = CreateChunk(tile.GridIndex, vector2i);
return newChunk;
}
private PathfindingChunk CreateChunk(GridId gridId, Vector2i indices)
{
var newChunk = new PathfindingChunk(gridId, indices);
if (!_graph.ContainsKey(gridId))
{
_graph.Add(gridId, new Dictionary<Vector2i, PathfindingChunk>());
}
_graph[gridId].Add(indices, newChunk);
newChunk.Initialize(_mapManager.GetGrid(gridId));
return newChunk;
}
/// <summary>
/// Get the entity's tile position, then get the corresponding node
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public PathfindingNode GetNode(EntityUid entity)
{
var tile = _mapManager.GetGrid(EntityManager.GetComponent<TransformComponent>(entity).GridID).GetTileRef(EntityManager.GetComponent<TransformComponent>(entity).Coordinates);
return GetNode(tile);
}
/// <summary>
/// Return the corresponding PathfindingNode for this tile
/// </summary>
/// <param name="tile"></param>
/// <returns></returns>
public PathfindingNode GetNode(TileRef tile)
{
var chunk = GetChunk(tile);
var node = chunk.GetNode(tile);
return node;
}
public override void Initialize()
{
SubscribeLocalEvent<RoundRestartCleanupEvent>(Reset);
SubscribeLocalEvent<CollisionChangeMessage>(QueueCollisionChangeMessage);
SubscribeLocalEvent<MoveEvent>(QueueMoveEvent);
SubscribeLocalEvent<AccessReaderChangeMessage>(QueueAccessChangeMessage);
SubscribeLocalEvent<GridRemovalEvent>(HandleGridRemoval);
SubscribeLocalEvent<GridModifiedEvent>(QueueGridChange);
SubscribeLocalEvent<TileChangedEvent>(QueueTileChange);
// Handle all the base grid changes
// Anything that affects traversal (i.e. collision layer) is handled separately.
}
private void HandleTileUpdate(TileRef tile)
{
if (!_mapManager.GridExists(tile.GridIndex)) return;
var node = GetNode(tile);
node.UpdateTile(tile);
}
private void HandleGridRemoval(GridRemovalEvent ev)
{
if (_graph.ContainsKey(ev.GridId))
{
_graph.Remove(ev.GridId);
}
}
private void QueueGridChange(GridModifiedEvent ev)
{
foreach (var (position, _) in ev.Modified)
{
_tileUpdateQueue.Enqueue(ev.Grid.GetTileRef(position));
}
}
private void QueueTileChange(TileChangedEvent ev)
{
_tileUpdateQueue.Enqueue(ev.NewTile);
}
private void QueueAccessChangeMessage(AccessReaderChangeMessage message)
{
_accessReaderUpdateQueue.Enqueue(message);
}
/// <summary>
/// Tries to add the entity to the relevant pathfinding node
/// </summary>
/// The node will filter it to the correct category (if possible)
/// <param name="entity"></param>
private void HandleEntityAdd(EntityUid entity)
{
if (Deleted(entity) ||
_lastKnownPositions.ContainsKey(entity) ||
!EntityManager.TryGetComponent(entity, out IPhysBody? physics) ||
!PathfindingNode.IsRelevant(entity, physics))
{
return;
}
var grid = _mapManager.GetGrid(EntityManager.GetComponent<TransformComponent>(entity).GridID);
var tileRef = grid.GetTileRef(EntityManager.GetComponent<TransformComponent>(entity).Coordinates);
var chunk = GetChunk(tileRef);
var node = chunk.GetNode(tileRef);
node.AddEntity(entity, physics);
_lastKnownPositions.Add(entity, node);
}
private void HandleEntityRemove(EntityUid entity)
{
if (!_lastKnownPositions.TryGetValue(entity, out var node))
{
return;
}
node.RemoveEntity(entity);
_lastKnownPositions.Remove(entity);
}
private void QueueMoveEvent(ref MoveEvent moveEvent)
{
_moveUpdateQueue.Enqueue(moveEvent);
}
/// <summary>
/// When an entity moves around we'll remove it from its old node and add it to its new node (if applicable)
/// </summary>
/// <param name="moveEvent"></param>
private void HandleEntityMove(MoveEvent moveEvent)
{
// If we've moved to space or the likes then remove us.
if ((!EntityManager.EntityExists(moveEvent.Sender) ? EntityLifeStage.Deleted : EntityManager.GetComponent<MetaDataComponent>(moveEvent.Sender).EntityLifeStage) >= EntityLifeStage.Deleted ||
!EntityManager.TryGetComponent(moveEvent.Sender, out IPhysBody? physics) ||
!PathfindingNode.IsRelevant(moveEvent.Sender, physics) ||
moveEvent.NewPosition.GetGridId(EntityManager) == GridId.Invalid)
{
HandleEntityRemove(moveEvent.Sender);
return;
}
// Memory leak protection until grid parenting confirmed fix / you REALLY need the performance
var gridBounds = _mapManager.GetGrid(EntityManager.GetComponent<TransformComponent>(moveEvent.Sender).GridID).WorldBounds;
if (!gridBounds.Contains(EntityManager.GetComponent<TransformComponent>(moveEvent.Sender).WorldPosition))
{
HandleEntityRemove(moveEvent.Sender);
return;
}
// If we move from space to a grid we may need to start tracking it.
if (!_lastKnownPositions.TryGetValue(moveEvent.Sender, out var oldNode))
{
HandleEntityAdd(moveEvent.Sender);
return;
}
var newGridId = moveEvent.NewPosition.GetGridId(_entityManager);
if (newGridId == GridId.Invalid)
{
HandleEntityRemove(moveEvent.Sender);
return;
}
// The pathfinding graph is tile-based so first we'll check if they're on a different tile and if we need to update.
// If you get entities bigger than 1 tile wide you'll need some other system so god help you.
var newTile = _mapManager.GetGrid(newGridId).GetTileRef(moveEvent.NewPosition);
if (oldNode == null || oldNode.TileRef == newTile)
{
return;
}
var newNode = GetNode(newTile);
_lastKnownPositions[moveEvent.Sender] = newNode;
oldNode.RemoveEntity(moveEvent.Sender);
newNode.AddEntity(moveEvent.Sender, physics);
}
private void QueueCollisionChangeMessage(CollisionChangeMessage collisionMessage)
{
_collidableUpdateQueue.Enqueue(collisionMessage);
}
// TODO: Need to rethink the pathfinder utils (traversable etc.). Maybe just chuck them all in PathfindingSystem
// Otherwise you get the steerer using this and the pathfinders using a different traversable.
// Also look at increasing tile cost the more physics entities are on it
public bool CanTraverse(EntityUid entity, EntityCoordinates coordinates)
{
var gridId = coordinates.GetGridId(EntityManager);
var tile = _mapManager.GetGrid(gridId).GetTileRef(coordinates);
var node = GetNode(tile);
return CanTraverse(entity, node);
}
public bool CanTraverse(EntityUid entity, PathfindingNode node)
{
if (EntityManager.TryGetComponent(entity, out IPhysBody? physics) &&
(physics.CollisionMask & node.BlockedCollisionMask) != 0)
{
return false;
}
var access = _accessReader.FindAccessTags(entity);
foreach (var reader in node.AccessReaders)
{
if (!_accessReader.IsAllowed(reader, access))
{
return false;
}
}
return true;
}
public void Reset(RoundRestartCleanupEvent ev)
{
_graph.Clear();
_collidableUpdateQueue.Clear();
_moveUpdateQueue.Clear();
_accessReaderUpdateQueue.Clear();
_tileUpdateQueue.Clear();
_lastKnownPositions.Clear();
}
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.Xml;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Thrift.Collections;
namespace Thrift.Tests.Collections
{
// ReSharper disable once InconsistentNaming
[TestClass]
public class TCollectionsTests
{
//TODO: Add tests for IEnumerable with objects and primitive values inside
[TestMethod]
public void TCollection_List_Equals_Primitive_Test()
{
var collection1 = new List<int> {1,2,3};
var collection2 = new List<int> {1,2,3};
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsTrue(collection1.SequenceEqual(collection2));
}
[TestMethod]
public void TCollection_List_Equals_Primitive_Different_Test()
{
var collection1 = new List<int> { 1, 2, 3 };
var collection2 = new List<int> { 1, 2 };
Assert.IsFalse(TCollections.Equals(collection1, collection2));
Assert.IsFalse(collection1.SequenceEqual(collection2));
collection2.Add(4);
Assert.IsFalse(TCollections.Equals(collection1, collection2));
Assert.IsFalse(collection1.SequenceEqual(collection2));
}
[TestMethod]
public void TCollection_List_Equals_Objects_Test()
{
var collection1 = new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } };
var collection2 = new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } };
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsTrue(collection1.SequenceEqual(collection2));
}
[TestMethod]
public void TCollection_List_List_Equals_Objects_Test()
{
var collection1 = new List<List<ExampleClass>> { new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } } };
var collection2 = new List<List<ExampleClass>> { new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } } };
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsFalse(collection1.SequenceEqual(collection2)); // SequenceEqual() calls Equals() of the inner list instead of SequenceEqual()
}
[TestMethod]
public void TCollection_List_Equals_OneAndTheSameObject_Test()
{
var collection1 = new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } };
var collection2 = collection1;
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsTrue(collection1.SequenceEqual(collection2));
}
[TestMethod]
public void TCollection_Set_Equals_Primitive_Test()
{
var collection1 = new HashSet<int> {1,2,3};
var collection2 = new HashSet<int> {1,2,3};
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsTrue(collection1.SequenceEqual(collection2));
}
[TestMethod]
public void TCollection_Set_Equals_Primitive_Different_Test()
{
var collection1 = new HashSet<int> { 1, 2, 3 };
var collection2 = new HashSet<int> { 1, 2 };
Assert.IsFalse(TCollections.Equals(collection1, collection2));
Assert.IsFalse(collection1.SequenceEqual(collection2));
collection2.Add(4);
Assert.IsFalse(TCollections.Equals(collection1, collection2));
Assert.IsFalse(collection1.SequenceEqual(collection2));
}
[TestMethod]
public void TCollection_Set_Equals_Objects_Test()
{
var collection1 = new HashSet<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } };
var collection2 = new HashSet<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } };
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsTrue(collection1.SequenceEqual(collection2));
}
[TestMethod]
public void TCollection_Set_Set_Equals_Objects_Test()
{
var collection1 = new HashSet<HashSet<ExampleClass>> { new HashSet<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } } };
var collection2 = new HashSet<HashSet<ExampleClass>> { new HashSet<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } } };
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsFalse(collection1.SequenceEqual(collection2)); // SequenceEqual() calls Equals() of the inner list instead of SequenceEqual()
}
[TestMethod]
public void TCollection_Set_Equals_OneAndTheSameObject_Test()
{
var collection1 = new HashSet<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } };
var collection2 = collection1; // references to one and the same collection
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsTrue(collection1.SequenceEqual(collection2));
}
[TestMethod]
public void TCollection_Map_Equals_Primitive_Test()
{
var collection1 = new Dictionary<int, int> { [1] = 1, [2] = 2, [3] = 3 };
var collection2 = new Dictionary<int, int> { [1] = 1, [2] = 2, [3] = 3 };
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsTrue(collection1.SequenceEqual(collection2));
}
[TestMethod]
public void TCollection_Map_Equals_Primitive_Different_Test()
{
var collection1 = new Dictionary<int, int> { [1] = 1, [2] = 2, [3] = 3 };
var collection2 = new Dictionary<int, int> { [1] = 1, [2] = 2 };
Assert.IsFalse(TCollections.Equals(collection1, collection2));
Assert.IsFalse(collection1.SequenceEqual(collection2));
collection2[3] = 3;
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsTrue(collection1.SequenceEqual(collection2));
collection2[3] = 4;
Assert.IsFalse(TCollections.Equals(collection1, collection2));
}
[TestMethod]
public void TCollection_Map_Equals_Objects_Test()
{
var collection1 = new Dictionary<int, ExampleClass>
{
[1] = new ExampleClass { X = 1 },
[-1] = new ExampleClass { X = 2 }
};
var collection2 = new Dictionary<int, ExampleClass>
{
[1] = new ExampleClass { X = 1 },
[-1] = new ExampleClass { X = 2 }
};
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsTrue(collection1.SequenceEqual(collection2));
}
[TestMethod]
public void TCollection_Map_Map_Equals_Objects_Test()
{
var collection1 = new Dictionary<int, Dictionary<int, ExampleClass>>
{
[0] = new Dictionary<int, ExampleClass>
{
[1] = new ExampleClass { X = 1 },
[-1] = new ExampleClass { X = 2 }
}
};
var collection2 = new Dictionary<int, Dictionary<int, ExampleClass>>
{
[0] = new Dictionary<int, ExampleClass>
{
[1] = new ExampleClass { X = 1 },
[-1] = new ExampleClass { X = 2 }
}
};
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsFalse(collection1.SequenceEqual(collection2)); // SequenceEqual() calls Equals() of the inner list instead of SequenceEqual()
}
[TestMethod]
public void TCollection_Map_Equals_OneAndTheSameObject_Test()
{
var collection1 = new Dictionary<int, ExampleClass>
{
[1] = new ExampleClass { X = 1 },
[-1] = new ExampleClass { X = 2 }
};
var collection2 = collection1;
Assert.IsTrue(TCollections.Equals(collection1, collection2));
Assert.IsTrue(collection1.SequenceEqual(collection2));
}
private class ExampleClass
{
public int X { get; set; }
// all Thrift-generated classes override Equals(), we do just the same
public override bool Equals(object? that)
{
if (that is not ExampleClass other) return false;
if (ReferenceEquals(this, other)) return true;
return this.X == other.X;
}
// overriding Equals() requires GetHashCode() as well
public override int GetHashCode()
{
int hashcode = 157;
unchecked
{
hashcode = (hashcode * 397) + X.GetHashCode();
}
return hashcode;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>ExpandedLandingPageView</c> resource.</summary>
public sealed partial class ExpandedLandingPageViewName : gax::IResourceName, sys::IEquatable<ExpandedLandingPageViewName>
{
/// <summary>The possible contents of <see cref="ExpandedLandingPageViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>.
/// </summary>
CustomerExpandedFinalUrlFingerprint = 1,
}
private static gax::PathTemplate s_customerExpandedFinalUrlFingerprint = new gax::PathTemplate("customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}");
/// <summary>Creates a <see cref="ExpandedLandingPageViewName"/> 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="ExpandedLandingPageViewName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ExpandedLandingPageViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ExpandedLandingPageViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ExpandedLandingPageViewName"/> with the pattern
/// <c>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="expandedFinalUrlFingerprintId">
/// The <c>ExpandedFinalUrlFingerprint</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="ExpandedLandingPageViewName"/> constructed from the provided ids.
/// </returns>
public static ExpandedLandingPageViewName FromCustomerExpandedFinalUrlFingerprint(string customerId, string expandedFinalUrlFingerprintId) =>
new ExpandedLandingPageViewName(ResourceNameType.CustomerExpandedFinalUrlFingerprint, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), expandedFinalUrlFingerprintId: gax::GaxPreconditions.CheckNotNullOrEmpty(expandedFinalUrlFingerprintId, nameof(expandedFinalUrlFingerprintId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ExpandedLandingPageViewName"/> with
/// pattern <c>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="expandedFinalUrlFingerprintId">
/// The <c>ExpandedFinalUrlFingerprint</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ExpandedLandingPageViewName"/> with pattern
/// <c>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>.
/// </returns>
public static string Format(string customerId, string expandedFinalUrlFingerprintId) =>
FormatCustomerExpandedFinalUrlFingerprint(customerId, expandedFinalUrlFingerprintId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ExpandedLandingPageViewName"/> with
/// pattern <c>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="expandedFinalUrlFingerprintId">
/// The <c>ExpandedFinalUrlFingerprint</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ExpandedLandingPageViewName"/> with pattern
/// <c>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>.
/// </returns>
public static string FormatCustomerExpandedFinalUrlFingerprint(string customerId, string expandedFinalUrlFingerprintId) =>
s_customerExpandedFinalUrlFingerprint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(expandedFinalUrlFingerprintId, nameof(expandedFinalUrlFingerprintId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ExpandedLandingPageViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="expandedLandingPageViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ExpandedLandingPageViewName"/> if successful.</returns>
public static ExpandedLandingPageViewName Parse(string expandedLandingPageViewName) =>
Parse(expandedLandingPageViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ExpandedLandingPageViewName"/> 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>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="expandedLandingPageViewName">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="ExpandedLandingPageViewName"/> if successful.</returns>
public static ExpandedLandingPageViewName Parse(string expandedLandingPageViewName, bool allowUnparsed) =>
TryParse(expandedLandingPageViewName, allowUnparsed, out ExpandedLandingPageViewName 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="ExpandedLandingPageViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="expandedLandingPageViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ExpandedLandingPageViewName"/>, 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 expandedLandingPageViewName, out ExpandedLandingPageViewName result) =>
TryParse(expandedLandingPageViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ExpandedLandingPageViewName"/> 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>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="expandedLandingPageViewName">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="ExpandedLandingPageViewName"/>, 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 expandedLandingPageViewName, bool allowUnparsed, out ExpandedLandingPageViewName result)
{
gax::GaxPreconditions.CheckNotNull(expandedLandingPageViewName, nameof(expandedLandingPageViewName));
gax::TemplatedResourceName resourceName;
if (s_customerExpandedFinalUrlFingerprint.TryParseName(expandedLandingPageViewName, out resourceName))
{
result = FromCustomerExpandedFinalUrlFingerprint(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(expandedLandingPageViewName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ExpandedLandingPageViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string expandedFinalUrlFingerprintId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
ExpandedFinalUrlFingerprintId = expandedFinalUrlFingerprintId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ExpandedLandingPageViewName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/expandedLandingPageViews/{expanded_final_url_fingerprint}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="expandedFinalUrlFingerprintId">
/// The <c>ExpandedFinalUrlFingerprint</c> ID. Must not be <c>null</c> or empty.
/// </param>
public ExpandedLandingPageViewName(string customerId, string expandedFinalUrlFingerprintId) : this(ResourceNameType.CustomerExpandedFinalUrlFingerprint, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), expandedFinalUrlFingerprintId: gax::GaxPreconditions.CheckNotNullOrEmpty(expandedFinalUrlFingerprintId, nameof(expandedFinalUrlFingerprintId)))
{
}
/// <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>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>ExpandedFinalUrlFingerprint</c> ID. Will not be <c>null</c>, unless this instance contains an
/// unparsed resource name.
/// </summary>
public string ExpandedFinalUrlFingerprintId { 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.CustomerExpandedFinalUrlFingerprint: return s_customerExpandedFinalUrlFingerprint.Expand(CustomerId, ExpandedFinalUrlFingerprintId);
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 ExpandedLandingPageViewName);
/// <inheritdoc/>
public bool Equals(ExpandedLandingPageViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ExpandedLandingPageViewName a, ExpandedLandingPageViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ExpandedLandingPageViewName a, ExpandedLandingPageViewName b) => !(a == b);
}
public partial class ExpandedLandingPageView
{
/// <summary>
/// <see cref="ExpandedLandingPageViewName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal ExpandedLandingPageViewName ResourceNameAsExpandedLandingPageViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : ExpandedLandingPageViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
//-----------------------------------------------------------------------------
// Verve
// Copyright (C) - Violent Tulip
//-----------------------------------------------------------------------------
function VerveEditor::AddGroup( %groupType )
{
if ( !isObject( $VerveEditor::Controller ) )
{
// No Controller.
return;
}
if ( %groupType $= "" )
{
// Default.
%groupType = "VGroup";
}
/*
// Add Template Group.
VerveEditor::AddTemplateGroup( $VerveEditor::TemplateFolder @ "/" @ %groupType @ ".vsf" );
*/
// Get the Name of the Target Group.
VerveEditorGroupBuilderGUI.Build( %groupType, "VerveEditor::_AddGroup" );
}
function VerveEditor::_AddGroup( %groupType, %groupLabel )
{
// Group History Actions.
VerveEditor::ToggleHistoryGroup();
// Create the Group.
%groupObject = new ( %groupType )();
// Add to Group.
$VerveEditor::Controller.addObject( %groupObject );
// Apply the Label.
%groupObject.setLabelUnique( %groupLabel );
// Callback.
if ( !%groupObject.OnAdd() )
{
// Remove Object.
$VerveEditor::Controller.removeObject( %groupObject );
// Delete Object.
%groupObject.delete();
// Finish Up.
VerveEditor::ToggleHistoryGroup();
return;
}
// Resolve the Field Stack.
%groupObject.ResolveBuildStack( VerveEditorGroupBuilderFieldStack );
// Finish Up.
VerveEditor::ToggleHistoryGroup();
// Refresh Editor.
VerveEditor::Refresh();
// Set Selection.
VerveEditor::SetSelection( %groupObject.Control );
}
function VerveEditor::AddTemplateGroup( %templateFile )
{
if ( !isObject( $VerveEditor::Controller ) || !isFile( %templateFile ) )
{
// No Controller.
return;
}
// Fetch Current Count.
%groupCount = $VerveEditor::Controller.getCount();
// Group History Actions.
VerveEditor::ToggleHistoryGroup();
// Load Template.
$VerveEditor::Controller.readTemplate( %templateFile );
// Finish Up.
VerveEditor::ToggleHistoryGroup();
%newCount = $VerveEditor::Controller.getCount();
if ( %groupCount != %newCount )
{
if ( %newCount > %groupCount )
{
// Select New Object.
%selectedObject = $VerveEditor::Controller.getObject( %newCount - 1 );
}
// Refresh Editor.
VerveEditor::Refresh();
if ( isObject( %selectedObject ) )
{
// Set Selection.
VerveEditor::SetSelection( %selectedObject.Control );
}
}
}
function VerveEditor::AddTrack( %trackType, %targetGroup, %refresh )
{
if ( !isObject( $VerveEditor::Controller ) )
{
// No Controller.
return;
}
if ( !isObject( %targetGroup ) )
{
if ( !isObject( $VerveEditor::InspectorObject ) )
{
// No Controller or Selection.
return;
}
// Use Current Selection.
%targetGroup = $VerveEditor::InspectorObject;
}
if ( !%targetGroup.isMemberOfClass( "VGroup" ) )
{
// Invalid Target.
return;
}
if ( %trackType $= "" )
{
// Default.
%trackType = "VTrack";
}
// Create Track.
%trackObject = new ( %trackType )();
// Add to Group.
%targetGroup.addObject( %trackObject );
// Refresh Label.
%trackObject.setLabelUnique( %trackObject.Label );
// Callback.
if ( !%trackObject.OnAdd() )
{
// Remove Object.
%targetGroup.removeObject( %trackObject );
// Delete Object.
%trackObject.delete();
// Return.
return 0;
}
if ( %refresh $= "" || %refresh == true )
{
// Refresh.
VerveEditor::Refresh();
// Select New Object.
VerveEditor::SetSelection( %trackObject.Control );
}
// Return Track.
return %trackObject;
}
function VerveEditor::AddEvent( %targetTrack, %targetTime, %refresh )
{
if ( !isObject( $VerveEditor::Controller ) )
{
// No Controller.
return;
}
if ( !isObject( %targetTrack ) )
{
if ( !isObject( $VerveEditor::InspectorObject ) )
{
// No Controller or Selection.
return;
}
// Use Current Selection.
%targetTrack = $VerveEditor::InspectorObject;
}
if ( !%targetTrack.isMemberOfClass( "VTrack" ) )
{
// Invalid Target.
return;
}
// Create Event.
%eventObject = %targetTrack.CreateEvent();
if ( !isObject( %eventObject ) )
{
// Return.
return;
}
// Add to Track.
%targetTrack.addObject( %eventObject );
if ( %targetTime $= "" )
{
// User Controller Time.
%targetTime = $VerveEditor::Controller.Time;
}
// Apply Time.
%eventObject.SnapToTime( %targetTime, true );
// Callback.
if ( !%eventObject.OnAdd() )
{
// Remove Object.
%targetTrack.removeObject( %eventObject );
// Delete Object.
%eventObject.delete();
// Return.
return 0;
}
if ( %refresh $= "" || %refresh == true )
{
// Refresh.
VerveEditor::Refresh();
// Select Existing Track.
VerveEditor::SetSelection( %targetTrack.Control );
}
// Return Event.
return %eventObject;
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace Palaso.UI.WindowsForms.Widgets.Flying
{
public class CubicBezierCurve
{
private PointF _origin;
// Polynomial Coefficients
private PointF _A;
private PointF _B;
private PointF _C;
public CubicBezierCurve(PointF origin, PointF control1, PointF control2, PointF end)
{
CalculatePolynomialCoefficients(origin, control1, control2, end);
_origin = origin;
}
private void CalculatePolynomialCoefficients(PointF origin,
PointF control1,
PointF control2,
PointF end)
{
_C.X = 3.0f * (control1.X - origin.X);
_B.X = 3.0f * (control2.X - control1.X) - _C.X;
_A.X = end.X - origin.X - _C.X - _B.X;
_C.Y = 3.0f * (control1.Y - origin.Y);
_B.Y = 3.0f * (control2.Y - control1.Y) - _C.Y;
_A.Y = end.Y - origin.Y - _C.Y - _B.Y;
}
/// <summary>
/// Get Point on curve at parameter t
/// </summary>
/// <param name="t">the interval (varies between 0 and 1)</param>
/// <returns></returns>
private PointF GetPointFromInterval(float t)
{
float t_t = t * t; // interval squarred
float t_t_t = t_t * t;
PointF result = new PointF();
result.X = ((_A.X * t_t_t) + (_B.X * t_t) + (_C.X * t) + _origin.X);
result.Y = ((_A.Y * t_t_t) + (_B.Y * t_t) + (_C.Y * t) + _origin.Y);
return result;
}
/// <summary>
/// Given a DistanceRatio (ArcLength to CurveLength) gives us the
/// X,Y coordinates of the arc with that length
/// </summary>
public PointF GetPointOnCurve(float distanceRatio)
{
if (distanceRatio < 0 || distanceRatio > 1)
{
throw new ArgumentOutOfRangeException("distanceRatio",
distanceRatio,
"distanceRatio is a ratio and so must be between 0 and 1");
}
return GetPointFromInterval(distanceRatio);
}
}
public class Animator
{
public class AnimatorEventArgs: EventArgs
{
private readonly PointF _point;
public AnimatorEventArgs(PointF point)
{
_point = point;
}
public PointF Point
{
get { return _point; }
}
}
/// <summary>
/// Converts a ratio of time to a ratio of distance
/// </summary>
/// <param name="time">the ratio of time that has past
/// to the total time (varies uniformly between 0 and 1)</param>
/// <returns>the ratio of the distance traveled to the total
/// distance (varies between 0 and 1</returns>
public delegate float Speed(float time);
/// <summary>
/// Gets the proportion into space at which a given proportion of
/// the distance has been traveled along a path from the origin
/// </summary>
/// <remarks>The space is defined by a start point with
/// coordinates 0,0 and an end point with coordinates 1,1</remarks>
/// <param name="distance">the proportion of the distance traveled
/// to the total distance (varies between 0 and 1</param>
/// <returns>The proportional point into space at which
/// the distance has been traveled</returns>
public delegate PointF PointFromDistance(float distance);
public delegate void AnimateEventDelegate(object sender, AnimatorEventArgs e);
public event AnimateEventDelegate Animate = delegate { };
public event EventHandler Finished = delegate { };
private int _duration;
private Speed _speedFunction;
private PointFromDistance _pointFromDistanceFunction;
private int _elapsedTime;
private DateTime _lastMeasuredTime;
private readonly Timer _timer;
#region YAGNI
private readonly float _repeatCount; // greater than 0 or infinite
#endregion
public Animator()
{
Duration = 500;
_repeatCount = 1;
_speedFunction = SpeedFunctions.LinearSpeed;
_pointFromDistanceFunction = PointFromDistanceFunctions.LinearPointFromDistance;
_elapsedTime = 0;
_timer = new Timer();
_timer.Tick += Tick;
}
private void Tick(object sender, EventArgs e)
{
DateTime now = DateTime.Now;
_elapsedTime += now.Subtract(_lastMeasuredTime).Milliseconds;
_lastMeasuredTime = now;
if (_elapsedTime > Duration * _repeatCount)
{
Stop();
Finished(this, new EventArgs());
}
OnAnimate();
}
private void OnAnimate()
{
//convert time to distance
int elapsedTime;
Math.DivRem(_elapsedTime, Duration, out elapsedTime);
PointF pointF = PointFromDistanceFunction(SpeedFunction(elapsedTime / (float) Duration));
Animate(this, new AnimatorEventArgs(pointF));
}
/// <summary>
/// Starts the timer from the place it last was stopped
/// </summary>
public void Start()
{
_lastMeasuredTime = DateTime.Now;
_timer.Start();
}
/// <summary>
/// Stops the timer (effectively a pause until Reset is called)
/// </summary>
public void Stop()
{
_timer.Stop();
}
/// <summary>
/// Resets the timer to time 0
/// </summary>
public void Reset()
{
_elapsedTime = 0;
}
/// <summary>
/// Duration in Miliseconds
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">When negative value.</exception>
public int Duration
{
get { return _duration; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException();
}
_duration = value;
}
}
/// <summary>
/// Determines the rate at which the annimation travels along the curve.
/// </summary>
public Speed SpeedFunction
{
get { return _speedFunction; }
set { _speedFunction = value; }
}
public PointFromDistance PointFromDistanceFunction
{
get { return _pointFromDistanceFunction; }
set { _pointFromDistanceFunction = value; }
}
/// <summary>
/// The number of frames per second
/// </summary>
public float FrameRate
{
get { return 1000 / _timer.Interval; }
set
{
if (value > 1000 || value <= 0)
{
throw new ArgumentOutOfRangeException("value",
value,
"FrameRate must be between 1 and 1000, inclusive");
}
_timer.Interval = (int) (1000f / value);
}
}
/// <summary>
/// The duration of a single frame in milliseconds
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">When negative.</exception>
public int FrameDuration
{
get { return _timer.Interval; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException();
}
_timer.Interval = value;
}
}
public class SpeedFunctions
{
public static float LinearSpeed(float t)
{
return t;
}
/// <summary>
/// if input t varies uniformly between 0 and 1,
/// output t' starts at 0 slowly increasing, gaining speed until
/// the middle values and then decelerating at it approaches 1.
/// </summary>
/// <param name="t">varies uniformly between 0 and 1</param>
/// <returns>a number which varies between 0 and 1</returns>
public static float SinSpeed(float t)
{
return (float) (Math.Sin(t * Math.PI - Math.PI / 2f) + 1f) / 2f;
}
}
public class PointFromDistanceFunctions
{
public static PointF LinearPointFromDistance(float distance)
{
return new PointF(distance, distance);
}
}
public static int GetValue(float proportion, int from, int to)
{
return (int) ((to - from) * proportion) + from;
}
public static T GetValue<T>(float proportion, IList<T> list)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
if (list.Count < 1)
{
throw new ArgumentOutOfRangeException("list", list, "list is empty");
}
int index = (int) (list.Count * proportion);
return list[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.
/*============================================================
**
**
**
** Purpose: The CLR wrapper for all Win32 as well as
** ROTOR-style Unix PAL, etc. native operations
**
**
===========================================================*/
/**
* Notes to PInvoke users: Getting the syntax exactly correct is crucial, and
* more than a little confusing. Here's some guidelines.
*
* For handles, you should use a SafeHandle subclass specific to your handle
* type. For files, we have the following set of interesting definitions:
*
* [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
* private static extern SafeFileHandle CreateFile(...);
*
* [DllImport(KERNEL32, SetLastError=true)]
* unsafe internal static extern int ReadFile(SafeFileHandle handle, ...);
*
* [DllImport(KERNEL32, SetLastError=true)]
* internal static extern bool CloseHandle(IntPtr handle);
*
* P/Invoke will create the SafeFileHandle instance for you and assign the
* return value from CreateFile into the handle atomically. When we call
* ReadFile, P/Invoke will increment a ref count, make the call, then decrement
* it (preventing handle recycling vulnerabilities). Then SafeFileHandle's
* ReleaseHandle method will call CloseHandle, passing in the handle field
* as an IntPtr.
*
* If for some reason you cannot use a SafeHandle subclass for your handles,
* then use IntPtr as the handle type (or possibly HandleRef - understand when
* to use GC.KeepAlive). If your code will run in SQL Server (or any other
* long-running process that can't be recycled easily), use a constrained
* execution region to prevent thread aborts while allocating your
* handle, and consider making your handle wrapper subclass
* CriticalFinalizerObject to ensure you can free the handle. As you can
* probably guess, SafeHandle will save you a lot of headaches if your code
* needs to be robust to thread aborts and OOM.
*
*
* If you have a method that takes a native struct, you have two options for
* declaring that struct. You can make it a value type ('struct' in CSharp),
* or a reference type ('class'). This choice doesn't seem very interesting,
* but your function prototype must use different syntax depending on your
* choice. For example, if your native method is prototyped as such:
*
* bool GetVersionEx(OSVERSIONINFO & lposvi);
*
*
* you must use EITHER THIS OR THE NEXT syntax:
*
* [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
* internal struct OSVERSIONINFO { ... }
*
* [DllImport(KERNEL32, CharSet=CharSet.Auto)]
* internal static extern bool GetVersionEx(ref OSVERSIONINFO lposvi);
*
* OR:
*
* [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
* internal class OSVERSIONINFO { ... }
*
* [DllImport(KERNEL32, CharSet=CharSet.Auto)]
* internal static extern bool GetVersionEx([In, Out] OSVERSIONINFO lposvi);
*
* Note that classes require being marked as [In, Out] while value types must
* be passed as ref parameters.
*
* Also note the CharSet.Auto on GetVersionEx - while it does not take a String
* as a parameter, the OSVERSIONINFO contains an embedded array of TCHARs, so
* the size of the struct varies on different platforms, and there's a
* GetVersionExA & a GetVersionExW. Also, the OSVERSIONINFO struct has a sizeof
* field so the OS can ensure you've passed in the correctly-sized copy of an
* OSVERSIONINFO. You must explicitly set this using Marshal.SizeOf(Object);
*
* For security reasons, if you're making a P/Invoke method to a Win32 method
* that takes an ANSI String and that String is the name of some resource you've
* done a security check on (such as a file name), you want to disable best fit
* mapping in WideCharToMultiByte. Do this by setting BestFitMapping=false
* in your DllImportAttribute.
*/
namespace Microsoft.Win32
{
using System;
using System.Security;
using System.Text;
using System.Configuration.Assemblies;
using System.Runtime.Remoting;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using BOOL = System.Int32;
using DWORD = System.UInt32;
using ULONG = System.UInt32;
/**
* Win32 encapsulation for MSCORLIB.
*/
// Remove the default demands for all P/Invoke methods with this
// global declaration on the class.
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class Win32Native
{
internal const int KEY_QUERY_VALUE = 0x0001;
internal const int KEY_SET_VALUE = 0x0002;
internal const int KEY_CREATE_SUB_KEY = 0x0004;
internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008;
internal const int KEY_NOTIFY = 0x0010;
internal const int KEY_CREATE_LINK = 0x0020;
internal const int KEY_READ = ((STANDARD_RIGHTS_READ |
KEY_QUERY_VALUE |
KEY_ENUMERATE_SUB_KEYS |
KEY_NOTIFY)
&
(~SYNCHRONIZE));
internal const int KEY_WRITE = ((STANDARD_RIGHTS_WRITE |
KEY_SET_VALUE |
KEY_CREATE_SUB_KEY)
&
(~SYNCHRONIZE));
internal const int KEY_WOW64_64KEY = 0x0100; //
internal const int KEY_WOW64_32KEY = 0x0200; //
internal const int REG_OPTION_NON_VOLATILE = 0x0000; // (default) keys are persisted beyond reboot/unload
internal const int REG_OPTION_VOLATILE = 0x0001; // All keys created by the function are volatile
internal const int REG_OPTION_CREATE_LINK = 0x0002; // They key is a symbolic link
internal const int REG_OPTION_BACKUP_RESTORE = 0x0004; // Use SE_BACKUP_NAME process special privileges
internal const int REG_NONE = 0; // No value type
internal const int REG_SZ = 1; // Unicode nul terminated string
internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string
// (with environment variable references)
internal const int REG_BINARY = 3; // Free form binary
internal const int REG_DWORD = 4; // 32-bit number
internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD)
internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number
internal const int REG_LINK = 6; // Symbolic Link (unicode)
internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings
internal const int REG_RESOURCE_LIST = 8; // Resource list in the resource map
internal const int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource list in the hardware description
internal const int REG_RESOURCE_REQUIREMENTS_LIST = 10;
internal const int REG_QWORD = 11; // 64-bit number
internal const int HWND_BROADCAST = 0xffff;
internal const int WM_SETTINGCHANGE = 0x001A;
// TimeZone
internal const int TIME_ZONE_ID_INVALID = -1;
internal const int TIME_ZONE_ID_UNKNOWN = 0;
internal const int TIME_ZONE_ID_STANDARD = 1;
internal const int TIME_ZONE_ID_DAYLIGHT = 2;
internal const int MAX_PATH = 260;
internal const int MUI_LANGUAGE_ID = 0x4;
internal const int MUI_LANGUAGE_NAME = 0x8;
internal const int MUI_PREFERRED_UI_LANGUAGES = 0x10;
internal const int MUI_INSTALLED_LANGUAGES = 0x20;
internal const int MUI_ALL_LANGUAGES = 0x40;
internal const int MUI_LANG_NEUTRAL_PE_FILE = 0x100;
internal const int MUI_NON_LANG_NEUTRAL_FILE = 0x200;
internal const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
internal const int LOAD_STRING_MAX_LENGTH = 500;
[StructLayout(LayoutKind.Sequential)]
internal struct SystemTime
{
[MarshalAs(UnmanagedType.U2)]
public short Year;
[MarshalAs(UnmanagedType.U2)]
public short Month;
[MarshalAs(UnmanagedType.U2)]
public short DayOfWeek;
[MarshalAs(UnmanagedType.U2)]
public short Day;
[MarshalAs(UnmanagedType.U2)]
public short Hour;
[MarshalAs(UnmanagedType.U2)]
public short Minute;
[MarshalAs(UnmanagedType.U2)]
public short Second;
[MarshalAs(UnmanagedType.U2)]
public short Milliseconds;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct TimeZoneInformation
{
[MarshalAs(UnmanagedType.I4)]
public Int32 Bias;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string StandardName;
public SystemTime StandardDate;
[MarshalAs(UnmanagedType.I4)]
public Int32 StandardBias;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string DaylightName;
public SystemTime DaylightDate;
[MarshalAs(UnmanagedType.I4)]
public Int32 DaylightBias;
public TimeZoneInformation(Win32Native.DynamicTimeZoneInformation dtzi)
{
Bias = dtzi.Bias;
StandardName = dtzi.StandardName;
StandardDate = dtzi.StandardDate;
StandardBias = dtzi.StandardBias;
DaylightName = dtzi.DaylightName;
DaylightDate = dtzi.DaylightDate;
DaylightBias = dtzi.DaylightBias;
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct DynamicTimeZoneInformation
{
[MarshalAs(UnmanagedType.I4)]
public Int32 Bias;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string StandardName;
public SystemTime StandardDate;
[MarshalAs(UnmanagedType.I4)]
public Int32 StandardBias;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string DaylightName;
public SystemTime DaylightDate;
[MarshalAs(UnmanagedType.I4)]
public Int32 DaylightBias;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string TimeZoneKeyName;
[MarshalAs(UnmanagedType.Bool)]
public bool DynamicDaylightTimeDisabled;
}
[StructLayout(LayoutKind.Sequential)]
internal struct RegistryTimeZoneInformation
{
[MarshalAs(UnmanagedType.I4)]
public Int32 Bias;
[MarshalAs(UnmanagedType.I4)]
public Int32 StandardBias;
[MarshalAs(UnmanagedType.I4)]
public Int32 DaylightBias;
public SystemTime StandardDate;
public SystemTime DaylightDate;
public RegistryTimeZoneInformation(Win32Native.TimeZoneInformation tzi)
{
Bias = tzi.Bias;
StandardDate = tzi.StandardDate;
StandardBias = tzi.StandardBias;
DaylightDate = tzi.DaylightDate;
DaylightBias = tzi.DaylightBias;
}
public RegistryTimeZoneInformation(Byte[] bytes)
{
//
// typedef struct _REG_TZI_FORMAT {
// [00-03] LONG Bias;
// [04-07] LONG StandardBias;
// [08-11] LONG DaylightBias;
// [12-27] SYSTEMTIME StandardDate;
// [12-13] WORD wYear;
// [14-15] WORD wMonth;
// [16-17] WORD wDayOfWeek;
// [18-19] WORD wDay;
// [20-21] WORD wHour;
// [22-23] WORD wMinute;
// [24-25] WORD wSecond;
// [26-27] WORD wMilliseconds;
// [28-43] SYSTEMTIME DaylightDate;
// [28-29] WORD wYear;
// [30-31] WORD wMonth;
// [32-33] WORD wDayOfWeek;
// [34-35] WORD wDay;
// [36-37] WORD wHour;
// [38-39] WORD wMinute;
// [40-41] WORD wSecond;
// [42-43] WORD wMilliseconds;
// } REG_TZI_FORMAT;
//
if (bytes == null || bytes.Length != 44)
{
throw new ArgumentException(SR.Argument_InvalidREG_TZI_FORMAT, nameof(bytes));
}
Bias = BitConverter.ToInt32(bytes, 0);
StandardBias = BitConverter.ToInt32(bytes, 4);
DaylightBias = BitConverter.ToInt32(bytes, 8);
StandardDate.Year = BitConverter.ToInt16(bytes, 12);
StandardDate.Month = BitConverter.ToInt16(bytes, 14);
StandardDate.DayOfWeek = BitConverter.ToInt16(bytes, 16);
StandardDate.Day = BitConverter.ToInt16(bytes, 18);
StandardDate.Hour = BitConverter.ToInt16(bytes, 20);
StandardDate.Minute = BitConverter.ToInt16(bytes, 22);
StandardDate.Second = BitConverter.ToInt16(bytes, 24);
StandardDate.Milliseconds = BitConverter.ToInt16(bytes, 26);
DaylightDate.Year = BitConverter.ToInt16(bytes, 28);
DaylightDate.Month = BitConverter.ToInt16(bytes, 30);
DaylightDate.DayOfWeek = BitConverter.ToInt16(bytes, 32);
DaylightDate.Day = BitConverter.ToInt16(bytes, 34);
DaylightDate.Hour = BitConverter.ToInt16(bytes, 36);
DaylightDate.Minute = BitConverter.ToInt16(bytes, 38);
DaylightDate.Second = BitConverter.ToInt16(bytes, 40);
DaylightDate.Milliseconds = BitConverter.ToInt16(bytes, 42);
}
}
// end of TimeZone
// Win32 ACL-related constants:
internal const int READ_CONTROL = 0x00020000;
internal const int SYNCHRONIZE = 0x00100000;
internal const int STANDARD_RIGHTS_READ = READ_CONTROL;
internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL;
// STANDARD_RIGHTS_REQUIRED (0x000F0000L)
// SEMAPHORE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3)
// SEMAPHORE and Event both use 0x0002
// MUTEX uses 0x001 (MUTANT_QUERY_STATE)
// Note that you may need to specify the SYNCHRONIZE bit as well
// to be able to open a synchronization primitive.
internal const int SEMAPHORE_MODIFY_STATE = 0x00000002;
internal const int EVENT_MODIFY_STATE = 0x00000002;
internal const int MUTEX_MODIFY_STATE = 0x00000001;
internal const int MUTEX_ALL_ACCESS = 0x001F0001;
internal const int LMEM_FIXED = 0x0000;
internal const int LMEM_ZEROINIT = 0x0040;
internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class OSVERSIONINFO
{
internal OSVERSIONINFO()
{
OSVersionInfoSize = (int)Marshal.SizeOf(this);
}
// The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
internal int OSVersionInfoSize = 0;
internal int MajorVersion = 0;
internal int MinorVersion = 0;
internal int BuildNumber = 0;
internal int PlatformId = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
internal String CSDVersion = null;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class OSVERSIONINFOEX
{
public OSVERSIONINFOEX()
{
OSVersionInfoSize = (int)Marshal.SizeOf(this);
}
// The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
internal int OSVersionInfoSize = 0;
internal int MajorVersion = 0;
internal int MinorVersion = 0;
internal int BuildNumber = 0;
internal int PlatformId = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
internal string CSDVersion = null;
internal ushort ServicePackMajor = 0;
internal ushort ServicePackMinor = 0;
internal short SuiteMask = 0;
internal byte ProductType = 0;
internal byte Reserved = 0;
}
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES
{
internal int nLength = 0;
// don't remove null, or this field will disappear in bcl.small
internal unsafe byte* pSecurityDescriptor = null;
internal int bInheritHandle = 0;
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
internal struct WIN32_FILE_ATTRIBUTE_DATA
{
internal int fileAttributes;
internal uint ftCreationTimeLow;
internal uint ftCreationTimeHigh;
internal uint ftLastAccessTimeLow;
internal uint ftLastAccessTimeHigh;
internal uint ftLastWriteTimeLow;
internal uint ftLastWriteTimeHigh;
internal int fileSizeHigh;
internal int fileSizeLow;
internal void PopulateFrom(WIN32_FIND_DATA findData)
{
// Copy the information to data
fileAttributes = findData.dwFileAttributes;
ftCreationTimeLow = findData.ftCreationTime_dwLowDateTime;
ftCreationTimeHigh = findData.ftCreationTime_dwHighDateTime;
ftLastAccessTimeLow = findData.ftLastAccessTime_dwLowDateTime;
ftLastAccessTimeHigh = findData.ftLastAccessTime_dwHighDateTime;
ftLastWriteTimeLow = findData.ftLastWriteTime_dwLowDateTime;
ftLastWriteTimeHigh = findData.ftLastWriteTime_dwHighDateTime;
fileSizeHigh = findData.nFileSizeHigh;
fileSizeLow = findData.nFileSizeLow;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct MEMORYSTATUSEX
{
// The length field must be set to the size of this data structure.
internal int length;
internal int memoryLoad;
internal ulong totalPhys;
internal ulong availPhys;
internal ulong totalPageFile;
internal ulong availPageFile;
internal ulong totalVirtual;
internal ulong availVirtual;
internal ulong availExtendedVirtual;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct MEMORY_BASIC_INFORMATION
{
internal void* BaseAddress;
internal void* AllocationBase;
internal uint AllocationProtect;
internal UIntPtr RegionSize;
internal uint State;
internal uint Protect;
internal uint Type;
}
#if !FEATURE_PAL
internal const String KERNEL32 = "kernel32.dll";
internal const String USER32 = "user32.dll";
internal const String OLE32 = "ole32.dll";
internal const String OLEAUT32 = "oleaut32.dll";
internal const String NTDLL = "ntdll.dll";
#else //FEATURE_PAL
internal const String KERNEL32 = "libcoreclr";
internal const String USER32 = "libcoreclr";
internal const String OLE32 = "libcoreclr";
internal const String OLEAUT32 = "libcoreclr";
internal const String NTDLL = "libcoreclr";
#endif //FEATURE_PAL
internal const String ADVAPI32 = "advapi32.dll";
internal const String SHELL32 = "shell32.dll";
internal const String SHIM = "mscoree.dll";
internal const String CRYPT32 = "crypt32.dll";
internal const String SECUR32 = "secur32.dll";
internal const String MSCORWKS = "coreclr.dll";
// From WinBase.h
internal const int SEM_FAILCRITICALERRORS = 1;
[DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = true)]
internal static extern int FormatMessage(int dwFlags, IntPtr lpSource,
int dwMessageId, int dwLanguageId, [Out]StringBuilder lpBuffer,
int nSize, IntPtr va_list_arguments);
// Gets an error message for a Win32 error code.
internal static String GetMessage(int errorCode)
{
StringBuilder sb = StringBuilderCache.Acquire(512);
int result = Win32Native.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
IntPtr.Zero, errorCode, 0, sb, sb.Capacity, IntPtr.Zero);
if (result != 0)
{
// result is the # of characters copied to the StringBuilder.
return StringBuilderCache.GetStringAndRelease(sb);
}
else
{
StringBuilderCache.Release(sb);
return SR.Format(SR.UnknownError_Num, errorCode);
}
}
[DllImport(KERNEL32, EntryPoint = "LocalAlloc")]
internal static extern IntPtr LocalAlloc_NoSafeHandle(int uFlags, UIntPtr sizetdwBytes);
[DllImport(KERNEL32, SetLastError = true)]
internal static extern IntPtr LocalFree(IntPtr handle);
// MSDN says the length is a SIZE_T.
[DllImport(NTDLL, EntryPoint = "RtlZeroMemory")]
internal static extern void ZeroMemory(IntPtr address, UIntPtr length);
internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer)
{
buffer.length = Marshal.SizeOf(typeof(MEMORYSTATUSEX));
return GlobalMemoryStatusExNative(ref buffer);
}
[DllImport(KERNEL32, SetLastError = true, EntryPoint = "GlobalMemoryStatusEx")]
private static extern bool GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX buffer);
[DllImport(KERNEL32, SetLastError = true)]
unsafe internal static extern UIntPtr VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, UIntPtr sizeOfBuffer);
// VirtualAlloc should generally be avoided, but is needed in
// the MemoryFailPoint implementation (within a CER) to increase the
// size of the page file, ignoring any host memory allocators.
[DllImport(KERNEL32, SetLastError = true)]
unsafe internal static extern void* VirtualAlloc(void* address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode);
[DllImport(KERNEL32, SetLastError = true)]
unsafe internal static extern bool VirtualFree(void* address, UIntPtr numBytes, int pageFreeMode);
[DllImport(KERNEL32, CharSet = CharSet.Ansi, ExactSpelling = true, EntryPoint = "lstrlenA")]
internal static extern int lstrlenA(IntPtr ptr);
[DllImport(KERNEL32, CharSet = CharSet.Unicode, ExactSpelling = true, EntryPoint = "lstrlenW")]
internal static extern int lstrlenW(IntPtr ptr);
[DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)]
internal static extern IntPtr SysAllocStringLen(String src, int len); // BSTR
[DllImport(Win32Native.OLEAUT32)]
internal static extern uint SysStringLen(IntPtr bstr);
[DllImport(Win32Native.OLEAUT32)]
internal static extern void SysFreeString(IntPtr bstr);
#if FEATURE_COMINTEROP
[DllImport(Win32Native.OLEAUT32)]
internal static extern IntPtr SysAllocStringByteLen(byte[] str, uint len); // BSTR
[DllImport(Win32Native.OLEAUT32)]
internal static extern uint SysStringByteLen(IntPtr bstr);
#endif
[DllImport(KERNEL32, SetLastError = true)]
internal static extern bool SetEvent(SafeWaitHandle handle);
[DllImport(KERNEL32, SetLastError = true)]
internal static extern bool ResetEvent(SafeWaitHandle handle);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle CreateEvent(SECURITY_ATTRIBUTES lpSecurityAttributes, bool isManualReset, bool initialState, String name);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle OpenEvent(/* DWORD */ int desiredAccess, bool inheritHandle, String name);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle CreateMutex(SECURITY_ATTRIBUTES lpSecurityAttributes, bool initialOwner, String name);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle OpenMutex(/* DWORD */ int desiredAccess, bool inheritHandle, String name);
[DllImport(KERNEL32, SetLastError = true)]
internal static extern bool ReleaseMutex(SafeWaitHandle handle);
[DllImport(KERNEL32, SetLastError = true)]
internal static extern bool CloseHandle(IntPtr handle);
[DllImport(KERNEL32, SetLastError = true)]
internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle CreateSemaphore(SECURITY_ATTRIBUTES lpSecurityAttributes, int initialCount, int maximumCount, String name);
[DllImport(KERNEL32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle OpenSemaphore(/* DWORD */ int desiredAccess, bool inheritHandle, String name);
// Will be in winnls.h
internal const int FIND_STARTSWITH = 0x00100000; // see if value is at the beginning of source
internal const int FIND_ENDSWITH = 0x00200000; // see if value is at the end of source
internal const int FIND_FROMSTART = 0x00400000; // look for value in source, starting at the beginning
internal const int FIND_FROMEND = 0x00800000; // look for value in source, starting at the end
[StructLayout(LayoutKind.Sequential)]
internal struct NlsVersionInfoEx
{
internal int dwNLSVersionInfoSize;
internal int dwNLSVersion;
internal int dwDefinedVersion;
internal int dwEffectiveId;
internal Guid guidCustomVersion;
}
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static extern int GetSystemDirectory([Out]StringBuilder sb, int length);
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h
// Note, these are #defines used to extract handles, and are NOT handles.
internal const int STD_INPUT_HANDLE = -10;
internal const int STD_OUTPUT_HANDLE = -11;
internal const int STD_ERROR_HANDLE = -12;
[DllImport(KERNEL32, SetLastError = true)]
internal static extern IntPtr GetStdHandle(int nStdHandle); // param is NOT a handle, but it returns one!
// From wincon.h
internal const int CTRL_C_EVENT = 0;
internal const int CTRL_BREAK_EVENT = 1;
internal const int CTRL_CLOSE_EVENT = 2;
internal const int CTRL_LOGOFF_EVENT = 5;
internal const int CTRL_SHUTDOWN_EVENT = 6;
internal const short KEY_EVENT = 1;
// From WinBase.h
internal const int FILE_TYPE_DISK = 0x0001;
internal const int FILE_TYPE_CHAR = 0x0002;
internal const int FILE_TYPE_PIPE = 0x0003;
internal const int REPLACEFILE_WRITE_THROUGH = 0x1;
internal const int REPLACEFILE_IGNORE_MERGE_ERRORS = 0x2;
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
internal const uint FILE_MAP_WRITE = 0x0002;
internal const uint FILE_MAP_READ = 0x0004;
// Constants from WinNT.h
internal const int FILE_ATTRIBUTE_READONLY = 0x00000001;
internal const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
internal const int FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400;
internal const int IO_REPARSE_TAG_MOUNT_POINT = unchecked((int)0xA0000003);
internal const int PAGE_READWRITE = 0x04;
internal const int MEM_COMMIT = 0x1000;
internal const int MEM_RESERVE = 0x2000;
internal const int MEM_RELEASE = 0x8000;
internal const int MEM_FREE = 0x10000;
// Error codes from WinError.h
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_INVALID_FUNCTION = 0x1;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DATA = 0xd;
internal const int ERROR_INVALID_DRIVE = 0xf;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_BAD_LENGTH = 0x18;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_NOT_SUPPORTED = 0x32;
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57;
internal const int ERROR_BROKEN_PIPE = 0x6D;
internal const int ERROR_CALL_NOT_IMPLEMENTED = 0x78;
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A;
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_BAD_PATHNAME = 0xA1;
internal const int ERROR_ALREADY_EXISTS = 0xB7;
internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long.
internal const int ERROR_NO_DATA = 0xE8;
internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9;
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_DIRECTORY = 0x10B;
internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation
internal const int ERROR_NOT_FOUND = 0x490; // 1168; For IO Cancellation
internal const int ERROR_NO_TOKEN = 0x3f0;
internal const int ERROR_DLL_INIT_FAILED = 0x45A;
internal const int ERROR_NON_ACCOUNT_SID = 0x4E9;
internal const int ERROR_NOT_ALL_ASSIGNED = 0x514;
internal const int ERROR_UNKNOWN_REVISION = 0x519;
internal const int ERROR_INVALID_OWNER = 0x51B;
internal const int ERROR_INVALID_PRIMARY_GROUP = 0x51C;
internal const int ERROR_NO_SUCH_PRIVILEGE = 0x521;
internal const int ERROR_PRIVILEGE_NOT_HELD = 0x522;
internal const int ERROR_NONE_MAPPED = 0x534;
internal const int ERROR_INVALID_ACL = 0x538;
internal const int ERROR_INVALID_SID = 0x539;
internal const int ERROR_INVALID_SECURITY_DESCR = 0x53A;
internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542;
internal const int ERROR_CANT_OPEN_ANONYMOUS = 0x543;
internal const int ERROR_NO_SECURITY_ON_OBJECT = 0x546;
internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 0x6FD;
// Error codes from ntstatus.h
internal const uint STATUS_SUCCESS = 0x00000000;
internal const uint STATUS_SOME_NOT_MAPPED = 0x00000107;
internal const uint STATUS_NO_MEMORY = 0xC0000017;
internal const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034;
internal const uint STATUS_NONE_MAPPED = 0xC0000073;
internal const uint STATUS_INSUFFICIENT_RESOURCES = 0xC000009A;
internal const uint STATUS_ACCESS_DENIED = 0xC0000022;
internal const int INVALID_FILE_SIZE = -1;
// From WinStatus.h
internal const int STATUS_ACCOUNT_RESTRICTION = unchecked((int)0xC000006E);
// Use this to translate error codes like the above into HRESULTs like
// 0x80070006 for ERROR_INVALID_HANDLE
internal static int MakeHRFromErrorCode(int errorCode)
{
BCLDebug.Assert((0xFFFF0000 & errorCode) == 0, "This is an HRESULT, not an error code!");
return unchecked(((int)0x80070000) | errorCode);
}
// Win32 Structs in N/Direct style
[Serializable]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
[BestFitMapping(false)]
internal class WIN32_FIND_DATA
{
internal int dwFileAttributes = 0;
// ftCreationTime was a by-value FILETIME structure
internal uint ftCreationTime_dwLowDateTime = 0;
internal uint ftCreationTime_dwHighDateTime = 0;
// ftLastAccessTime was a by-value FILETIME structure
internal uint ftLastAccessTime_dwLowDateTime = 0;
internal uint ftLastAccessTime_dwHighDateTime = 0;
// ftLastWriteTime was a by-value FILETIME structure
internal uint ftLastWriteTime_dwLowDateTime = 0;
internal uint ftLastWriteTime_dwHighDateTime = 0;
internal int nFileSizeHigh = 0;
internal int nFileSizeLow = 0;
// If the file attributes' reparse point flag is set, then
// dwReserved0 is the file tag (aka reparse tag) for the
// reparse point. Use this to figure out whether something is
// a volume mount point or a symbolic link.
internal int dwReserved0 = 0;
internal int dwReserved1 = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
internal String cFileName = null;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
internal String cAlternateFileName = null;
}
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeFindHandle FindFirstFile(String fileName, [In, Out] Win32Native.WIN32_FIND_DATA data);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool FindNextFile(
SafeFindHandle hndFindFile,
[In, Out, MarshalAs(UnmanagedType.LPStruct)]
WIN32_FIND_DATA lpFindFileData);
[DllImport(KERNEL32)]
internal static extern bool FindClose(IntPtr handle);
[DllImport(KERNEL32, SetLastError = true, ExactSpelling = true)]
internal static extern uint GetCurrentDirectoryW(uint nBufferLength, char[] lpBuffer);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool GetFileAttributesEx(String name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool SetCurrentDirectory(String path);
[DllImport(KERNEL32, SetLastError = false, EntryPoint = "SetErrorMode", ExactSpelling = true)]
private static extern int SetErrorMode_VistaAndOlder(int newMode);
// RTM versions of Win7 and Windows Server 2008 R2
private static readonly Version ThreadErrorModeMinOsVersion = new Version(6, 1, 7600);
// this method uses the thread-safe version of SetErrorMode on Windows 7 / Windows Server 2008 R2 operating systems.
internal static int SetErrorMode(int newMode)
{
return SetErrorMode_VistaAndOlder(newMode);
}
internal const int LCID_SUPPORTED = 0x00000002; // supported locale ids
[DllImport(KERNEL32)]
internal static extern unsafe int WideCharToMultiByte(uint cp, uint flags, char* pwzSource, int cchSource, byte* pbDestBuffer, int cbDestBuffer, IntPtr null1, IntPtr null2);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static extern bool SetEnvironmentVariable(string lpName, string lpValue);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static extern int GetEnvironmentVariable(string lpName, [Out]StringBuilder lpValue, int size);
[DllImport(KERNEL32, CharSet = CharSet.Unicode)]
internal static unsafe extern char* GetEnvironmentStrings();
[DllImport(KERNEL32, CharSet = CharSet.Unicode)]
internal static unsafe extern bool FreeEnvironmentStrings(char* pStrings);
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern uint GetCurrentProcessId();
[DllImport(OLE32)]
internal extern static int CoCreateGuid(out Guid guid);
[DllImport(OLE32)]
internal static extern IntPtr CoTaskMemAlloc(UIntPtr cb);
[DllImport(OLE32)]
internal static extern void CoTaskMemFree(IntPtr ptr);
[DllImport(OLE32)]
internal static extern IntPtr CoTaskMemRealloc(IntPtr pv, UIntPtr cb);
#if FEATURE_WIN32_REGISTRY
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegDeleteValue(SafeRegistryHandle hKey, String lpValueName);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal unsafe static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex,
char[] lpName, ref int lpcbName, int[] lpReserved,
[Out]StringBuilder lpClass, int[] lpcbClass,
long[] lpftLastWriteTime);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal unsafe static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex,
char[] lpValueName, ref int lpcbValueName,
IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData,
int[] lpcbData);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey,
int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegQueryInfoKey(SafeRegistryHandle hKey, [Out]StringBuilder lpClass,
int[] lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys,
int[] lpcbMaxSubKeyLen, int[] lpcbMaxClassLen,
ref int lpcValues, int[] lpcbMaxValueNameLen,
int[] lpcbMaxValueLen, int[] lpcbSecurityDescriptor,
int[] lpftLastWriteTime);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, [Out] byte[] lpData,
ref int lpcbData);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, ref int lpData,
ref int lpcbData);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, ref long lpData,
ref int lpcbData);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, [Out] char[] lpData,
ref int lpcbData);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, ref int lpData, int cbData);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, ref long lpData, int cbData);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, String lpData, int cbData);
#endif // FEATURE_WIN32_REGISTRY
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static extern int ExpandEnvironmentStrings(String lpSrc, [Out]StringBuilder lpDst, int nSize);
[DllImport(KERNEL32)]
internal static extern IntPtr LocalReAlloc(IntPtr handle, IntPtr sizetcbBytes, int uFlags);
internal const int SHGFP_TYPE_CURRENT = 0; // the current (user) folder path setting
internal const int UOI_FLAGS = 1;
internal const int WSF_VISIBLE = 1;
// .NET Framework 4.0 and newer - all versions of windows ||| \public\sdk\inc\shlobj.h
internal const int CSIDL_FLAG_CREATE = 0x8000; // force folder creation in SHGetFolderPath
internal const int CSIDL_FLAG_DONT_VERIFY = 0x4000; // return an unverified folder path
internal const int CSIDL_ADMINTOOLS = 0x0030; // <user name>\Start Menu\Programs\Administrative Tools
internal const int CSIDL_CDBURN_AREA = 0x003b; // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
internal const int CSIDL_COMMON_ADMINTOOLS = 0x002f; // All Users\Start Menu\Programs\Administrative Tools
internal const int CSIDL_COMMON_DOCUMENTS = 0x002e; // All Users\Documents
internal const int CSIDL_COMMON_MUSIC = 0x0035; // All Users\My Music
internal const int CSIDL_COMMON_OEM_LINKS = 0x003a; // Links to All Users OEM specific apps
internal const int CSIDL_COMMON_PICTURES = 0x0036; // All Users\My Pictures
internal const int CSIDL_COMMON_STARTMENU = 0x0016; // All Users\Start Menu
internal const int CSIDL_COMMON_PROGRAMS = 0X0017; // All Users\Start Menu\Programs
internal const int CSIDL_COMMON_STARTUP = 0x0018; // All Users\Startup
internal const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019; // All Users\Desktop
internal const int CSIDL_COMMON_TEMPLATES = 0x002d; // All Users\Templates
internal const int CSIDL_COMMON_VIDEO = 0x0037; // All Users\My Video
internal const int CSIDL_FONTS = 0x0014; // windows\fonts
internal const int CSIDL_MYVIDEO = 0x000e; // "My Videos" folder
internal const int CSIDL_NETHOOD = 0x0013; // %APPDATA%\Microsoft\Windows\Network Shortcuts
internal const int CSIDL_PRINTHOOD = 0x001b; // %APPDATA%\Microsoft\Windows\Printer Shortcuts
internal const int CSIDL_PROFILE = 0x0028; // %USERPROFILE% (%SystemDrive%\Users\%USERNAME%)
internal const int CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c; // x86 Program Files\Common on RISC
internal const int CSIDL_PROGRAM_FILESX86 = 0x002a; // x86 C:\Program Files on RISC
internal const int CSIDL_RESOURCES = 0x0038; // %windir%\Resources
internal const int CSIDL_RESOURCES_LOCALIZED = 0x0039; // %windir%\resources\0409 (code page)
internal const int CSIDL_SYSTEMX86 = 0x0029; // %windir%\system32
internal const int CSIDL_WINDOWS = 0x0024; // GetWindowsDirectory()
// .NET Framework 3.5 and earlier - all versions of windows
internal const int CSIDL_APPDATA = 0x001a;
internal const int CSIDL_COMMON_APPDATA = 0x0023;
internal const int CSIDL_LOCAL_APPDATA = 0x001c;
internal const int CSIDL_COOKIES = 0x0021;
internal const int CSIDL_FAVORITES = 0x0006;
internal const int CSIDL_HISTORY = 0x0022;
internal const int CSIDL_INTERNET_CACHE = 0x0020;
internal const int CSIDL_PROGRAMS = 0x0002;
internal const int CSIDL_RECENT = 0x0008;
internal const int CSIDL_SENDTO = 0x0009;
internal const int CSIDL_STARTMENU = 0x000b;
internal const int CSIDL_STARTUP = 0x0007;
internal const int CSIDL_SYSTEM = 0x0025;
internal const int CSIDL_TEMPLATES = 0x0015;
internal const int CSIDL_DESKTOPDIRECTORY = 0x0010;
internal const int CSIDL_PERSONAL = 0x0005;
internal const int CSIDL_PROGRAM_FILES = 0x0026;
internal const int CSIDL_PROGRAM_FILES_COMMON = 0x002b;
internal const int CSIDL_DESKTOP = 0x0000;
internal const int CSIDL_DRIVES = 0x0011;
internal const int CSIDL_MYMUSIC = 0x000d;
internal const int CSIDL_MYPICTURES = 0x0027;
internal const int NameSamCompatible = 2;
[DllImport(USER32, SetLastError = true, BestFitMapping = false)]
internal static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, String lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult);
[DllImport(KERNEL32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal extern static bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime);
internal const byte VER_GREATER_EQUAL = 0x3;
internal const uint VER_MAJORVERSION = 0x0000002;
internal const uint VER_MINORVERSION = 0x0000001;
internal const uint VER_SERVICEPACKMAJOR = 0x0000020;
internal const uint VER_SERVICEPACKMINOR = 0x0000010;
[DllImport("kernel32.dll")]
internal static extern bool VerifyVersionInfoW([In, Out] OSVERSIONINFOEX lpVersionInfo, uint dwTypeMask, ulong dwlConditionMask);
[DllImport("kernel32.dll")]
internal static extern ulong VerSetConditionMask(ulong dwlConditionMask, uint dwTypeBitMask, byte dwConditionMask);
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Tools.cs" company="">
//
// </copyright>
// <summary>
// Tools that are available to the core of the program (converting a player id or name into
// a player object) and internal methods are mostly stored here.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Skylight
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using PlayerIOClient;
using Skylight.Blocks;
/// <summary>
/// Tools that are available to the core of the program (converting a player id or name into
/// a player object) and internal methods are mostly stored here.
/// </summary>
public static class RoomAccessor
{
#region Public Properties
/// <summary>
/// Gets or sets the height of the room.
/// </summary>
/// <value>The height.</value>
public static int Height { get; set; }
/// <summary>
/// Gets or sets the width of the room.
/// </summary>
/// <value>The width.</value>
public static int Width { get; set; }
#endregion
}
/// <summary>
/// Class Tools.
/// </summary>
public static class Tools
{
#region Static Fields
/// <summary>
/// The ran.
/// </summary>
public static Random Ran = new Random();
#endregion
#region Delegates
/// <summary>
/// Delegate ProgramEvent
/// </summary>
/// <param name="message">The message.</param>
public delegate void ProgramEvent(string message);
#endregion
#region Public Events
/// <summary>
/// Occurs when a program message is sent.
/// </summary>
public static event ProgramEvent ProgramMessage = delegate { };
#endregion
#region Public Methods and Operators
/// <summary>
/// Clears the map.
/// </summary>
/// <param name="r">
/// The room.
/// </param>
public static void ClearMap(Room r)
{
r.Map.threeDimBlockList.Clear();
for (int x = 0; x <= r.Width; x++)
r.Map.threeDimBlockList.Add(new List<List<Block>>(r.Height));
for (int x = 0; x <= r.Width; x++)
for (int y = 0; y <= r.Height; y++)
r.Map.threeDimBlockList[x].Add(new List<Block>(2));
for (int x = 0; x <= r.Width; x++)
{
// Add each column
r.Map.threeDimBlockList[x].Add(new List<Block>(r.Height));
for (int y = 0; y <= r.Height; y++)
{
for (int z = 0; z < 2; z++)
{
r.Map.threeDimBlockList[x][y].Add(new Block(0, x, y, z));
}
}
}
}
/// <summary>
/// Gets the crown holder.
/// </summary>
/// <param name="r">
/// The room.
/// </param>
/// <returns>
/// The Player who holds the crown (if there is one).
/// </returns>
public static Player GetCrownHolder(Room r)
{
foreach (Player p in r.OnlinePlayers.Where(p => p.HasCrown))
{
return p;
}
SkylightMessage("Could not find crown holder.");
return null;
}
/// <summary>
/// Gets the player by their session identifier.
/// </summary>
/// <param name="id">
/// The identifier.
/// </param>
/// <param name="r">
/// The room.
/// </param>
/// <param name="onlyReturnBots">
/// if set to <c>true</c> [only return bots].
/// </param>
/// <returns>
/// Player.
/// </returns>
public static Player GetPlayer(int id, Room r, bool onlyReturnBots = false)
{
foreach (Player p in r.OnlinePlayers.Where(p => p.Id == id).Where(p => !onlyReturnBots || p.IsBot))
{
return p;
}
SkylightMessage("Could not find player " + id + " in " + r.Name);
return null;
}
/// <summary>
/// Gets the name of the player by.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <param name="r">
/// The room.
/// </param>
/// <param name="onlyReturnBots">
/// if set to <c>true</c> [only return bots].
/// </param>
/// <returns>
/// Player.
/// </returns>
public static Player GetPlayer(string name, Room r, bool onlyReturnBots = false)
{
foreach (Player p in r.OnlinePlayers.Where(p => p.Name == name).Where(p => !onlyReturnBots || p.IsBot))
{
return p;
}
SkylightMessage("Could not find player " + name + " in " + r.Name);
return null;
}
/// <summary>
/// Gets the room.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <returns>
/// Room.
/// </returns>
public static Room GetRoom(string name)
{
foreach (Room r in Room.JoinedRooms.Where(r => r.Name == name))
{
return r;
}
SkylightMessage("Could not find room \"" + name + "\"");
return null;
}
/// <summary>
/// Gets the winners.
/// </summary>
/// <param name="r">
/// The room.
/// </param>
/// <returns>
/// A list of Players who have touched the trophy
/// </returns>
public static List<Player> GetWinners(Room r)
{
return r.OnlinePlayers.Where(p => p.HasSilverCrown).ToList();
}
/// <summary>
/// Parses the URL.
/// </summary>
/// <param name="id">
/// The unparsed identifier of the room.
/// </param>
/// <returns>
/// A parsed room id
/// </returns>
public static string ParseUrl(string id)
{
// If it matches any type of URL and has 13 characters at the end, return the last 13 characters.
// Supports haphazard copy/pasting.
id = id.Trim();
if (Regex.IsMatch(id, @"^[a-zA-Z0-9_-]+$") && (id.Length <= 14) && (9 <= id.Length))
{
return id;
}
if (Regex.IsMatch(id, "[htp:/w.evrybodis.comga]{0,36}[a-zA-Z0-9_-]{13}"))
{
try
{
var parsedUrl = new Uri(id);
var finalUrl = Convert.ToString(parsedUrl.Segments.Last());
return finalUrl;
}
catch (UriFormatException)
{
SkylightMessage("Invalid room id");
}
}
return null;
}
/// <summary>
/// Shuffles a list
/// </summary>
/// <param name="list">
/// The list.
/// </param>
public static void Shuffle<T>(this IList<T> list)
{
var rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
#endregion
// Return the correct coin ID based based on whether or not the block is gate or door
#region Methods
/// <summary>
/// Derots the specified world key.
/// </summary>
/// <param name="worldKey">
/// The world key.
/// </param>
/// <returns>
/// Derotted world key
/// </returns>
internal static string Derot(string worldKey)
{
char[] array = worldKey.ToCharArray();
for (int i = 0; i < array.Length; i++)
{
int number = array[i];
if (number >= 'a' && number <= 'z')
{
if (number > 'm')
{
number -= 13;
}
else
{
number += 13;
}
}
else if (number >= 'A' && number <= 'Z')
{
if (number > 'M')
{
number -= 13;
}
else
{
number += 13;
}
}
array[i] = (char)number;
}
return new string(array);
}
/// <summary>
/// Deserializes the initialize.
/// </summary>
/// <param name="m">
/// The message
/// </param>
/// <param name="start">
/// The start.
/// </param>
/// <param name="r">
/// The room.
/// </param>
/// <returns>
/// A list of blocks which is the room.
/// </returns>
internal static IEnumerable<Block> DeserializeInit(Message m, uint start, Room r)
{
var list = new List<Block>();
try
{
//// FULL CREDIT TO @kevin-brown FOR THE FOLLOWING CODE
//// I wrote it in my own way in C# but he made the original.
//// Without it I would not know how to do this.
//// Praise him. (this is mainly due to my laziness)
// First, fill the entire map with blank blocks (so that you don't get null exceptions).
ClearMap(r);
// And now replace empty blocks with the ones that already exist.
uint messageIndex = start;
// Iterate through each internal set of messages.
while (messageIndex < m.Count && !(m[messageIndex] is string))
{
// The ID is first.
int blockId = m.GetInteger(messageIndex++);
// Then the z.
int z = m.GetInteger(messageIndex++);
// Then the list of all X coordinates of given block
byte[] xa = m.GetByteArray(messageIndex++);
// Then the list of all Y coordinates of given block
byte[] ya = m.GetByteArray(messageIndex++);
int rotation = 0, note = 0, type = 0, portalId = 0, destination = 0, coins = 0;
bool isVisible = false, isGate = false;
string roomDestination = string.Empty;
string signMessage = string.Empty;
// Get the variables that are unique to the current block
switch (blockId)
{
case BlockIds.Action.Portals.Invisible:
case BlockIds.Action.Portals.Normal:
rotation = m.GetInteger(messageIndex++);
portalId = m.GetInteger(messageIndex++);
destination = m.GetInteger(messageIndex++);
isVisible = blockId != BlockIds.Action.Portals.Invisible;
break;
case BlockIds.Action.Portals.World:
roomDestination = m.GetString(messageIndex++);
break;
case BlockIds.Action.Sign:
signMessage = m.GetString(messageIndex++);
break;
case BlockIds.Action.Coins.GoldGate:
case BlockIds.Action.Coins.GoldDoor:
coins = m.GetInteger(messageIndex++);
isGate = blockId == BlockIds.Action.Coins.GoldGate;
break;
case BlockIds.Action.Music.Percussion:
type = m.GetInteger(messageIndex++);
break;
case BlockIds.Action.Music.Piano:
note = m.GetInteger(messageIndex++);
break;
case BlockIds.Action.Hazards.Spike:
case BlockIds.Decorative.SciFi2013.Orangestraight:
case BlockIds.Decorative.SciFi2013.Orangebend:
case BlockIds.Decorative.SciFi2013.Greenstraight:
case BlockIds.Decorative.SciFi2013.Greenbend:
case BlockIds.Decorative.SciFi2013.Bluestraight:
case BlockIds.Decorative.SciFi2013.Bluebend:
case BlockIds.Blocks.OneWay.Blue:
case BlockIds.Blocks.OneWay.Red:
case BlockIds.Blocks.OneWay.Yellow:
case BlockIds.Blocks.OneWay.Purple:
rotation = m.GetInteger(messageIndex++);
break;
case BlockIds.Action.Effect.Fly:
case BlockIds.Action.Effect.Jump:
case BlockIds.Action.Effect.LowGravity:
case BlockIds.Action.Effect.Protection:
case BlockIds.Action.Effect.Speed:
messageIndex++;
break;
}
// Some variables to simplify things.
for (int pos = 0; pos < ya.Length; pos += 2)
{
// Extract the X and Y positions from the array.
int x = (xa[pos] * 256) + xa[pos + 1];
int y = (ya[pos] * 256) + ya[pos + 1];
// Ascertain the block from the ID.
// Add block accordingly.
switch (blockId)
{
case BlockIds.Action.Portals.Invisible:
case BlockIds.Action.Portals.Normal:
list.Add(new PortalBlock(x, y, rotation, portalId, destination, isVisible));
break;
case BlockIds.Action.Portals.World:
list.Add(new RoomPortalBlock(x, y, roomDestination));
break;
case BlockIds.Action.Coins.GoldGate:
list.Add(new CoinBlock(BlockIds.Action.Coins.GoldGate, x, y, coins));
break;
case BlockIds.Action.Coins.GoldDoor:
list.Add(new CoinBlock(BlockIds.Action.Coins.GoldDoor, x, y, coins));
break;
case BlockIds.Action.Music.Percussion:
list.Add(new PercussionBlock(x, y, type));
break;
case BlockIds.Action.Music.Piano:
list.Add(new PianoBlock(x, y, note));
break;
case BlockIds.Action.Sign:
list.Add(new TextBlock(blockId, x, y, signMessage));
break;
default:
list.Add(new Block(blockId, x, y, z, rotation));
break;
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Error loading existing blocks:\n" + e);
}
SkylightMessage("Done loading blocks");
return list;
}
/// <summary>
/// Return the correct portal ID based on whether or not the portal is visible or invisible.
/// </summary>
/// <param name="visible">
/// if set to <c>true</c> [visible].
/// </param>
/// <returns>
/// Returns the id of the portal based on its visibility.
/// </returns>
internal static int PortalIdByVisible(bool visible)
{
return visible ? BlockIds.Action.Portals.Normal : BlockIds.Action.Portals.Invisible;
}
/// <summary>
/// Main logging method.
/// </summary>
/// <param name="m">
/// The message.
/// </param>
internal static void SkylightMessage(string m)
{
ProgramMessage(m);
}
#endregion
}
}
| |
#region License
// /*
// See license included in this library folder.
// */
#endregion
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using Sqloogle.Libs.NLog.Common;
using Sqloogle.Libs.NLog.Config;
using Sqloogle.Libs.NLog.Internal;
using Sqloogle.Libs.NLog.Layouts;
#if !NET_CF && !SILVERLIGHT
namespace Sqloogle.Libs.NLog.Targets
{
/// <summary>
/// Writes log message to the Event Log.
/// </summary>
/// <seealso href="http://nlog-project.org/wiki/EventLog_target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/EventLog/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/EventLog/Simple/Example.cs" />
/// </example>
[Target("EventLog")]
public class EventLogTarget : TargetWithLayout, IInstallable
{
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget" /> class.
/// </summary>
public EventLogTarget()
{
Source = AppDomain.CurrentDomain.FriendlyName;
Log = "Application";
MachineName = ".";
}
/// <summary>
/// Gets or sets the name of the machine on which Event Log service is running.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
[DefaultValue(".")]
public string MachineName { get; set; }
/// <summary>
/// Gets or sets the layout that renders event ID.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
public Layout EventId { get; set; }
/// <summary>
/// Gets or sets the layout that renders event Category.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
public Layout Category { get; set; }
/// <summary>
/// Gets or sets the value to be used as the event Source.
/// </summary>
/// <remarks>
/// By default this is the friendly name of the current AppDomain.
/// </remarks>
/// <docgen category='Event Log Options' order='10' />
public string Source { get; set; }
/// <summary>
/// Gets or sets the name of the Event Log to write to. This can be System, Application or
/// any user-defined name.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
[DefaultValue("Application")]
public string Log { get; set; }
/// <summary>
/// Performs installation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Install(InstallationContext installationContext)
{
if (EventLog.SourceExists(Source, MachineName))
{
var currentLogName = EventLog.LogNameFromSourceName(Source, MachineName);
if (currentLogName != Log)
{
// re-create the association between Log and Source
EventLog.DeleteEventSource(Source, MachineName);
var escd = new EventSourceCreationData(Source, Log)
{
MachineName = MachineName
};
EventLog.CreateEventSource(escd);
}
}
else
{
var escd = new EventSourceCreationData(Source, Log)
{
MachineName = MachineName
};
EventLog.CreateEventSource(escd);
}
}
/// <summary>
/// Performs uninstallation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Uninstall(InstallationContext installationContext)
{
EventLog.DeleteEventSource(Source, MachineName);
}
/// <summary>
/// Determines whether the item is installed.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <returns>
/// Value indicating whether the item is installed or null if it is not possible to determine.
/// </returns>
public bool? IsInstalled(InstallationContext installationContext)
{
return EventLog.SourceExists(Source, MachineName);
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
var s = EventLog.LogNameFromSourceName(Source, MachineName);
if (s != Log)
{
CreateEventSourceIfNeeded();
}
}
/// <summary>
/// Writes the specified logging event to the event log.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
var message = Layout.Render(logEvent);
if (message.Length > 16384)
{
// limitation of EventLog API
message = message.Substring(0, 16384);
}
EventLogEntryType entryType;
if (logEvent.Level >= LogLevel.Error)
{
entryType = EventLogEntryType.Error;
}
else if (logEvent.Level >= LogLevel.Warn)
{
entryType = EventLogEntryType.Warning;
}
else
{
entryType = EventLogEntryType.Information;
}
var eventId = 0;
if (EventId != null)
{
eventId = Convert.ToInt32(EventId.Render(logEvent), CultureInfo.InvariantCulture);
}
short category = 0;
if (Category != null)
{
category = Convert.ToInt16(Category.Render(logEvent), CultureInfo.InvariantCulture);
}
EventLog.WriteEntry(Source, message, entryType, eventId, category);
}
private void CreateEventSourceIfNeeded()
{
// if we throw anywhere, we remain non-operational
try
{
if (EventLog.SourceExists(Source, MachineName))
{
var currentLogName = EventLog.LogNameFromSourceName(Source, MachineName);
if (currentLogName != Log)
{
// re-create the association between Log and Source
EventLog.DeleteEventSource(Source, MachineName);
var escd = new EventSourceCreationData(Source, Log)
{
MachineName = MachineName
};
EventLog.CreateEventSource(escd);
}
}
else
{
var escd = new EventSourceCreationData(Source, Log)
{
MachineName = MachineName
};
EventLog.CreateEventSource(escd);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error when connecting to EventLog: {0}", exception);
throw;
}
}
}
}
#endif
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
using AsterNET.IO;
using AsterNET.Manager.Action;
using AsterNET.Manager.Event;
using AsterNET.Manager.Response;
namespace AsterNET.Manager
{
/// <summary>
/// Default implementation of the ManagerReader interface.
/// </summary>
public class ManagerReader
{
#if LOGGER
private readonly Logger logger = Logger.Instance();
#endif
private readonly ManagerConnection mrConnector;
private SocketConnection mrSocket;
private bool die;
private bool is_logoff;
private bool disconnect;
private byte[] lineBytes;
private string lineBuffer;
private readonly Queue<string> lineQueue;
private ResponseHandler pingHandler;
private bool processingCommandResult;
private bool wait4identiier;
private DateTime lastPacketTime;
private readonly Dictionary<string, string> packet;
private readonly List<string> commandList;
#region ManagerReader(dispatcher, asteriskServer)
/// <summary>
/// Creates a new ManagerReader.
/// </summary>
/// <param name="dispatcher">the dispatcher to use for dispatching events and responses.</param>
public ManagerReader(ManagerConnection connection)
{
mrConnector = connection;
die = false;
lineQueue = new Queue<string>();
packet = new Dictionary<string, string>();
commandList = new List<string>();
}
#endregion
#region Socket
/// <summary>
/// Sets the socket to use for reading from the asterisk server.
/// </summary>
internal SocketConnection Socket
{
set { mrSocket = value; }
}
#endregion
#region Die
internal bool Die
{
get { return die; }
set
{
die = value;
if (die)
mrSocket = null;
}
}
#endregion
#region IsLogoff
internal bool IsLogoff
{
set { is_logoff = value; }
}
#endregion
#region mrReaderCallbback(IAsyncResult ar)
/// <summary>
/// Async Read callback
/// </summary>
/// <param name="ar">IAsyncResult</param>
private void mrReaderCallbback(IAsyncResult ar)
{
// mreader = Mr.Reader
var mrReader = (ManagerReader) ar.AsyncState;
if (mrReader.die)
return;
SocketConnection mrSocket = mrReader.mrSocket;
if (mrSocket == null || mrSocket.TcpClient == null)
{
// No socket - it's DISCONNECT !!!
disconnect = true;
return;
}
NetworkStream nstream = mrSocket.NetworkStream;
if (nstream == null)
{
// No network stream - it's DISCONNECT !!!
disconnect = true;
return;
}
try
{
int count = nstream.EndRead(ar);
if (count == 0)
{
// No received data - it's may be DISCONNECT !!!
if (!is_logoff)
disconnect = true;
return;
}
string line = mrSocket.Encoding.GetString(mrReader.lineBytes, 0, count);
mrReader.lineBuffer += line;
int idx;
// \n - because not all dev in Digium use \r\n
// .Trim() kill \r
lock (((ICollection) lineQueue).SyncRoot)
while (!string.IsNullOrEmpty(mrReader.lineBuffer) && (idx = mrReader.lineBuffer.IndexOf('\n')) >= 0)
{
line = idx > 0 ? mrReader.lineBuffer.Substring(0, idx).Trim() : string.Empty;
mrReader.lineBuffer = (idx + 1 < mrReader.lineBuffer.Length
? mrReader.lineBuffer.Substring(idx + 1)
: string.Empty);
lineQueue.Enqueue(line);
}
// Give a next portion !!!
nstream.BeginRead(mrReader.lineBytes, 0, mrReader.lineBytes.Length, mrReaderCallbback, mrReader);
}
#if LOGGER
catch (Exception ex)
{
mrReader.logger.Error("Read data error", ex.Message);
#else
catch
{
#endif
// Any catch - disconncatch !
disconnect = true;
if (mrReader.mrSocket != null)
mrReader.mrSocket.Close();
mrReader.mrSocket = null;
}
}
#endregion
#region Reinitialize
internal void Reinitialize()
{
mrSocket.Initial = false;
disconnect = false;
lineQueue.Clear();
packet.Clear();
commandList.Clear();
lineBuffer = string.Empty;
lineBytes = new byte[mrSocket.TcpClient.ReceiveBufferSize];
lastPacketTime = DateTime.Now;
wait4identiier = true;
processingCommandResult = false;
mrSocket.NetworkStream.BeginRead(lineBytes, 0, lineBytes.Length, mrReaderCallbback, this);
lastPacketTime = DateTime.Now;
}
#endregion
#region Run()
/// <summary>
/// Reads line by line from the asterisk server, sets the protocol identifier as soon as it is
/// received and dispatches the received events and responses via the associated dispatcher.
/// </summary>
/// <seealso cref="ManagerConnection.DispatchEvent(ManagerEvent)" />
/// <seealso cref="ManagerConnection.DispatchResponse(Response.ManagerResponse)" />
/// <seealso cref="ManagerConnection.setProtocolIdentifier(String)" />
internal void Run()
{
if (mrSocket == null)
throw new SystemException("Unable to run: socket is null.");
string line;
while (true)
{
try
{
while (!die)
{
#region check line from *
if (!is_logoff)
{
if (mrSocket != null && mrSocket.Initial)
{
Reinitialize();
}
else if (disconnect)
{
disconnect = false;
mrConnector.DispatchEvent(new DisconnectEvent(mrConnector));
}
}
if (lineQueue.Count == 0)
{
if (lastPacketTime.AddMilliseconds(mrConnector.PingInterval) < DateTime.Now
&& mrConnector.PingInterval > 0
&& mrSocket != null
&& !wait4identiier
&& !is_logoff
)
{
if (pingHandler != null)
{
if (pingHandler.Response == null)
{
// If one PingInterval from Ping without Pong then send Disconnect event
mrConnector.RemoveResponseHandler(pingHandler);
mrConnector.DispatchEvent(new DisconnectEvent(mrConnector));
}
pingHandler.Free();
pingHandler = null;
}
else
{
// Send PING to *
try
{
pingHandler = new ResponseHandler(new PingAction(), null);
mrConnector.SendAction(pingHandler.Action, pingHandler);
}
catch
{
disconnect = true;
mrSocket = null;
}
}
lastPacketTime = DateTime.Now;
}
Thread.Sleep(50);
continue;
}
#endregion
lastPacketTime = DateTime.Now;
lock (((ICollection) lineQueue).SyncRoot)
line = lineQueue.Dequeue().Trim();
#if LOGGER
logger.Debug(line);
#endif
#region processing Response: Follows
if (processingCommandResult)
{
string lineLower = line.ToLower(Helper.CultureInfo);
if (lineLower == "--end command--" || lineLower == "")
{
var commandResponse = new CommandResponse();
Helper.SetAttributes(commandResponse, packet);
commandResponse.Result = commandList;
processingCommandResult = false;
packet.Clear();
mrConnector.DispatchResponse(commandResponse);
}
else if (lineLower.StartsWith("privilege: ")
|| lineLower.StartsWith("actionid: ")
|| lineLower.StartsWith("timestamp: ")
|| lineLower.StartsWith("server: ")
)
Helper.AddKeyValue(packet, line);
else
commandList.Add(line);
continue;
}
#endregion
#region collect key: value and ProtocolIdentifier
if (!string.IsNullOrEmpty(line))
{
if (wait4identiier && line.StartsWith("Asterisk Call Manager"))
{
wait4identiier = false;
var connectEvent = new ConnectEvent(mrConnector);
connectEvent.ProtocolIdentifier = line;
mrConnector.DispatchEvent(connectEvent);
continue;
}
if (line.Trim().ToLower(Helper.CultureInfo) == "response: follows"
|| line.Trim().ToLower(Helper.CultureInfo).EndsWith("command output follows"))
{
// Switch to wait "--END COMMAND--"/"" mode
processingCommandResult = true;
commandList.Clear();
Helper.AddKeyValue(packet, line);
continue;
}
Helper.AddKeyValue(packet, line);
continue;
}
#endregion
#region process events and responses
if (packet.ContainsKey("event"))
mrConnector.DispatchEvent(packet);
else if (packet.ContainsKey("response"))
mrConnector.DispatchResponse(packet);
#endregion
packet.Clear();
}
if (mrSocket != null)
mrSocket.Close();
break;
}
#if LOGGER
catch (Exception ex)
{
logger.Info("Exception : {0}", ex.Message);
#else
catch
{
#endif
}
if (die)
break;
#if LOGGER
logger.Info("No die, any error - send disconnect.");
#endif
mrConnector.DispatchEvent(new DisconnectEvent(mrConnector));
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using Server;
using Server.Engines.PartySystem;
using Server.Misc;
using Server.Guilds;
using Server.Mobiles;
using Server.Network;
using Server.ContextMenus;
namespace Server.Items
{
public class SleepingBody : Container
{
private Mobile m_Owner;
private string m_SleepingBodyName; // Value of the SleepingNameAttribute attached to the owner when he died -or- null if the owner had no SleepingBodyNameAttribute; use "the remains of ~name~"
private bool m_Blessed;
private ArrayList m_EquipItems; // List of items equiped when the owner died. Ingame, these items display /on/ the SleepingBody, not just inside
private bool m_spell;
private DateTime m_NextSnoreTrigger;
[CommandProperty( AccessLevel.GameMaster )]
public Mobile Owner
{
get{ return m_Owner; }
}
public ArrayList EquipItems
{
get{ return m_EquipItems; }
}
[CommandProperty( AccessLevel.GameMaster )]
public bool Invuln
{
get{ return m_Blessed; }
}
[Constructable]
public SleepingBody( Mobile owner, bool blessed ) : this( owner, blessed, true )
{
}
[Constructable]
public SleepingBody( Mobile owner, bool blessed, bool isSpell ) : base( 0x2006 )
{
Stackable = true; // To supress console warnings, stackable must be true
Amount = owner.Body; // protocol defines that for itemid 0x2006, amount=body
Stackable = false;
m_Blessed = blessed;
Movable = false;
m_Owner = owner;
Name = m_Owner.Name;
m_SleepingBodyName = GetBodyName( owner );
Hue = m_Owner.Hue;
Direction = m_Owner.Direction;
m_spell = isSpell;
m_EquipItems = new ArrayList();
AddFromLayer( m_Owner, Layer.FirstValid, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.TwoHanded, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Shoes, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Pants, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Shirt, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Helm, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Gloves, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Ring, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Neck, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Hair, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Waist, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.InnerTorso, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Bracelet, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.FacialHair, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.MiddleTorso, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Earrings, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Arms, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.Cloak, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.OuterTorso, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.OuterLegs, ref m_EquipItems );
AddFromLayer( m_Owner, Layer.LastUserValid, ref m_EquipItems );
}
private void AddFromLayer( Mobile from, Layer layer, ref ArrayList list )
{
if( list == null )
list = new ArrayList();
Item worn = from.FindItemOnLayer( layer );
if ( worn != null )
{
Item item = new Item();
item.ItemID = worn.ItemID;
item.Hue = worn.Hue;
item.Layer = layer;
DropItem( item );
list.Add( item );
}
}
public override void OnDoubleClick( Mobile from )
{
from.SendLocalizedMessage( 1001018 ); // You cannot perform negative acts on your target.
}
public override bool HandlesOnMovement{ get{ return true; } } // Tell the core that we implement OnMovement
public override bool OnDragDropInto( Mobile from, Item item, Point3D p )
{
from.SendLocalizedMessage( 1005468, "", 0x8A5 ); // Me Sleepy.
return false;
}
public override bool OnDragDrop(Mobile from, Item dropped)
{
from.SendLocalizedMessage( 1005468, "", 0x8A5 ); // Me Sleepy.
return false;
}
public override bool CheckContentDisplay( Mobile from )
{
return false;
}
public override bool DisplaysContent{ get{ return false; } }
public override void OnAfterDelete()
{
if( m_Owner != null )
{
m_Owner.Z = this.Z;
m_Owner.Blessed = this.m_Blessed;
}
for( int i = 0; i < m_EquipItems.Count; i++ )
{
object o = m_EquipItems[i];
if( o != null && o is Item )
{
Item item = (Item)o;
item.Delete();
}
}
base.OnAfterDelete();
}
public SleepingBody( Serial serial ) : base( serial )
{
}
//public override void SendInfoTo( NetState state )
//{
//base.SendInfoTo( state );
public override void SendInfoTo( NetState state, bool sendOplPacket )
{
base.SendInfoTo( state, sendOplPacket );
if ( ItemID == 0x2006 )
{
state.Send( new SleepingBodyContent( state.Mobile, this ) );
state.Send( new SleepingBodyEquip( state.Mobile, this ) );
}
}
public override void AddNameProperty( ObjectPropertyList list )
{
if ( m_SleepingBodyName != null )
list.Add( m_SleepingBodyName );
else
list.Add( 1049644, String.Format( "Sleeping {0}", Name ) );
}
public override void OnSingleClick( Mobile from )
{
LabelTo( from, m_SleepingBodyName == null ? String.Format( "Sleeping {0}", Name ) : m_SleepingBodyName );
}
public static string GetBodyName( Mobile m )
{
Type t = m.GetType();
object[] attrs = t.GetCustomAttributes( typeof( SleepingNameAttribute ), true );
if ( attrs != null && attrs.Length > 0 )
{
SleepingNameAttribute attr = attrs[0] as SleepingNameAttribute;
if ( attr != null )
return attr.Name;
}
return m.Name;
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 );
writer.Write(m_spell); // version 1
writer.Write(m_Owner); // version 0
writer.Write(m_SleepingBodyName);
writer.Write(m_Blessed);
writer.WriteItemList( m_EquipItems, true );
}
public override void Deserialize( GenericReader reader )
{
m_spell = true;
base.Deserialize( reader );
int version = reader.ReadInt();
switch( version )
{
case 1:
{
m_spell = reader.ReadBool();
goto case 0;
}
case 0:
{
m_Owner = reader.ReadMobile();
m_SleepingBodyName = reader.ReadString();
m_Blessed = reader.ReadBool();
m_EquipItems = reader.ReadItemList();
break;
}
}
m_NextSnoreTrigger = DateTime.Now;
// Delete on Server restart if spell action
if( m_spell )
this.Delete();
}
public bool CheckRange( Point3D loc, Point3D oldLoc, int range )
{
return CheckRange( loc, range ) && !CheckRange( oldLoc, range );
}
public bool CheckRange( Point3D loc, int range )
{
return ( (this.Z + 8) >= loc.Z && (loc.Z + 16) > this.Z )
&& Utility.InRange( GetWorldLocation(), loc, range );
}
public override void OnMovement( Mobile m, Point3D oldLocation )
{
base.OnMovement( m, oldLocation );
if ( m.Location == oldLocation )
return;
if ( CheckRange( m.Location, oldLocation, 5 ) && DateTime.Now >= m_NextSnoreTrigger )
{
m_NextSnoreTrigger = DateTime.Now + TimeSpan.FromSeconds(Utility.Random(5,10));
if(this != null&&this.Owner!=null)
{
this.PublicOverheadMessage(0,Owner.SpeechHue,false,"zZz");
Owner.PlaySound( Owner.Female ? 819 : 1093);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
using static Interop.Crypt32;
namespace Internal.Cryptography.Pal.Windows
{
internal sealed partial class DecryptorPalWindows : DecryptorPal
{
public sealed override ContentInfo TryDecrypt(RecipientInfo recipientInfo, X509Certificate2 cert, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore, out Exception exception)
{
Debug.Assert(recipientInfo != null);
Debug.Assert(cert != null);
Debug.Assert(originatorCerts != null);
Debug.Assert(extraStore != null);
CryptKeySpec keySpec;
exception = TryGetKeySpecForCertificate(cert, out keySpec);
if (exception != null)
return null;
// Desktop compat: We pass false for "silent" here (thus allowing crypto providers to display UI.)
using (SafeProvOrNCryptKeyHandle hKey = TryGetCertificatePrivateKey(cert, false, out exception))
{
if (hKey == null)
return null;
RecipientInfoType type = recipientInfo.Type;
switch (type)
{
case RecipientInfoType.KeyTransport:
exception = TryDecryptTrans((KeyTransRecipientInfo)recipientInfo, hKey, keySpec);
break;
case RecipientInfoType.KeyAgreement:
exception = TryDecryptAgree((KeyAgreeRecipientInfo)recipientInfo, hKey, keySpec, originatorCerts, extraStore);
break;
default:
// Since only the framework can construct RecipientInfo's, we're at fault if we get here. So it's okay to assert and throw rather than
// returning to the caller.
Debug.Fail($"Unexpected RecipientInfoType: {type}");
throw new NotSupportedException();
}
if (exception != null)
return null;
// If we got here, we successfully decrypted. Return the decrypted content.
return _hCryptMsg.GetContentInfo();
}
}
private static Exception TryGetKeySpecForCertificate(X509Certificate2 cert, out CryptKeySpec keySpec)
{
using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
{
int cbSize = 0;
if (Interop.Crypt32.CertGetCertificateContextProperty(
hCertContext,
CertContextPropId.CERT_NCRYPT_KEY_HANDLE_PROP_ID,
null,
ref cbSize))
{
keySpec = CryptKeySpec.CERT_NCRYPT_KEY_SPEC;
return null;
}
if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cbSize))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetLastWin32Error());
keySpec = default(CryptKeySpec);
return errorCode.ToCryptographicException();
}
byte[] pData = new byte[cbSize];
unsafe
{
fixed (byte* pvData = pData)
{
if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, pData, ref cbSize))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetLastWin32Error());
keySpec = default(CryptKeySpec);
return errorCode.ToCryptographicException();
}
CRYPT_KEY_PROV_INFO* pCryptKeyProvInfo = (CRYPT_KEY_PROV_INFO*)pvData;
keySpec = pCryptKeyProvInfo->dwKeySpec;
return null;
}
}
}
}
private static SafeProvOrNCryptKeyHandle TryGetCertificatePrivateKey(X509Certificate2 cert, bool silent, out Exception exception)
{
CryptAcquireCertificatePrivateKeyFlags flags =
CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_USE_PROV_INFO_FLAG
| CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_COMPARE_KEY_FLAG
// Note: Using CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG rather than CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG because wrapping an NCrypt wrapper over CAPI keys unconditionally
// causes some legacy features (such as RC4 support) to break.
| CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG;
if (silent)
{
flags |= CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_SILENT_FLAG;
}
bool mustFree;
using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
{
IntPtr hKey;
int cbSize = IntPtr.Size;
if (Interop.Crypt32.CertGetCertificateContextProperty(
hCertContext,
CertContextPropId.CERT_NCRYPT_KEY_HANDLE_PROP_ID,
out hKey,
ref cbSize))
{
exception = null;
return new SafeProvOrNCryptKeyHandleUwp(hKey, hCertContext);
}
CryptKeySpec keySpec;
if (!Interop.Crypt32.CryptAcquireCertificatePrivateKey(hCertContext, flags, IntPtr.Zero, out hKey, out keySpec, out mustFree))
{
exception = Marshal.GetHRForLastWin32Error().ToCryptographicException();
return null;
}
// We need to know whether we got back a CRYPTPROV or NCrypt handle. Unfortunately, NCryptIsKeyHandle() is a prohibited api on UWP.
// Fortunately, CryptAcquireCertificatePrivateKey() is documented to tell us which one we got through the keySpec value.
bool isNCrypt;
switch (keySpec)
{
case CryptKeySpec.AT_KEYEXCHANGE:
case CryptKeySpec.AT_SIGNATURE:
isNCrypt = false;
break;
case CryptKeySpec.CERT_NCRYPT_KEY_SPEC:
isNCrypt = true;
break;
default:
// As of this writing, we've exhausted all the known values of keySpec. We have no idea what kind of key handle we got so
// play it safe and fail fast.
throw new NotSupportedException(SR.Format(SR.Cryptography_Cms_UnknownKeySpec, keySpec));
}
SafeProvOrNCryptKeyHandleUwp hProvOrNCryptKey = new SafeProvOrNCryptKeyHandleUwp(hKey, ownsHandle: mustFree, isNcrypt: isNCrypt);
exception = null;
return hProvOrNCryptKey;
}
}
private Exception TryDecryptTrans(KeyTransRecipientInfo recipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec)
{
KeyTransRecipientInfoPalWindows pal = (KeyTransRecipientInfoPalWindows)(recipientInfo.Pal);
CMSG_CTRL_DECRYPT_PARA decryptPara;
decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_DECRYPT_PARA>();
decryptPara.hKey = hKey;
decryptPara.dwKeySpec = keySpec;
decryptPara.dwRecipientIndex = pal.Index;
bool success = Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_DECRYPT, ref decryptPara);
if (!success)
return Marshal.GetHRForLastWin32Error().ToCryptographicException();
return null;
}
private Exception TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
{
unsafe
{
KeyAgreeRecipientInfoPalWindows pal = (KeyAgreeRecipientInfoPalWindows)(keyAgreeRecipientInfo.Pal);
return pal.WithCmsgCmsRecipientInfo<Exception>(
delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* pKeyAgreeRecipientInfo)
{
CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara = default(CMSG_CTRL_KEY_AGREE_DECRYPT_PARA);
decryptPara.cbSize = Marshal.SizeOf<CMSG_CTRL_KEY_AGREE_DECRYPT_PARA>();
decryptPara.hProv = hKey;
decryptPara.dwKeySpec = keySpec;
decryptPara.pKeyAgree = pKeyAgreeRecipientInfo;
decryptPara.dwRecipientIndex = pal.Index;
decryptPara.dwRecipientEncryptedKeyIndex = pal.SubIndex;
CMsgKeyAgreeOriginatorChoice originatorChoice = pKeyAgreeRecipientInfo->dwOriginatorChoice;
switch (originatorChoice)
{
case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_CERT:
{
X509Certificate2Collection candidateCerts = new X509Certificate2Collection();
candidateCerts.AddRange(Helpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.CurrentUser, openExistingOnly: true));
candidateCerts.AddRange(Helpers.GetStoreCertificates(StoreName.AddressBook, StoreLocation.LocalMachine, openExistingOnly: true));
candidateCerts.AddRange(originatorCerts);
candidateCerts.AddRange(extraStore);
SubjectIdentifier originatorId = pKeyAgreeRecipientInfo->OriginatorCertId.ToSubjectIdentifier();
X509Certificate2 originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId);
if (originatorCert == null)
return ErrorCode.CRYPT_E_NOT_FOUND.ToCryptographicException();
using (SafeCertContextHandle hCertContext = originatorCert.CreateCertContextHandle())
{
CERT_CONTEXT* pOriginatorCertContext = hCertContext.DangerousGetCertContext();
decryptPara.OriginatorPublicKey = pOriginatorCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey;
// Do not factor this call out of the switch statement as leaving this "using" block will free up
// native memory that decryptPara points to.
return TryExecuteDecryptAgree(ref decryptPara);
}
}
case CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY:
{
decryptPara.OriginatorPublicKey = pKeyAgreeRecipientInfo->OriginatorPublicKeyInfo.PublicKey;
return TryExecuteDecryptAgree(ref decryptPara);
}
default:
return new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Originator_Identifier_Choice, originatorChoice));
}
});
}
}
private Exception TryExecuteDecryptAgree(ref CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara)
{
if (!Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_KEY_AGREE_DECRYPT, ref decryptPara))
{
ErrorCode errorCode = (ErrorCode)(Marshal.GetHRForLastWin32Error());
return errorCode.ToCryptographicException();
}
return null;
}
}
}
| |
namespace EIDSS.Reports.Document.Veterinary.LivestockInvestigation
{
partial class DiagnosisReport
{
/// <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 Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DiagnosisReport));
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand();
this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.diagnosisDataSet1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.DiagnosisDataSet();
this.spRepVetDiagnosisTableAdapter = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.DiagnosisDataSetTableAdapters.spRepVetDiagnosisTableAdapter();
this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand();
this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.diagnosisDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(6, 6, 0, 0, 100F);
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Name = "PageHeader";
this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow3,
this.xrTableRow4,
this.xrTableRow5,
this.xrTableRow6});
this.xrTable1.StylePriority.UseFont = false;
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2,
this.xrTableCell3,
this.xrTableCell1,
this.xrTableCell16});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.StylePriority.UseFont = false;
//
// xrTableCell2
//
this.xrTableCell2.Name = "xrTableCell2";
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
//
// xrTableCell3
//
this.xrTableCell3.Name = "xrTableCell3";
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
//
// xrTableCell1
//
this.xrTableCell1.Name = "xrTableCell1";
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
//
// xrTableCell16
//
this.xrTableCell16.Name = "xrTableCell16";
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6,
this.xrTableCell4,
this.xrTableCell17});
this.xrTableRow3.Name = "xrTableRow3";
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
//
// xrTableCell5
//
this.xrTableCell5.Name = "xrTableCell5";
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
//
// xrTableCell6
//
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.strTentativeDiagnosis")});
this.xrTableCell6.Name = "xrTableCell6";
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
//
// xrTableCell4
//
this.xrTableCell4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.strTentativeDiagnosisCode")});
this.xrTableCell4.Name = "xrTableCell4";
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
//
// xrTableCell17
//
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.datTentativeDiagnosisDate", "{0:dd/MM/yyyy}")});
this.xrTableCell17.Name = "xrTableCell17";
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell8,
this.xrTableCell13,
this.xrTableCell18});
this.xrTableRow4.Name = "xrTableRow4";
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
//
// xrTableCell7
//
this.xrTableCell7.Name = "xrTableCell7";
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
//
// xrTableCell8
//
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.strTentativeDiagnosis1")});
this.xrTableCell8.Name = "xrTableCell8";
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
//
// xrTableCell13
//
this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.strTentativeDiagnosis1Code")});
this.xrTableCell13.Name = "xrTableCell13";
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
//
// xrTableCell18
//
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.datTentativeDiagnosis1Date", "{0:dd/MM/yyyy}")});
this.xrTableCell18.Name = "xrTableCell18";
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9,
this.xrTableCell10,
this.xrTableCell14,
this.xrTableCell19});
this.xrTableRow5.Name = "xrTableRow5";
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
//
// xrTableCell9
//
this.xrTableCell9.Name = "xrTableCell9";
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
//
// xrTableCell10
//
this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.strTentativeDiagnosis2")});
this.xrTableCell10.Name = "xrTableCell10";
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
//
// xrTableCell14
//
this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.strTentativeDiagnosis2Code")});
this.xrTableCell14.Name = "xrTableCell14";
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
//
// xrTableCell19
//
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.datTentativeDiagnosis2Date", "{0:dd/MM/yyyy}")});
this.xrTableCell19.Name = "xrTableCell19";
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell11,
this.xrTableCell12,
this.xrTableCell15,
this.xrTableCell20});
this.xrTableRow6.Name = "xrTableRow6";
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
//
// xrTableCell11
//
this.xrTableCell11.Name = "xrTableCell11";
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
//
// xrTableCell12
//
this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.strFinalDiagnosis")});
this.xrTableCell12.Name = "xrTableCell12";
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
//
// xrTableCell15
//
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.strFinalDiagnosisCode")});
this.xrTableCell15.Name = "xrTableCell15";
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
//
// xrTableCell20
//
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetDiagnosis.datFinalDiagnosisDate", "{0:dd/MM/yyyy}")});
this.xrTableCell20.Name = "xrTableCell20";
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.Name = "PageFooter";
this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel1});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Name = "ReportHeader";
this.ReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.ReportHeader.StylePriority.UsePadding = false;
//
// xrLabel1
//
this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseBorders = false;
this.xrLabel1.StylePriority.UseFont = false;
this.xrLabel1.StylePriority.UseTextAlignment = false;
//
// diagnosisDataSet1
//
this.diagnosisDataSet1.DataSetName = "DiagnosisDataSet";
this.diagnosisDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// spRepVetDiagnosisTableAdapter
//
this.spRepVetDiagnosisTableAdapter.ClearBeforeFill = true;
//
// topMarginBand1
//
resources.ApplyResources(this.topMarginBand1, "topMarginBand1");
this.topMarginBand1.Name = "topMarginBand1";
//
// bottomMarginBand1
//
resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1");
this.bottomMarginBand1.Name = "bottomMarginBand1";
//
// DiagnosisReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.topMarginBand1,
this.bottomMarginBand1});
this.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.DataAdapter = this.spRepVetDiagnosisTableAdapter;
this.DataMember = "spRepVetDiagnosis";
this.DataSource = this.diagnosisDataSet1;
this.ExportOptions.Xls.SheetName = resources.GetString("DiagnosisReport.ExportOptions.Xls.SheetName");
this.ExportOptions.Xlsx.SheetName = resources.GetString("DiagnosisReport.ExportOptions.Xlsx.SheetName");
resources.ApplyResources(this, "$this");
this.Version = "14.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.diagnosisDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.PageHeaderBand PageHeader;
private DevExpress.XtraReports.UI.PageFooterBand PageFooter;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DiagnosisDataSet diagnosisDataSet1;
private EIDSS.Reports.Document.Veterinary.LivestockInvestigation.DiagnosisDataSetTableAdapters.spRepVetDiagnosisTableAdapter spRepVetDiagnosisTableAdapter;
private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1;
private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ServiceModel.Syndication
{
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
public class XmlSyndicationContent : SyndicationContent
{
private XmlBuffer _contentBuffer;
private SyndicationElementExtension _extension;
private string _type;
// Saves the element in the reader to the buffer (attributes preserved)
// Type is populated from type attribute on reader
// Reader must be positioned at an element
public XmlSyndicationContent(XmlReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
SyndicationFeedFormatter.MoveToStartElement(reader);
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string name = reader.LocalName;
string ns = reader.NamespaceURI;
string value = reader.Value;
if (name == Atom10Constants.TypeTag && ns == string.Empty)
{
_type = value;
}
else if (!FeedUtils.IsXmlns(name, ns))
{
base.AttributeExtensions.Add(new XmlQualifiedName(name, ns), value);
}
}
reader.MoveToElement();
}
_type = string.IsNullOrEmpty(_type) ? Atom10Constants.XmlMediaType : _type;
_contentBuffer = new XmlBuffer(int.MaxValue);
using (XmlDictionaryWriter writer = _contentBuffer.OpenSection(XmlDictionaryReaderQuotas.Max))
{
writer.WriteNode(reader, false);
}
_contentBuffer.CloseSection();
_contentBuffer.Close();
}
public XmlSyndicationContent(string type, object dataContractExtension, XmlObjectSerializer dataContractSerializer)
{
_type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type;
_extension = new SyndicationElementExtension(dataContractExtension, dataContractSerializer);
}
public XmlSyndicationContent(string type, object xmlSerializerExtension, XmlSerializer serializer)
{
_type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type;
_extension = new SyndicationElementExtension(xmlSerializerExtension, serializer);
}
public XmlSyndicationContent(string type, SyndicationElementExtension extension)
{
if (extension == null)
{
throw new ArgumentNullException(nameof(extension));
}
_type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type;
_extension = extension;
}
protected XmlSyndicationContent(XmlSyndicationContent source)
: base(source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
_contentBuffer = source._contentBuffer;
_extension = source._extension;
_type = source._type;
}
public SyndicationElementExtension Extension
{
get
{
return _extension;
}
}
public override string Type
{
get { return _type; }
}
public override SyndicationContent Clone()
{
return new XmlSyndicationContent(this);
}
public XmlDictionaryReader GetReaderAtContent()
{
return GetReaderAtContentAsync().GetAwaiter().GetResult();
}
public TContent ReadContent<TContent>()
{
return ReadContent<TContent>((DataContractSerializer)null);
}
public TContent ReadContent<TContent>(XmlObjectSerializer dataContractSerializer)
{
return ReadContentAsync<TContent>(dataContractSerializer).GetAwaiter().GetResult();
}
public TContent ReadContent<TContent>(XmlSerializer serializer)
{
return ReadContentAsync<TContent>(serializer).GetAwaiter().GetResult();
}
public async Task<XmlDictionaryReader> GetReaderAtContentAsync()
{
await EnsureContentBufferAsync();
return _contentBuffer.GetReader(0);
}
public Task<TContent> ReadContentAsync<TContent>()
{
return ReadContentAsync<TContent>((DataContractSerializer)null);
}
public async Task<TContent> ReadContentAsync<TContent>(XmlObjectSerializer dataContractSerializer)
{
if (dataContractSerializer == null)
{
dataContractSerializer = new DataContractSerializer(typeof(TContent));
}
if (_extension != null)
{
return await _extension.GetObjectAsync<TContent>(dataContractSerializer);
}
else
{
Debug.Assert(_contentBuffer != null, "contentBuffer cannot be null");
using (XmlDictionaryReader reader = _contentBuffer.GetReader(0))
{
// skip past the content element
reader.ReadStartElement();
return (TContent)dataContractSerializer.ReadObject(reader, false);
}
}
}
public Task<TContent> ReadContentAsync<TContent>(XmlSerializer serializer)
{
if (serializer == null)
{
serializer = new XmlSerializer(typeof(TContent));
}
if (_extension != null)
{
return _extension.GetObjectAsync<TContent>(serializer);
}
else
{
Debug.Assert(_contentBuffer != null, "contentBuffer cannot be null");
using (XmlDictionaryReader reader = _contentBuffer.GetReader(0))
{
// skip past the content element
reader.ReadStartElement();
return Task.FromResult((TContent)serializer.Deserialize(reader));
//return (TContent)serializer.Deserialize(reader);
}
}
}
// does not write start element or type attribute, writes other attributes and rest of content
protected override void WriteContentsTo(XmlWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (_extension != null)
{
_extension.WriteToAsync(writer).GetAwaiter().GetResult();
}
else if (_contentBuffer != null)
{
using (XmlDictionaryReader reader = _contentBuffer.GetReader(0))
{
reader.MoveToStartElement();
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
while (reader.Depth >= 1 && reader.ReadState == ReadState.Interactive)
{
writer.WriteNode(reader, false);
}
}
}
}
}
private async Task EnsureContentBufferAsync()
{
if (_contentBuffer == null)
{
XmlBuffer tmp = new XmlBuffer(int.MaxValue);
using (XmlDictionaryWriter writer = tmp.OpenSection(XmlDictionaryReaderQuotas.Max))
{
await WriteToAsync(writer, Atom10Constants.ContentTag, Atom10Constants.Atom10Namespace);
}
tmp.CloseSection();
tmp.Close();
_contentBuffer = tmp;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Server;
using Server.Network;
namespace Server.Items
{
[Flipable( 0x1E5E, 0x1E5F )]
public class BulletinBoard : BaseBulletinBoard
{
[Constructable]
public BulletinBoard() : base( 0x1E5E )
{
}
public BulletinBoard( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
public abstract class BaseBulletinBoard : Item
{
private string m_BoardName;
[CommandProperty( AccessLevel.GameMaster )]
public string BoardName
{
get{ return m_BoardName; }
set{ m_BoardName = value; }
}
public BaseBulletinBoard( int itemID ) : base( itemID )
{
m_BoardName = "bulletin board";
Movable = false;
}
// Threads will be removed six hours after the last post was made
private static TimeSpan ThreadDeletionTime = TimeSpan.FromHours( 6.0 );
// A player may only create a thread once every two minutes
private static TimeSpan ThreadCreateTime = TimeSpan.FromMinutes( 2.0 );
// A player may only reply once every thirty seconds
private static TimeSpan ThreadReplyTime = TimeSpan.FromSeconds( 30.0 );
public static bool CheckTime( DateTime time, TimeSpan range )
{
return (time + range) < DateTime.Now;
}
public static string FormatTS( TimeSpan ts )
{
int totalSeconds = (int)ts.TotalSeconds;
int seconds = totalSeconds % 60;
int minutes = totalSeconds / 60;
if ( minutes != 0 && seconds != 0 )
return String.Format( "{0} minute{1} and {2} second{3}", minutes, minutes==1?"":"s", seconds, seconds==1?"":"s" );
else if ( minutes != 0 )
return String.Format( "{0} minute{1}", minutes, minutes==1?"":"s" );
else
return String.Format( "{0} second{1}", seconds, seconds==1?"":"s" );
}
public virtual void Cleanup()
{
List<Item> items = this.Items;
for ( int i = items.Count - 1; i >= 0; --i )
{
if ( i >= items.Count )
continue;
BulletinMessage msg = items[i] as BulletinMessage;
if ( msg == null )
continue;
if ( msg.Thread == null && CheckTime( msg.LastPostTime, ThreadDeletionTime ) )
{
msg.Delete();
RecurseDelete( msg ); // A root-level thread has expired
}
}
}
private void RecurseDelete( BulletinMessage msg )
{
List<Item> found = new List<Item>();
List<Item> items = this.Items;
for ( int i = items.Count - 1; i >= 0; --i )
{
if ( i >= items.Count )
continue;
BulletinMessage check = items[i] as BulletinMessage;
if ( check == null )
continue;
if ( check.Thread == msg )
{
check.Delete();
found.Add( check );
}
}
for ( int i = 0; i < found.Count; ++i )
RecurseDelete( (BulletinMessage)found[i] );
}
public virtual bool GetLastPostTime( Mobile poster, bool onlyCheckRoot, ref DateTime lastPostTime )
{
List<Item> items = this.Items;
bool wasSet = false;
for ( int i = 0; i < items.Count; ++i )
{
BulletinMessage msg = items[i] as BulletinMessage;
if ( msg == null || msg.Poster != poster )
continue;
if ( onlyCheckRoot && msg.Thread != null )
continue;
if ( msg.Time > lastPostTime )
{
wasSet = true;
lastPostTime = msg.Time;
}
}
return wasSet;
}
public override void OnDoubleClick( Mobile from )
{
if ( CheckRange( from ) )
{
Cleanup();
NetState state = from.NetState;
state.Send( new BBDisplayBoard( this ) );
if ( state.ContainerGridLines )
state.Send( new ContainerContent6017( from, this ) );
else
state.Send( new ContainerContent( from, this ) );
}
else
{
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that.
}
}
public virtual bool CheckRange( Mobile from )
{
if ( from.AccessLevel >= AccessLevel.GameMaster )
return true;
return ( from.Map == this.Map && from.InRange( GetWorldLocation(), 2 ) );
}
public void PostMessage( Mobile from, BulletinMessage thread, string subject, string[] lines )
{
if ( thread != null )
thread.LastPostTime = DateTime.Now;
AddItem( new BulletinMessage( from, thread, subject, lines ) );
}
public BaseBulletinBoard( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
writer.Write( (string) m_BoardName );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_BoardName = reader.ReadString();
break;
}
}
}
public static void Initialize()
{
PacketHandlers.Register( 0x71, 0, true, new OnPacketReceive( BBClientRequest ) );
}
public static void BBClientRequest( NetState state, PacketReader pvSrc )
{
Mobile from = state.Mobile;
int packetID = pvSrc.ReadByte();
BaseBulletinBoard board = World.FindItem( pvSrc.ReadInt32() ) as BaseBulletinBoard;
if ( board == null || !board.CheckRange( from ) )
return;
switch ( packetID )
{
case 3: BBRequestContent( from, board, pvSrc ); break;
case 4: BBRequestHeader( from, board, pvSrc ); break;
case 5: BBPostMessage( from, board, pvSrc ); break;
case 6: BBRemoveMessage( from, board, pvSrc ); break;
}
}
public static void BBRequestContent( Mobile from, BaseBulletinBoard board, PacketReader pvSrc )
{
BulletinMessage msg = World.FindItem( pvSrc.ReadInt32() ) as BulletinMessage;
if ( msg == null || msg.Parent != board )
return;
from.Send( new BBMessageContent( board, msg ) );
}
public static void BBRequestHeader( Mobile from, BaseBulletinBoard board, PacketReader pvSrc )
{
BulletinMessage msg = World.FindItem( pvSrc.ReadInt32() ) as BulletinMessage;
if ( msg == null || msg.Parent != board )
return;
from.Send( new BBMessageHeader( board, msg ) );
}
public static void BBPostMessage( Mobile from, BaseBulletinBoard board, PacketReader pvSrc )
{
BulletinMessage thread = World.FindItem( pvSrc.ReadInt32() ) as BulletinMessage;
if ( thread != null && thread.Parent != board )
thread = null;
int breakout = 0;
while ( thread != null && thread.Thread != null && breakout++ < 10 )
thread = thread.Thread;
DateTime lastPostTime = DateTime.MinValue;
if ( board.GetLastPostTime( from, ( thread == null ), ref lastPostTime ) )
{
if ( !CheckTime( lastPostTime, (thread == null ? ThreadCreateTime : ThreadReplyTime) ) )
{
if ( thread == null )
from.SendMessage( "You must wait {0} before creating a new thread.", FormatTS( ThreadCreateTime ) );
else
from.SendMessage( "You must wait {0} before replying to another thread.", FormatTS( ThreadReplyTime ) );
return;
}
}
string subject = pvSrc.ReadUTF8StringSafe( pvSrc.ReadByte() );
if ( subject.Length == 0 )
return;
string[] lines = new string[pvSrc.ReadByte()];
if ( lines.Length == 0 )
return;
for ( int i = 0; i < lines.Length; ++i )
lines[i] = pvSrc.ReadUTF8StringSafe( pvSrc.ReadByte() );
board.PostMessage( from, thread, subject, lines );
}
public static void BBRemoveMessage( Mobile from, BaseBulletinBoard board, PacketReader pvSrc )
{
BulletinMessage msg = World.FindItem( pvSrc.ReadInt32() ) as BulletinMessage;
if ( msg == null || msg.Parent != board )
return;
if ( from.AccessLevel < AccessLevel.GameMaster && msg.Poster != from )
return;
msg.Delete();
}
}
public struct BulletinEquip
{
public int itemID;
public int hue;
public BulletinEquip( int itemID, int hue )
{
this.itemID = itemID;
this.hue = hue;
}
}
public class BulletinMessage : Item
{
private Mobile m_Poster;
private string m_Subject;
private DateTime m_Time, m_LastPostTime;
private BulletinMessage m_Thread;
private string m_PostedName;
private int m_PostedBody;
private int m_PostedHue;
private BulletinEquip[] m_PostedEquip;
private string[] m_Lines;
public string GetTimeAsString()
{
return m_Time.ToString( "MMM dd, yyyy" );
}
public override bool CheckTarget( Mobile from, Server.Targeting.Target targ, object targeted )
{
return false;
}
public override bool IsAccessibleTo( Mobile check )
{
return false;
}
public BulletinMessage( Mobile poster, BulletinMessage thread, string subject, string[] lines ) : base( 0xEB0 )
{
Movable = false;
m_Poster = poster;
m_Subject = subject;
m_Time = DateTime.Now;
m_LastPostTime = m_Time;
m_Thread = thread;
m_PostedName = m_Poster.Name;
m_PostedBody = m_Poster.Body;
m_PostedHue = m_Poster.Hue;
m_Lines = lines;
List<BulletinEquip> list = new List<BulletinEquip>();
for ( int i = 0; i < poster.Items.Count; ++i )
{
Item item = poster.Items[i];
if ( item.Layer >= Layer.OneHanded && item.Layer <= Layer.Mount )
list.Add( new BulletinEquip( item.ItemID, item.Hue ) );
}
m_PostedEquip = list.ToArray();
}
public Mobile Poster{ get{ return m_Poster; } }
public BulletinMessage Thread{ get{ return m_Thread; } }
public string Subject{ get{ return m_Subject; } }
public DateTime Time{ get{ return m_Time; } }
public DateTime LastPostTime{ get{ return m_LastPostTime; } set{ m_LastPostTime = value; } }
public string PostedName{ get{ return m_PostedName; } }
public int PostedBody{ get{ return m_PostedBody; } }
public int PostedHue{ get{ return m_PostedHue; } }
public BulletinEquip[] PostedEquip{ get{ return m_PostedEquip; } }
public string[] Lines{ get{ return m_Lines; } }
public BulletinMessage( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 ); // version
writer.Write( (Mobile) m_Poster );
writer.Write( (string) m_Subject );
writer.Write( (DateTime) m_Time );
writer.Write( (DateTime) m_LastPostTime );
writer.Write( (bool) (m_Thread != null) );
writer.Write( (Item) m_Thread );
writer.Write( (string) m_PostedName );
writer.Write( (int) m_PostedBody );
writer.Write( (int) m_PostedHue );
writer.Write( (int) m_PostedEquip.Length );
for ( int i = 0; i < m_PostedEquip.Length; ++i )
{
writer.Write( (int) m_PostedEquip[i].itemID );
writer.Write( (int) m_PostedEquip[i].hue );
}
writer.Write( (int) m_Lines.Length );
for ( int i = 0; i < m_Lines.Length; ++i )
writer.Write( (string) m_Lines[i] );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 1:
case 0:
{
m_Poster = reader.ReadMobile();
m_Subject = reader.ReadString();
m_Time = reader.ReadDateTime();
m_LastPostTime = reader.ReadDateTime();
bool hasThread = reader.ReadBool();
m_Thread = reader.ReadItem() as BulletinMessage;
m_PostedName = reader.ReadString();
m_PostedBody = reader.ReadInt();
m_PostedHue = reader.ReadInt();
m_PostedEquip = new BulletinEquip[reader.ReadInt()];
for ( int i = 0; i < m_PostedEquip.Length; ++i )
{
m_PostedEquip[i].itemID = reader.ReadInt();
m_PostedEquip[i].hue = reader.ReadInt();
}
m_Lines = new string[reader.ReadInt()];
for ( int i = 0; i < m_Lines.Length; ++i )
m_Lines[i] = reader.ReadString();
if ( hasThread && m_Thread == null )
Delete();
if (version == 0)
ValidationQueue<BulletinMessage>.Add(this);
break;
}
}
}
public void Validate()
{
if (!(Parent is BulletinBoard && ((BulletinBoard)Parent).Items.Contains(this)))
Delete();
}
}
public class BBDisplayBoard : Packet
{
public BBDisplayBoard( BaseBulletinBoard board ) : base( 0x71 )
{
string name = board.BoardName;
if ( name == null )
name = "";
EnsureCapacity( 38 );
byte[] buffer = Utility.UTF8.GetBytes( name );
m_Stream.Write( (byte) 0x00 ); // PacketID
m_Stream.Write( (int) board.Serial ); // Bulletin board serial
// Bulletin board name
if ( buffer.Length >= 29 )
{
m_Stream.Write( buffer, 0, 29 );
m_Stream.Write( (byte) 0 );
}
else
{
m_Stream.Write( buffer, 0, buffer.Length );
m_Stream.Fill( 30 - buffer.Length );
}
}
}
public class BBMessageHeader : Packet
{
public BBMessageHeader( BaseBulletinBoard board, BulletinMessage msg ) : base( 0x71 )
{
string poster = SafeString( msg.PostedName );
string subject = SafeString( msg.Subject );
string time = SafeString( msg.GetTimeAsString() );
EnsureCapacity( 22 + poster.Length + subject.Length + time.Length );
m_Stream.Write( (byte) 0x01 ); // PacketID
m_Stream.Write( (int) board.Serial ); // Bulletin board serial
m_Stream.Write( (int) msg.Serial ); // Message serial
BulletinMessage thread = msg.Thread;
if ( thread == null )
m_Stream.Write( (int) 0 ); // Thread serial--root
else
m_Stream.Write( (int) thread.Serial ); // Thread serial--parent
WriteString( poster );
WriteString( subject );
WriteString( time );
}
public void WriteString( string v )
{
byte[] buffer = Utility.UTF8.GetBytes( v );
int len = buffer.Length + 1;
if ( len > 255 )
len = 255;
m_Stream.Write( (byte) len );
m_Stream.Write( buffer, 0, len-1 );
m_Stream.Write( (byte) 0 );
}
public string SafeString( string v )
{
if ( v == null )
return String.Empty;
return v;
}
}
public class BBMessageContent : Packet
{
public BBMessageContent( BaseBulletinBoard board, BulletinMessage msg ) : base( 0x71 )
{
string poster = SafeString( msg.PostedName );
string subject = SafeString( msg.Subject );
string time = SafeString( msg.GetTimeAsString() );
EnsureCapacity( 22 + poster.Length + subject.Length + time.Length );
m_Stream.Write( (byte) 0x02 ); // PacketID
m_Stream.Write( (int) board.Serial ); // Bulletin board serial
m_Stream.Write( (int) msg.Serial ); // Message serial
WriteString( poster );
WriteString( subject );
WriteString( time );
m_Stream.Write( (short) msg.PostedBody );
m_Stream.Write( (short) msg.PostedHue );
int len = msg.PostedEquip.Length;
if ( len > 255 )
len = 255;
m_Stream.Write((byte)len);
for (int i = 0; i < len; ++i)
WriteString(msg.Lines[i], true);
}
public void WriteString(string v)
{
WriteString(v, false);
}
public void WriteString(string v, bool padding)
{
byte[] buffer = Utility.UTF8.GetBytes(v);
int tail = padding ? 2 : 1;
int len = buffer.Length + tail;
if (len > 255)
len = 255;
m_Stream.Write((byte)len);
m_Stream.Write(buffer, 0, len - tail);
if (padding)
m_Stream.Write((short)0); // padding compensates for a client bug
else
m_Stream.Write((byte)0);
}
public string SafeString( string v )
{
if ( v == null )
return String.Empty;
return v;
}
}
}
| |
// 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\General\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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementByte0()
{
var test = new VectorGetAndWithElement__GetAndWithElementByte0();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementByte0
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Byte[] values = new Byte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetByte();
}
Vector256<Byte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]);
bool succeeded = !expectedOutOfRangeException;
try
{
Byte result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Byte insertedValue = TestLibrary.Generator.GetByte();
try
{
Vector256<Byte> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Byte[] values = new Byte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetByte();
}
Vector256<Byte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Byte)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Byte insertedValue = TestLibrary.Generator.GetByte();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(Byte))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<Byte>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Byte result, Byte[] values, [CallerMemberName] string method = "")
{
if (result != values[0])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<Byte> result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "")
{
Byte[] resultElements = new Byte[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Byte[] result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 0) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[0] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DeOps.Interface;
using DeOps.Interface.TLVex;
using DeOps.Interface.Views;
using DeOps.Implementation;
using DeOps.Implementation.Dht;
using DeOps.Implementation.Transport;
namespace DeOps.Services.Transfer
{
public partial class TransferView : CustomIconForm
{
public OpCore Core;
public TransferService Service;
Dictionary<ulong, TransferNode> TransferMap = new Dictionary<ulong, TransferNode>();
bool DefaultCollapse = true;
public static void Show(DhtNetwork network)
{
var form = new TransferView(network.Core.Transfers);
form.Show();
form.Activate();
}
public TransferView(TransferService service)
{
InitializeComponent();
Core = service.Core;
Service = service;
#if DEBUG
Service.Logging = true;
#endif
}
private void TransferView_Load(object sender, EventArgs e)
{
RefreshView();
Text = Core.GetName(Core.UserID) + "'s Transfers";
}
private void FastTimer_Tick(object sender, EventArgs e)
{
RefreshView();
}
private void RefreshView()
{
Dictionary<ulong, OpTransfer> displayMap = new Dictionary<ulong, OpTransfer>();
if (ShowDownloads.Checked)
foreach (OpTransfer download in Service.Transfers.Values.Where(t => t.Status != TransferStatus.Complete))
displayMap[download.FileID] = download;
if (ShowUploads.Checked)
foreach (OpTransfer upload in Service.Transfers.Values.Where(t => t.Status == TransferStatus.Complete))
displayMap[upload.FileID] = upload;
if (ShowPending.Checked)
foreach (OpTransfer pending in Service.Pending)
displayMap[pending.FileID] = pending;
if (ShowPartials.Checked)
foreach (OpTransfer partial in Service.Partials)
displayMap[partial.FileID] = partial;
// remove
var remove = (from TransferNode node in TransferList.Nodes
where !displayMap.ContainsKey(node.Transfer.FileID)
select node).ToList();
foreach (TransferNode node in remove)
{
TransferMap.Remove(node.Transfer.FileID);
TransferList.Nodes.Remove(node);
}
// add missing
var add = from transfer in displayMap.Values
where !TransferMap.ContainsKey(transfer.FileID)
select transfer;
foreach (OpTransfer transfer in add)
{
TransferNode node = new TransferNode(Service, transfer);
TransferMap[transfer.FileID] = node;
TransferList.Nodes.Add(node);
if(!DefaultCollapse)
node.Expand();
}
foreach (TransferNode transfer in TransferList.Nodes)
transfer.Refresh();
TransferList.Invalidate();
}
private void TransferList_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right)
return;
TreeListNode node = TransferList.GetNodeAt(e.Location) as TreeListNode;
if (node == null || node.GetType() != typeof(TransferNode))
return;
ContextMenuStripEx menu = new ContextMenuStripEx();
TransferNode transfer = node as TransferNode;
menu.Items.Add(new ToolStripMenuItem("Copy Hash to Clipboaard", null, (s, o) =>
{
Clipboard.SetText(Utilities.ToBase64String(transfer.Transfer.Details.Hash));
}));
menu.Show(TransferList, e.Location);
}
private void DownloadsCheck_CheckedChanged(object sender, EventArgs e)
{
RefreshView();
}
private void UploadsCheck_CheckedChanged(object sender, EventArgs e)
{
RefreshView();
}
private void PendingCheck_CheckedChanged(object sender, EventArgs e)
{
RefreshView();
}
private void PartialsCheck_CheckedChanged(object sender, EventArgs e)
{
RefreshView();
}
private void TransferView_FormClosing(object sender, FormClosingEventArgs e)
{
Service.Logging = false;
}
private void ExpandLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
DefaultCollapse = false;
foreach (TreeListNode node in TransferList.Nodes)
node.Expand();
}
private void CollapseLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
DefaultCollapse = true;
foreach (TreeListNode node in TransferList.Nodes)
node.Collapse();
}
}
public class TransferNode : TreeListNode
{
TransferService Service;
public OpTransfer Transfer;
BitfieldControl Bitfield = new BitfieldControl();
Dictionary<ulong, bool> PeerMap = new Dictionary<ulong, bool>();
public TransferNode(TransferService service, OpTransfer t)
{
Service = service;
Transfer = t;
SubItems.Add(Bitfield);
}
public void Refresh()
{
Bitfield.UpdateField(Transfer.LocalBitfield);
string text = "";
// set transfer text / columns
// time started, service, fileID, completed x of X
// flags: searching, file loaded, sub-hashes
text += Service.Core.Context.KnownServices[Transfer.Details.Service] + "-" + Transfer.FileID.ToString().Substring(0, 4) + ", ";
text += "Started: " + Transfer.Created.ToShortTimeString() + ", ";
if (Transfer.LocalBitfield != null)
text += Transfer.LocalBitfield.Length + " Pieces, ";
if (Transfer.Status == TransferStatus.Complete)
text += "Completed, ";
else
{
text += "Progress: " + Utilities.CommaIze(Transfer.GetProgress()) + " of " + Utilities.CommaIze(Transfer.Details.Size) + ", ";
}
if (Transfer.Searching)
text += "Searching, ";
if (Transfer.LocalFile == null)
text += "Unloaded, ";
Text = text.Substring(0, text.Length - 2);
// update sub items
var remove = (from PeerNode peer in Nodes
where !Transfer.Peers.ContainsKey(peer.RoutingID)
select peer).ToList();
foreach (PeerNode peer in remove)
{
PeerMap.Remove(peer.RoutingID);
Nodes.Remove(peer);
}
// add missing
var add = from peer in Transfer.Peers.Values
where !PeerMap.ContainsKey(peer.RoutingID)
select peer;
foreach (RemotePeer peer in add)
{
PeerMap[peer.RoutingID] = true;
Nodes.Add(new PeerNode(Service, peer.RoutingID));
}
foreach (PeerNode peer in Nodes)
peer.Refresh(Transfer);
}
}
public class PeerNode : TreeListNode
{
TransferService Service;
public ulong RoutingID;
BitfieldControl Bitfield = new BitfieldControl();
public PeerNode(TransferService service, ulong id)
{
Service = service;
RoutingID = id;
SubItems.Add(Bitfield);
}
public void Refresh(OpTransfer transfer)
{
if (!transfer.Peers.ContainsKey(RoutingID))
{
Text = "Error";
return;
}
RemotePeer peer = transfer.Peers[RoutingID];
int upPiece = -1, downPiece = -1;
string text = "";
// remote name / IP - last seen, timeout: x
// flags: UL (active?, chunk index, progress) / DL (chunk index, progress) / RBU
if (peer.DhtIndex < transfer.RoutingTable.Length && transfer.RoutingTable[peer.DhtIndex] == peer)
text += "(B" + peer.DhtIndex + ") ";
text += Service.Core.GetName(peer.Client.UserID) + ", ";
text += "Last Seen: " + peer.LastSeen.ToShortTimeString() + ", ";
//text += "Timeout: " + peer.PingTimeout + ", ";
if (peer.RemoteBitfieldUpdated)
text += "Out of Date, ";
if (Service.UploadPeers.ContainsKey(peer.RoutingID))
{
UploadPeer upload = Service.UploadPeers[peer.RoutingID];
text += "Last Upload: " + upload.LastAttempt.ToShortTimeString() + ", ";
if (upload.Active == peer)
{
text += "Upload: ";
if (upload.Active.LastRequest != null && upload.Active.CurrentPos != 0)
{
TransferRequest req = upload.Active.LastRequest;
upPiece = req.ChunkIndex;
int percent = (int) ((req.EndByte - upload.Active.CurrentPos) * 100 / (req.EndByte - req.StartByte));
// Piece 4 - 34%,
text += "Piece " + upPiece + " - " + percent + "%, ";
}
else
text += "Pending, ";
}
if(peer.LastError != null)
text += "Stopped: " + peer.LastError + ", ";
}
if(Service.DownloadPeers.ContainsKey(peer.RoutingID))
if (Service.DownloadPeers[peer.RoutingID].Requests.ContainsKey(transfer.FileID))
{
TransferRequest req = Service.DownloadPeers[peer.RoutingID].Requests[transfer.FileID];
text += "Download: ";
if (req.CurrentPos != 0)
{
downPiece = req.ChunkIndex;
int percent = (int)((req.EndByte - req.CurrentPos) * 100 / (req.EndByte - req.StartByte));
// Piece 4 - 34%,
text += "Piece " + downPiece + " - " + percent + "%, ";
}
else
text += "Pending, ";
}
Text = text.Substring(0, text.Length - 2);
Bitfield.UpdateField(peer.RemoteBitfield, upPiece, downPiece);
}
}
}
| |
#region License
/*
* HttpListenerResponse.cs
*
* This code is derived from System.Net.HttpListenerResponse.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-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
#region Authors
/*
* Authors:
* Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides access to a response to a request being processed by the
/// <see cref="HttpListener"/>.
/// </summary>
/// <remarks>
/// The HttpListenerResponse class cannot be inherited.
/// </remarks>
public sealed class HttpListenerResponse : IDisposable
{
#region Private Fields
private bool _chunked;
private Encoding _contentEncoding;
private long _contentLength;
private bool _contentLengthSet;
private string _contentType;
private HttpListenerContext _context;
private CookieCollection _cookies;
private bool _disposed;
private bool _forceCloseChunked;
private WebHeaderCollection _headers;
private bool _keepAlive;
private string _location;
private ResponseStream _outputStream;
private int _statusCode;
private string _statusDescription;
private Version _version;
#endregion
#region Internal Fields
internal bool HeadersSent;
#endregion
#region Internal Constructors
internal HttpListenerResponse (HttpListenerContext context)
{
_context = context;
_headers = new WebHeaderCollection ();
_keepAlive = true;
_statusCode = 200;
_statusDescription = "OK";
_version = HttpVersion.Version11;
}
#endregion
#region Internal Properties
internal bool ForceCloseChunked {
get {
return _forceCloseChunked;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the encoding that can be used with the entity body data
/// included in the response.
/// </summary>
/// <value>
/// A <see cref="Encoding"/> that represents the encoding that can be used
/// with the entity body data.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has been sent already.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public Encoding ContentEncoding {
get {
return _contentEncoding ?? (_contentEncoding = Encoding.Default);
}
set {
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException (
"Cannot be changed after headers are sent.");
_contentEncoding = value;
}
}
/// <summary>
/// Gets or sets the size of the entity body data included in the response.
/// </summary>
/// <value>
/// A <see cref="long"/> that represents the value of the Content-Length
/// entity-header field. The value is a number of bytes in the entity body
/// data.
/// </value>
/// <exception cref="ArgumentOutOfRangeException">
/// The value specified for a set operation is less than zero.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has been sent already.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public long ContentLength64 {
get {
return _contentLength;
}
set {
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException (
"Cannot be changed after headers are sent.");
if (value < 0)
throw new ArgumentOutOfRangeException (
"Must not be less than zero.", "value");
_contentLengthSet = true;
_contentLength = value;
}
}
/// <summary>
/// Gets or sets the media type of the entity body included in the response.
/// </summary>
/// <value>
/// The type of the content. A <see cref="string"/> that represents the value
/// of the Content-Type entity-header field.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation is empty.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The value specified for a set operation is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has been sent already.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public string ContentType {
get {
return _contentType;
}
set {
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException (
"Cannot be changed after headers are sent.");
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException (
"Must not be empty.", "value");
_contentType = value;
}
}
/// <summary>
/// Gets or sets the cookies returned with the response.
/// </summary>
/// <value>
/// A <see cref="CookieCollection"/> that contains the cookies returned with
/// the response.
/// </value>
public CookieCollection Cookies {
get {
return _cookies ?? (_cookies = new CookieCollection ());
}
set {
_cookies = value;
}
}
/// <summary>
/// Gets or sets the HTTP headers returned to the client.
/// </summary>
/// <value>
/// A <see cref="WebHeaderCollection"/> that contains the HTTP headers
/// returned to the client.
/// </value>
public WebHeaderCollection Headers {
get {
return _headers;
}
set {
/*
* "If you attempt to set a Content-Length, Keep-Alive, Transfer-Encoding,
* or WWW-Authenticate header using the Headers property, an exception
* will be thrown. Use the KeepAlive or ContentLength64 properties to set
* these headers. You cannot set the Transfer-Encoding or WWW-Authenticate
* headers manually."
*/
// TODO: Support for InvalidOperationException.
// TODO: Check if this is marked readonly after headers are sent.
_headers = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server requests a persistent
/// connection.
/// </summary>
/// <value>
/// <c>true</c> if the server requests a persistent connection; otherwise,
/// <c>false</c>. The default is <c>true</c>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has been sent already.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public bool KeepAlive {
get {
return _keepAlive;
}
set {
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException (
"Cannot be changed after headers are sent.");
_keepAlive = value;
}
}
/// <summary>
/// Gets a <see cref="Stream"/> to use to write the entity body data.
/// </summary>
/// <value>
/// A <see cref="Stream"/> to use to write the entity body data.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public Stream OutputStream {
get {
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
return _outputStream ??
(_outputStream = _context.Connection.GetResponseStream ());
}
}
/// <summary>
/// Gets or sets the HTTP version used in the response.
/// </summary>
/// <value>
/// A <see cref="Version"/> that represents the HTTP version used in the
/// response.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation doesn't have its <c>Major</c>
/// property set to 1 or doesn't have its <c>Minor</c> property set to
/// either 0 or 1.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The value specified for a set operation is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has been sent already.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public Version ProtocolVersion {
get {
return _version;
}
set {
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException (
"Cannot be changed after headers are sent.");
if (value == null)
throw new ArgumentNullException ("value");
if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1))
throw new ArgumentException ("Must be 1.0 or 1.1.", "value");
_version = value;
}
}
/// <summary>
/// Gets or sets the URL to which the client is redirected to locate
/// a requested resource.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Location
/// response-header field.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation is empty.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The response has been sent already.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public string RedirectLocation {
get {
return _location;
}
set {
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException (
"Cannot be changed after headers are sent.");
if (value.Length == 0)
throw new ArgumentException (
"Must not be empty.", "value");
_location = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the response uses the chunked
/// transfer encoding.
/// </summary>
/// <value>
/// <c>true</c> if the response uses the chunked transfer encoding;
/// otherwise, <c>false</c>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has been sent already.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public bool SendChunked {
get {
return _chunked;
}
set {
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException (
"Cannot be changed after headers are sent.");
_chunked = value;
}
}
/// <summary>
/// Gets or sets the HTTP status code returned to the client.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the HTTP status code for the
/// response to the request. The default is <see cref="HttpStatusCode.OK"/>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The response has been sent already.
/// </exception>
/// <exception cref="System.Net.ProtocolViolationException">
/// The value specified for a set operation is invalid. Valid values are
/// between 100 and 999.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public int StatusCode {
get {
return _statusCode;
}
set {
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (HeadersSent)
throw new InvalidOperationException (
"Cannot be changed after headers are sent.");
if (value < 100 || value > 999)
throw new System.Net.ProtocolViolationException (
"StatusCode must be between 100 and 999.");
_statusCode = value;
_statusDescription = value.GetStatusDescription ();
}
}
/// <summary>
/// Gets or sets the description of the HTTP status code returned to the
/// client.
/// </summary>
/// <value>
/// A <see cref="String"/> that represents the description of the HTTP status
/// code returned to the client.
/// </value>
public string StatusDescription {
get {
return _statusDescription;
}
set {
_statusDescription = value == null || value.Length == 0
? _statusCode.GetStatusDescription ()
: value;
}
}
#endregion
#region Private Methods
private bool canAddOrUpdate (Cookie cookie)
{
if (Cookies.Count == 0)
return true;
var found = findCookie (cookie);
if (found.Count () == 0)
return true;
foreach (var c in found)
if (c.Version == cookie.Version)
return true;
return false;
}
private void close (bool force)
{
_disposed = true;
_context.Connection.Close (force);
}
private IEnumerable<Cookie> findCookie (Cookie cookie)
{
var name = cookie.Name;
var domain = cookie.Domain;
var path = cookie.Path;
return from Cookie c in Cookies
where c.Name.Equals (name, StringComparison.OrdinalIgnoreCase) &&
c.Domain.Equals (domain, StringComparison.OrdinalIgnoreCase) &&
c.Path.Equals (path, StringComparison.Ordinal)
select c;
}
#endregion
#region Internal Methods
internal void SendHeaders (bool closing, MemoryStream stream)
{
if (_contentType != null) {
if (_contentEncoding != null &&
_contentType.IndexOf ("charset=", StringComparison.Ordinal) == -1) {
var charset = _contentEncoding.WebName;
_headers.SetInternal (
"Content-Type", _contentType + "; charset=" + charset, true);
}
else {
_headers.SetInternal ("Content-Type", _contentType, true);
}
}
if (_headers ["Server"] == null)
_headers.SetInternal ("Server", "websocket-sharp/1.0", true);
var provider = CultureInfo.InvariantCulture;
if (_headers ["Date"] == null)
_headers.SetInternal (
"Date", DateTime.UtcNow.ToString ("r", provider), true);
if (!_chunked) {
if (!_contentLengthSet && closing) {
_contentLengthSet = true;
_contentLength = 0;
}
if (_contentLengthSet)
_headers.SetInternal (
"Content-Length", _contentLength.ToString (provider), true);
}
var version = _context.Request.ProtocolVersion;
if (!_contentLengthSet && !_chunked && version >= HttpVersion.Version11)
_chunked = true;
/* Apache forces closing the connection for these status codes:
* HttpStatusCode.BadRequest 400
* HttpStatusCode.RequestTimeout 408
* HttpStatusCode.LengthRequired 411
* HttpStatusCode.RequestEntityTooLarge 413
* HttpStatusCode.RequestUriTooLong 414
* HttpStatusCode.InternalServerError 500
* HttpStatusCode.ServiceUnavailable 503
*/
var connClose = _statusCode == 400 ||
_statusCode == 408 ||
_statusCode == 411 ||
_statusCode == 413 ||
_statusCode == 414 ||
_statusCode == 500 ||
_statusCode == 503;
if (!connClose)
connClose = !_context.Request.KeepAlive;
// They sent both KeepAlive: true and Connection: close!?
if (!_keepAlive || connClose) {
_headers.SetInternal ("Connection", "close", true);
connClose = true;
}
if (_chunked)
_headers.SetInternal ("Transfer-Encoding", "chunked", true);
int reuses = _context.Connection.Reuses;
if (reuses >= 100) {
_forceCloseChunked = true;
if (!connClose) {
_headers.SetInternal ("Connection", "close", true);
connClose = true;
}
}
if (!connClose) {
_headers.SetInternal (
"Keep-Alive",
String.Format ("timeout=15,max={0}", 100 - reuses), true);
if (_context.Request.ProtocolVersion <= HttpVersion.Version10)
_headers.SetInternal ("Connection", "keep-alive", true);
}
if (_location != null)
_headers.SetInternal ("Location", _location, true);
if (_cookies != null) {
foreach (Cookie cookie in _cookies)
_headers.SetInternal ("Set-Cookie", cookie.ToResponseString (), true);
}
var encoding = _contentEncoding ?? Encoding.Default;
var writer = new StreamWriter (stream, encoding, 256);
writer.Write (
"HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription);
var headers = _headers.ToStringMultiValue (true);
writer.Write (headers);
writer.Flush ();
var preamble = encoding.CodePage == 65001 ? 3 : encoding.GetPreamble ().Length;
if (_outputStream == null)
_outputStream = _context.Connection.GetResponseStream ();
// Assumes that the stream was at position 0.
stream.Position = preamble;
HeadersSent = true;
}
#endregion
#region Public Methods
/// <summary>
/// Closes the connection to the client without sending a response.
/// </summary>
public void Abort ()
{
if (_disposed)
return;
close (true);
}
/// <summary>
/// Adds the specified HTTP header <paramref name="name"/> and
/// <paramref name="value"/> to the headers for this response.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that contains the name of the HTTP header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that contains the value of the HTTP header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
public void AddHeader (string name, string value)
{
if (name == null || name.Length == 0)
throw new ArgumentNullException ("name");
// TODO: Check for forbidden headers and invalid characters.
if (value.Length > 65535)
throw new ArgumentOutOfRangeException (
"value", "Greater than 65,535 characters.");
_headers.Set (name, value);
}
/// <summary>
/// Adds the specified <see cref="Cookie"/> to the <see cref="Cookies"/> sent
/// with the response.
/// </summary>
/// <param name="cookie">
/// A <see cref="Cookie"/> to add to the <see cref="Cookies"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
public void AppendCookie (Cookie cookie)
{
if (cookie == null)
throw new ArgumentNullException ("cookie");
Cookies.Add (cookie);
}
/// <summary>
/// Appends a <paramref name="value"/> to the specified HTTP header sent with
/// the response.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that contains the name of the HTTP header to
/// append <paramref name="value"/> to.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that contains the value to append to the HTTP
/// header.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
public void AppendHeader (string name, string value)
{
// TODO: Check for forbidden headers and invalid characters.
if (name == null || name.Length == 0)
throw new ArgumentException ("Must not be null or empty.", "name");
if (value.Length > 65535)
throw new ArgumentOutOfRangeException (
"value", "Greater than 65,535 characters.");
_headers.Add (name, value);
}
/// <summary>
/// Sends the response to the client and releases the resources associated
/// with the <see cref="HttpListenerResponse"/> instance.
/// </summary>
public void Close ()
{
if (_disposed)
return;
close (false);
}
/// <summary>
/// Sends the response with the specified array of <see cref="byte"/> to the
/// client and releases the resources associated with the
/// <see cref="HttpListenerResponse"/> instance.
/// </summary>
/// <param name="responseEntity">
/// An array of <see cref="byte"/> that contains the response entity body
/// data.
/// </param>
/// <param name="willBlock">
/// <c>true</c> if this method blocks execution while flushing the stream to
/// the client; otherwise, <c>false</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="responseEntity"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This object is closed.
/// </exception>
public void Close (byte [] responseEntity, bool willBlock)
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (responseEntity == null)
throw new ArgumentNullException ("responseEntity");
// TODO: If willBlock -> BeginWrite + Close?
ContentLength64 = responseEntity.Length;
OutputStream.Write (responseEntity, 0, (int) _contentLength);
close (false);
}
/// <summary>
/// Copies properties from the specified <see cref="HttpListenerResponse"/>
/// to this response.
/// </summary>
/// <param name="templateResponse">
/// A <see cref="HttpListenerResponse"/> to copy.
/// </param>
public void CopyFrom (HttpListenerResponse templateResponse)
{
_headers.Clear ();
_headers.Add (templateResponse._headers);
_contentLength = templateResponse._contentLength;
_statusCode = templateResponse._statusCode;
_statusDescription = templateResponse._statusDescription;
_keepAlive = templateResponse._keepAlive;
_version = templateResponse._version;
}
/// <summary>
/// Configures the response to redirect the client's request to the specified
/// <paramref name="url"/>.
/// </summary>
/// <param name="url">
/// A <see cref="string"/> that represents the URL to redirect the client's
/// request to.
/// </param>
public void Redirect (string url)
{
StatusCode = (int) HttpStatusCode.Redirect;
_location = url;
}
/// <summary>
/// Adds or updates a <see cref="Cookie"/> in the <see cref="Cookies"/> sent
/// with the response.
/// </summary>
/// <param name="cookie">
/// A <see cref="Cookie"/> to set.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="cookie"/> already exists in the <see cref="Cookies"/> and
/// could not be replaced.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
public void SetCookie (Cookie cookie)
{
if (cookie == null)
throw new ArgumentNullException ("cookie");
if (!canAddOrUpdate (cookie))
throw new ArgumentException ("Cannot be replaced.", "cookie");
Cookies.Add (cookie);
}
#endregion
#region Explicit Interface Implementation
/// <summary>
/// Releases all resource used by the <see cref="HttpListenerResponse"/>.
/// </summary>
void IDisposable.Dispose ()
{
// TODO: Abort or Close?
close (true);
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.